Elgg  Version 2.2
 All Classes Namespaces Files Functions Variables Pages
elgglib.php
Go to the documentation of this file.
1 <?php
2 
4 
19 function elgg() {
21 }
22 
34 function elgg_register_library($name, $location) {
35  $config = _elgg_services()->config;
36 
37  $libraries = $config->get('libraries');
38  if ($libraries === null) {
39  $libraries = array();
40  }
41  $libraries[$name] = $location;
42  $config->set('libraries', $libraries);
43 }
44 
57  static $loaded_libraries = array();
58 
59  if (in_array($name, $loaded_libraries)) {
60  return;
61  }
62 
63  $libraries = _elgg_services()->config->get('libraries');
64 
65  if (!isset($libraries[$name])) {
66  $error = "$name is not a registered library";
67  throw new \InvalidParameterException($error);
68  }
69 
70  if (!include_once($libraries[$name])) {
71  $error = "Could not load the $name library from {$libraries[$name]}";
72  throw new \InvalidParameterException($error);
73  }
74 
75  $loaded_libraries[] = $name;
76 }
77 
93 function forward($location = "", $reason = 'system') {
94  if (!headers_sent($file, $line)) {
95  if ($location === REFERER) {
96  $location = _elgg_services()->request->headers->get('Referer');
97  }
98 
99  $location = elgg_normalize_url($location);
100 
101  // return new forward location or false to stop the forward or empty string to exit
103  $params = array('current_url' => $current_page, 'forward_url' => $location);
104  $location = elgg_trigger_plugin_hook('forward', $reason, $params, $location);
105 
106  if ($location) {
107  header("Location: {$location}");
108  }
109  exit;
110  } else {
111  throw new \SecurityException("Redirect could not be issued due to headers already being sent. Halting execution for security. "
112  . "Output started in file $file at line $line. Search http://learn.elgg.org/ for more information.");
113  }
114 }
115 
143 function elgg_register_js($name, $url, $location = 'head', $priority = null) {
144  return elgg_register_external_file('js', $name, $url, $location, $priority);
145 }
146 
171 function elgg_define_js($name, $config) {
172  $src = elgg_extract('src', $config);
173 
174  if ($src) {
176  _elgg_services()->amdConfig->addPath($name, $url);
177  }
178 
179  // shimmed module
180  if (isset($config['deps']) || isset($config['exports'])) {
181  _elgg_services()->amdConfig->addShim($name, $config);
182  }
183 }
184 
194  return elgg_unregister_external_file('js', $name);
195 }
196 
208 function elgg_load_js($name) {
210 }
211 
212 
221  _elgg_services()->amdConfig->addDependency($name);
222 }
223 
234  _elgg_services()->amdConfig->removeDependency($name);
235 }
236 
245 function elgg_get_loaded_js($location = 'head') {
246  return elgg_get_loaded_external_files('js', $location);
247 }
248 
259 function elgg_register_css($name, $url, $priority = null) {
260  return elgg_register_external_file('css', $name, $url, 'head', $priority);
261 }
262 
272  return elgg_unregister_external_file('css', $name);
273 }
274 
286 function elgg_load_css($name) {
288 }
289 
297  return elgg_get_loaded_external_files('css', 'head');
298 }
299 
312 function elgg_register_external_file($type, $name, $url, $location, $priority = 500) {
313  return _elgg_services()->externalFiles->register($type, $name, $url, $location, $priority);
314 }
315 
326  return _elgg_services()->externalFiles->unregister($type, $name);
327 }
328 
339  return _elgg_services()->externalFiles->load($type, $name);
340 }
341 
351 function elgg_get_loaded_external_files($type, $location) {
352  return _elgg_services()->externalFiles->getLoadedFiles($type, $location);
353 }
354 
367 function elgg_get_file_list($directory, $exceptions = array(), $list = array(),
368 $extensions = null) {
369 
370  $directory = sanitise_filepath($directory);
371  if ($handle = opendir($directory)) {
372  while (($file = readdir($handle)) !== false) {
373  if (!is_file($directory . $file) || in_array($file, $exceptions)) {
374  continue;
375  }
376 
377  if (is_array($extensions)) {
378  if (in_array(strrchr($file, '.'), $extensions)) {
379  $list[] = $directory . $file;
380  }
381  } else {
382  $list[] = $directory . $file;
383  }
384  }
385  closedir($handle);
386  }
387 
388  return $list;
389 }
390 
399 function sanitise_filepath($path, $append_slash = true) {
400  // Convert to correct UNIX paths
401  $path = str_replace('\\', '/', $path);
402  $path = str_replace('../', '/', $path);
403  // replace // with / except when preceeded by :
404  $path = preg_replace("/([^:])\/\//", "$1/", $path);
405 
406  // Sort trailing slash
407  $path = trim($path);
408  // rtrim defaults plus /
409  $path = rtrim($path, " \n\t\0\x0B/");
410 
411  if ($append_slash) {
412  $path = $path . '/';
413  }
414 
415  return $path;
416 }
417 
425 function count_messages($register = "") {
426  return _elgg_services()->systemMessages->count($register);
427 }
428 
439  _elgg_services()->systemMessages->addSuccessMessage($message);
440  return true;
441 }
442 
453  _elgg_services()->systemMessages->addErrorMessage($error);
454  return true;
455 }
456 
464  return _elgg_services()->systemMessages->loadRegisters();
465 }
466 
474 function elgg_set_system_messages(\Elgg\SystemMessages\RegisterSet $set) {
475  _elgg_services()->systemMessages->saveRegisters($set);
476 }
477 
538 function elgg_register_event_handler($event, $object_type, $callback, $priority = 500) {
539  return _elgg_services()->events->registerHandler($event, $object_type, $callback, $priority);
540 }
541 
552 function elgg_unregister_event_handler($event, $object_type, $callback) {
553  return _elgg_services()->events->unregisterHandler($event, $object_type, $callback);
554 }
555 
589 function elgg_trigger_event($event, $object_type, $object = null) {
590  return _elgg_services()->events->trigger($event, $object_type, $object);
591 }
592 
610 function elgg_trigger_before_event($event, $object_type, $object = null) {
611  return _elgg_services()->events->triggerBefore($event, $object_type, $object);
612 }
613 
629 function elgg_trigger_after_event($event, $object_type, $object = null) {
630  return _elgg_services()->events->triggerAfter($event, $object_type, $object);
631 }
632 
646 function elgg_trigger_deprecated_event($event, $object_type, $object = null, $message, $version) {
647  return _elgg_services()->events->triggerDeprecated($event, $object_type, $object, $message, $version);
648 }
649 
715 function elgg_register_plugin_hook_handler($hook, $type, $callback, $priority = 500) {
716  return _elgg_services()->hooks->registerHandler($hook, $type, $callback, $priority);
717 }
718 
730 function elgg_unregister_plugin_hook_handler($hook, $entity_type, $callback) {
731  _elgg_services()->hooks->unregisterHandler($hook, $entity_type, $callback);
732 }
733 
744  _elgg_services()->hooks->clearHandlers($hook, $type);
745 }
746 
801 function elgg_trigger_plugin_hook($hook, $type, $params = null, $returnvalue = null) {
802  return _elgg_services()->hooks->trigger($hook, $type, $params, $returnvalue);
803 }
804 
816  return _elgg_services()->hooks->getOrderedHandlers($hook, $type);
817 }
818 
830  return _elgg_services()->events->getOrderedHandlers($event, $type);
831 }
832 
851  $timestamp = time();
852  error_log("Exception at time $timestamp: $exception");
853 
854  // Wipe any existing output buffer
855  ob_end_clean();
856 
857  // make sure the error isn't cached
858  header("Cache-Control: no-cache, must-revalidate", true);
859  header('Expires: Fri, 05 Feb 1982 00:00:00 -0500', true);
860 
861  // we don't want the 'pagesetup', 'system' event to fire
862  global $CONFIG;
863  $GLOBALS['_ELGG']->pagesetupdone = true;
864 
865  try {
866  // allow custom scripts to trigger on exception
867  // $CONFIG->exception_include can be set locally in settings.php
868  // value should be a system path to a file to include
869  if (!empty($CONFIG->exception_include) && is_file($CONFIG->exception_include)) {
870  ob_start();
871  include $CONFIG->exception_include;
872  $exception_output = ob_get_clean();
873 
874  // if content is returned from the custom handler we will output
875  // that instead of our default failsafe view
876  if (!empty($exception_output)) {
877  echo $exception_output;
878  exit;
879  }
880  }
881 
882  if (elgg_is_xhr()) {
883  elgg_set_viewtype('json');
884  $response = new \Symfony\Component\HttpFoundation\JsonResponse(null, 500);
885  } else {
886  elgg_set_viewtype('failsafe');
887  $response = new \Symfony\Component\HttpFoundation\Response('', 500);
888  }
889 
890  if (elgg_is_admin_logged_in()) {
891  $body = elgg_view("messages/exceptions/admin_exception", array(
892  'object' => $exception,
893  'ts' => $timestamp
894  ));
895  } else {
896  $body = elgg_view("messages/exceptions/exception", array(
897  'object' => $exception,
898  'ts' => $timestamp
899  ));
900  }
901 
902  $response->setContent(elgg_view_page(elgg_echo('exception:title'), $body));
903  $response->send();
904  } catch (Exception $e) {
905  $timestamp = time();
906  $message = $e->getMessage();
907  http_response_code(500);
908  echo "Fatal error in exception handler. Check log for Exception at time $timestamp";
909  error_log("Exception at time $timestamp : fatal error in exception handler : $message");
910  }
911 }
912 
936 function _elgg_php_error_handler($errno, $errmsg, $filename, $linenum, $vars) {
937 
938  // Elgg 2.0 no longer uses ext/mysql, so these warnings are just a nuisance for 1.x site
939  // owners and plugin devs.
940  if (0 === strpos($errmsg, "mysql_connect(): The mysql extension is deprecated")) {
941  // only suppress core's usage
942  if (preg_match('~/classes/Elgg/Database\.php$~', strtr($filename, '\\', '/'))) {
943  return true;
944  }
945  }
946 
947  $error = date("Y-m-d H:i:s (T)") . ": \"$errmsg\" in file $filename (line $linenum)";
948 
949  switch ($errno) {
950  case E_USER_ERROR:
951  if (!elgg_log("PHP: $error", 'ERROR')) {
952  error_log("PHP ERROR: $error");
953  }
954  register_error("ERROR: $error");
955 
956  // Since this is a fatal error, we want to stop any further execution but do so gracefully.
957  throw new \Exception($error);
958  break;
959 
960  case E_WARNING :
961  case E_USER_WARNING :
962  case E_RECOVERABLE_ERROR: // (e.g. type hint violation)
963 
964  // check if the error wasn't suppressed by the error control operator (@)
965  if (error_reporting() && !elgg_log("PHP: $error", 'WARNING')) {
966  error_log("PHP WARNING: $error");
967  }
968  break;
969 
970  default:
971  global $CONFIG;
972  if (isset($CONFIG->debug) && $CONFIG->debug === 'NOTICE') {
973  if (!elgg_log("PHP (errno $errno): $error", 'NOTICE')) {
974  error_log("PHP NOTICE: $error");
975  }
976  }
977  }
978 
979  return true;
980 }
981 
982 
1000 function elgg_log($message, $level = 'NOTICE') {
1001  static $levels = array(
1002  'INFO' => 200,
1003  'NOTICE' => 250,
1004  'WARNING' => 300,
1005  'DEBUG' => 300,
1006  'ERROR' => 400,
1007  );
1008 
1009  if ($level == 'DEBUG') {
1010  elgg_deprecated_notice("The 'DEBUG' level for logging has been deprecated.", 1.9);
1011  }
1012 
1013  $level = $levels[$level];
1014  return _elgg_services()->logger->log($message, $level);
1015 }
1016 
1031 function elgg_dump($value, $to_screen = true) {
1032  _elgg_services()->logger->dump($value, $to_screen);
1033 }
1034 
1043 function elgg_get_version($human_readable = false) {
1044  static $version, $release;
1045 
1046  if (!isset($version) || !isset($release)) {
1047  $path = \Elgg\Application::elggDir()->getPath('version.php');
1048  if (!is_file($path)) {
1049  return false;
1050  }
1051  include $path;
1052  }
1053 
1054  return $human_readable ? $release : $version;
1055 }
1056 
1070 function elgg_deprecated_notice($msg, $dep_version, $backtrace_level = 1) {
1071  $backtrace_level += 1;
1072  return _elgg_services()->deprecation->sendNotice($msg, $dep_version, $backtrace_level);
1073 }
1074 
1088 function elgg_http_build_url(array $parts, $html_encode = true) {
1089  // build only what's given to us.
1090  $scheme = isset($parts['scheme']) ? "{$parts['scheme']}://" : '';
1091  $host = isset($parts['host']) ? "{$parts['host']}" : '';
1092  $port = isset($parts['port']) ? ":{$parts['port']}" : '';
1093  $path = isset($parts['path']) ? "{$parts['path']}" : '';
1094  $query = isset($parts['query']) ? "?{$parts['query']}" : '';
1095  $fragment = isset($parts['fragment']) ? "#{$parts['fragment']}" : '';
1096 
1097  $string = $scheme . $host . $port . $path . $query . $fragment;
1098 
1099  if ($html_encode) {
1100  return elgg_format_url($string);
1101  } else {
1102  return $string;
1103  }
1104 }
1105 
1123 function elgg_add_action_tokens_to_url($url, $html_encode = false) {
1125  $components = parse_url($url);
1126 
1127  if (isset($components['query'])) {
1128  $query = elgg_parse_str($components['query']);
1129  } else {
1130  $query = array();
1131  }
1132 
1133  if (isset($query['__elgg_ts']) && isset($query['__elgg_token'])) {
1134  return $url;
1135  }
1136 
1137  // append action tokens to the existing query
1138  $query['__elgg_ts'] = time();
1139  $query['__elgg_token'] = generate_action_token($query['__elgg_ts']);
1140  $components['query'] = http_build_query($query);
1141 
1142  // rebuild the full url
1143  return elgg_http_build_url($components, $html_encode);
1144 }
1145 
1158  return elgg_http_add_url_query_elements($url, array($element => null));
1159 }
1160 
1171 function elgg_http_add_url_query_elements($url, array $elements) {
1172  $url_array = parse_url($url);
1173 
1174  if (isset($url_array['query'])) {
1175  $query = elgg_parse_str($url_array['query']);
1176  } else {
1177  $query = array();
1178  }
1179 
1180  foreach ($elements as $k => $v) {
1181  if ($v === null) {
1182  unset($query[$k]);
1183  } else {
1184  $query[$k] = $v;
1185  }
1186  }
1187 
1188  // why check path? A: if no path, this may be a relative URL like "?foo=1". In this case,
1189  // the output "" would be interpreted the current URL, so in this case we *must* set
1190  // a query to make sure elements are removed.
1191  if ($query || empty($url_array['path'])) {
1192  $url_array['query'] = http_build_query($query);
1193  } else {
1194  unset($url_array['query']);
1195  }
1196  $string = elgg_http_build_url($url_array, false);
1197 
1198  return $string;
1199 }
1200 
1215 function elgg_http_url_is_identical($url1, $url2, $ignore_params = array('offset', 'limit')) {
1216  $url1 = elgg_normalize_url($url1);
1217  $url2 = elgg_normalize_url($url2);
1218 
1219  // @todo - should probably do something with relative URLs
1220 
1221  if ($url1 == $url2) {
1222  return true;
1223  }
1224 
1225  $url1_info = parse_url($url1);
1226  $url2_info = parse_url($url2);
1227 
1228  if (isset($url1_info['path'])) {
1229  $url1_info['path'] = trim($url1_info['path'], '/');
1230  }
1231  if (isset($url2_info['path'])) {
1232  $url2_info['path'] = trim($url2_info['path'], '/');
1233  }
1234 
1235  // compare basic bits
1236  $parts = array('scheme', 'host', 'path');
1237 
1238  foreach ($parts as $part) {
1239  if ((isset($url1_info[$part]) && isset($url2_info[$part]))
1240  && $url1_info[$part] != $url2_info[$part]) {
1241  return false;
1242  } elseif (isset($url1_info[$part]) && !isset($url2_info[$part])) {
1243  return false;
1244  } elseif (!isset($url1_info[$part]) && isset($url2_info[$part])) {
1245  return false;
1246  }
1247  }
1248 
1249  // quick compare of get params
1250  if (isset($url1_info['query']) && isset($url2_info['query'])
1251  && $url1_info['query'] == $url2_info['query']) {
1252  return true;
1253  }
1254 
1255  // compare get params that might be out of order
1256  $url1_params = array();
1257  $url2_params = array();
1258 
1259  if (isset($url1_info['query'])) {
1260  if ($url1_info['query'] = html_entity_decode($url1_info['query'])) {
1261  $url1_params = elgg_parse_str($url1_info['query']);
1262  }
1263  }
1264 
1265  if (isset($url2_info['query'])) {
1266  if ($url2_info['query'] = html_entity_decode($url2_info['query'])) {
1267  $url2_params = elgg_parse_str($url2_info['query']);
1268  }
1269  }
1270 
1271  // drop ignored params
1272  foreach ($ignore_params as $param) {
1273  if (isset($url1_params[$param])) {
1274  unset($url1_params[$param]);
1275  }
1276  if (isset($url2_params[$param])) {
1277  unset($url2_params[$param]);
1278  }
1279  }
1280 
1281  // array_diff_assoc only returns the items in arr1 that aren't in arrN
1282  // but not the items that ARE in arrN but NOT in arr1
1283  // if arr1 is an empty array, this function will return 0 no matter what.
1284  // since we only care if they're different and not how different,
1285  // add the results together to get a non-zero (ie, different) result
1286  $diff_count = count(array_diff_assoc($url1_params, $url2_params));
1287  $diff_count += count(array_diff_assoc($url2_params, $url1_params));
1288  if ($diff_count > 0) {
1289  return false;
1290  }
1291 
1292  return true;
1293 }
1294 
1310 function elgg_extract($key, $array, $default = null, $strict = true) {
1311  if (!is_array($array)) {
1312  return $default;
1313  }
1314 
1315  if ($strict) {
1316  return (isset($array[$key])) ? $array[$key] : $default;
1317  } else {
1318  return (isset($array[$key]) && !empty($array[$key])) ? $array[$key] : $default;
1319  }
1320 }
1321 
1342 function elgg_sort_3d_array_by_value(&$array, $element, $sort_order = SORT_ASC,
1343 $sort_type = SORT_LOCALE_STRING) {
1344 
1345  $sort = array();
1346 
1347  foreach ($array as $v) {
1348  if (isset($v[$element])) {
1349  $sort[] = strtolower($v[$element]);
1350  } else {
1351  $sort[] = null;
1352  }
1353  };
1354 
1355  return array_multisort($sort, $sort_order, $sort_type, $array);
1356 }
1357 
1368 function ini_get_bool($ini_get_arg) {
1369  $temp = strtolower(ini_get($ini_get_arg));
1370 
1371  if ($temp == '1' || $temp == 'on' || $temp == 'true') {
1372  return true;
1373  }
1374  return false;
1375 }
1376 
1388 function elgg_get_ini_setting_in_bytes($setting) {
1389  // retrieve INI setting
1390  $val = ini_get($setting);
1391 
1392  // convert INI setting when shorthand notation is used
1393  $last = strtolower($val[strlen($val) - 1]);
1394  switch($last) {
1395  case 'g':
1396  $val *= 1024;
1397  // fallthrough intentional
1398  case 'm':
1399  $val *= 1024;
1400  // fallthrough intentional
1401  case 'k':
1402  $val *= 1024;
1403  }
1404 
1405  // return byte value
1406  return $val;
1407 }
1408 
1420  if (($string === '') || ($string === false) || ($string === null)) {
1421  return false;
1422  }
1423 
1424  return true;
1425 }
1426 
1441  foreach ($singulars as $singular) {
1442  $plural = $singular . 's';
1443 
1444  if (array_key_exists($singular, $options)) {
1445  if ($options[$singular] === ELGG_ENTITIES_ANY_VALUE) {
1446  $options[$plural] = $options[$singular];
1447  } else {
1448  // Test for array refs #2641
1449  if (!is_array($options[$singular])) {
1450  $options[$plural] = array($options[$singular]);
1451  } else {
1452  $options[$plural] = $options[$singular];
1453  }
1454  }
1455  }
1456 
1457  unset($options[$singular]);
1458  }
1459 
1460  return $options;
1461 }
1462 
1481  try {
1482  _elgg_services()->logger->setDisplay(false);
1483  elgg_trigger_event('shutdown', 'system');
1484 
1485  $time = (float)(microtime(true) - $GLOBALS['START_MICROTIME']);
1486  $uri = _elgg_services()->request->server->get('REQUEST_URI', 'CLI');
1487  // demoted to NOTICE from DEBUG so javascript is not corrupted
1488  elgg_log("Page {$uri} generated in $time seconds", 'INFO');
1489  } catch (Exception $e) {
1490  $message = 'Error: ' . get_class($e) . ' thrown within the shutdown handler. ';
1491  $message .= "Message: '{$e->getMessage()}' in file {$e->getFile()} (line {$e->getLine()})";
1492  error_log($message);
1493  error_log("Exception trace stack: {$e->getTraceAsString()}");
1494  }
1495 
1496  // Prevent an APC session bug: https://bugs.php.net/bug.php?id=60657
1497  session_write_close();
1498 }
1499 
1512 function _elgg_js_page_handler($page) {
1513  return _elgg_cacheable_view_page_handler($page, 'js');
1514 }
1515 
1529 function _elgg_ajax_page_handler($segments) {
1530  elgg_ajax_gatekeeper();
1531 
1532  if (count($segments) < 2) {
1533  return false;
1534  }
1535 
1536  if ($segments[0] === 'view' || $segments[0] === 'form') {
1537  if ($segments[0] === 'view') {
1538  // ignore 'view/'
1539  $view = implode('/', array_slice($segments, 1));
1540  } else {
1541  // form views start with "forms", not "form"
1542  $view = 'forms/' . implode('/', array_slice($segments, 1));
1543  }
1544 
1545  $allowed_views = $GLOBALS['_ELGG']->allowed_ajax_views;
1546  $ajax_api = _elgg_services()->ajax;
1547 
1548  // cacheable views are always allowed
1549  if (!array_key_exists($view, $allowed_views) && !_elgg_services()->views->isCacheableView($view)) {
1550  if ($ajax_api->isReady()) {
1551  $ajax_api->respondWithError("Ajax view '$view' was not registered");
1552  return true;
1553  }
1554 
1555  // legacy XHR behavior
1556  header('HTTP/1.1 403 Forbidden');
1557  exit;
1558  }
1559 
1560  // pull out GET parameters through filter
1561  $vars = array();
1562  foreach (_elgg_services()->request->query->keys() as $name) {
1563  $vars[$name] = get_input($name);
1564  }
1565 
1566  if (isset($vars['guid'])) {
1567  $vars['entity'] = get_entity($vars['guid']);
1568  }
1569 
1570  $content_type = '';
1571  if ($segments[0] === 'view') {
1573  $ajax_hook_type = "view:$view";
1574 
1575  // Try to guess the mime-type
1576  switch ($segments[1]) {
1577  case "js":
1578  $content_type = 'text/javascript';
1579  break;
1580  case "css":
1581  $content_type = 'text/css';
1582  break;
1583  }
1584  } else {
1585  $action = implode('/', array_slice($segments, 1));
1586  $output = elgg_view_form($action, array(), $vars);
1587  $ajax_hook_type = "form:$action";
1588  }
1589 
1590  if ($ajax_api->isReady()) {
1591  $ajax_api->respondFromOutput($output, $ajax_hook_type);
1592  return true;
1593  }
1594 
1595  // legacy XHR behavior
1596  if ($content_type) {
1597  header("Content-Type: $content_type;charset=utf-8");
1598  }
1599  echo $output;
1600  return true;
1601  }
1602 
1603  return false;
1604 }
1605 
1617 function _elgg_css_page_handler($page) {
1618  if (!isset($page[0])) {
1619  // default css
1620  $page[0] = 'elgg';
1621  }
1622 
1623  return _elgg_cacheable_view_page_handler($page, 'css');
1624 }
1625 
1634 function _elgg_favicon_page_handler($segments) {
1635  header("HTTP/1.1 404 Not Found", true, 404);
1636 
1637  header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', strtotime("+1 week")), true);
1638  header("Pragma: public", true);
1639  header("Cache-Control: public", true);
1640 
1641  // TODO in next 1.x send our default icon
1642  //header('Content-Type: image/x-icon');
1643  //echo elgg_view('favicon.ico');
1644 
1645  return true;
1646 }
1647 
1661 
1662  switch ($type) {
1663  case 'js':
1664  $content_type = 'text/javascript';
1665  break;
1666 
1667  case 'css':
1668  $content_type = 'text/css';
1669  break;
1670 
1671  default:
1672  return false;
1673  break;
1674  }
1675 
1676  if ($page) {
1677  // the view file names can have multiple dots
1678  // eg: views/default/js/calendars/jquery.fullcalendar.min.php
1679  // translates to the url /js/<ts>/calendars/jquery.fullcalendar.min.js
1680  // and the view js/calendars/jquery.fullcalendar.min
1681  // we ignore the last two dots for the ts and the ext.
1682  // Additionally, the timestamp is optional.
1683  $page = implode('/', $page);
1684  $regex = '|(.+?)\.\w+$|';
1685  if (!preg_match($regex, $page, $matches)) {
1686  return false;
1687  }
1688  $view = "$type/{$matches[1]}";
1689  if (!elgg_view_exists($view)) {
1690  return false;
1691  }
1692 
1693  $msg = 'URLs starting with /js/ and /css/ are deprecated. Use elgg_get_simplecache_url().';
1694  elgg_deprecated_notice($msg, '2.1');
1695 
1696  $return = elgg_view($view);
1697 
1698  header("Content-type: $content_type;charset=utf-8");
1699 
1700  // @todo should js be cached when simple cache turned off
1701  //header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', strtotime("+10 days")), true);
1702  //header("Pragma: public");
1703  //header("Cache-Control: public");
1704  //header("Content-Length: " . strlen($return));
1705 
1706  echo $return;
1707  return true;
1708  }
1709  return false;
1710 }
1711 
1724  $order_by = strtolower($order_by);
1725 
1726  if (strpos($order_by, ' asc') !== false) {
1727  $return = str_replace(' asc', ' desc', $order_by);
1728  } elseif (strpos($order_by, ' desc') !== false) {
1729  $return = str_replace(' desc', ' asc', $order_by);
1730  } else {
1731  // no order specified, so default to desc since mysql defaults to asc
1732  $return = $order_by . ' desc';
1733  }
1734 
1735  return $return;
1736 }
1737 
1750  // our db functions return the number of rows affected...
1751  return $object->enable() ? true : false;
1752 }
1753 
1764  // our db functions return the number of rows affected...
1765  return $object->disable() ? true : false;
1766 }
1767 
1778  // our db functions return the number of rows affected...
1779  return $object->delete() ? true : false;
1780 }
1781 
1792  if (!$options || !is_array($options)) {
1793  return false;
1794  }
1795 
1796  // at least one of these is required.
1797  $required = array(
1798  // generic restraints
1799  'guid', 'guids'
1800  );
1801 
1802  switch ($type) {
1803  case 'metadata':
1804  $metadata_required = array(
1805  'metadata_owner_guid', 'metadata_owner_guids',
1806  'metadata_name', 'metadata_names',
1807  'metadata_value', 'metadata_values'
1808  );
1809 
1810  $required = array_merge($required, $metadata_required);
1811  break;
1812 
1813  case 'annotations':
1814  case 'annotation':
1815  $annotations_required = array(
1816  'annotation_owner_guid', 'annotation_owner_guids',
1817  'annotation_name', 'annotation_names',
1818  'annotation_value', 'annotation_values'
1819  );
1820 
1821  $required = array_merge($required, $annotations_required);
1822  break;
1823 
1824  default:
1825  return false;
1826  }
1827 
1828  foreach ($required as $key) {
1829  // check that it exists and is something.
1830  if (isset($options[$key]) && $options[$key]) {
1831  return true;
1832  }
1833  }
1834 
1835  return false;
1836 }
1837 
1845  echo elgg_view_resource('walled_garden');
1846  return true;
1847 }
1848 
1849 
1858  $view = $page[0];
1859  if (!elgg_view_exists("core/walled_garden/$view")) {
1860  return false;
1861  }
1862  $params = array(
1863  'content' => elgg_view("core/walled_garden/$view"),
1864  'class' => 'elgg-walledgarden-single hidden',
1865  'id' => str_replace('_', '-', "elgg-walledgarden-$view"),
1866  );
1867  echo elgg_view_layout('walled_garden', $params);
1868  return true;
1869 }
1870 
1885  global $CONFIG;
1886 
1887  elgg_register_css('elgg.walled_garden', elgg_get_simplecache_url('walled_garden.css'));
1888  elgg_register_js('elgg.walled_garden', elgg_get_simplecache_url('walled_garden.js'));
1889 
1890  elgg_register_page_handler('walled_garden', '_elgg_walled_garden_ajax_handler');
1891 
1892  // check for external page view
1893  if (isset($CONFIG->site) && $CONFIG->site instanceof \ElggSite) {
1894  $CONFIG->site->checkWalledGarden();
1895  }
1896 }
1897 
1908  if (isset($accesses[ACCESS_PUBLIC])) {
1909  unset($accesses[ACCESS_PUBLIC]);
1910  }
1911  return $accesses;
1912 }
1913 
1923 function _elgg_init() {
1924  elgg_register_action('entity/delete');
1925  elgg_register_action('comment/save');
1926  elgg_register_action('comment/delete');
1927 
1928  elgg_register_page_handler('js', '_elgg_js_page_handler');
1929  elgg_register_page_handler('css', '_elgg_css_page_handler');
1930  elgg_register_page_handler('ajax', '_elgg_ajax_page_handler');
1931  elgg_register_page_handler('favicon.ico', '_elgg_favicon_page_handler');
1932 
1933  elgg_register_page_handler('manifest.json', function() {
1935  $resource = new \Elgg\Http\WebAppManifestResource($site);
1936  header('Content-Type: application/json;charset=utf-8');
1937  echo json_encode($resource->get());
1938  return true;
1939  });
1940 
1941  elgg_register_plugin_hook_handler('head', 'page', function($hook, $type, array $result) {
1942  $result['links']['manifest'] = [
1943  'rel' => 'manifest',
1944  'href' => elgg_normalize_url('/manifest.json'),
1945  ];
1946 
1947  return $result;
1948  });
1949 
1950  if (_elgg_services()->config->getVolatile('enable_profiling')) {
1954  elgg_register_plugin_hook_handler('output', 'page', [\Elgg\Profiler::class, 'handlePageOutput'], 999);
1955  }
1956 }
1957 
1970 function _elgg_api_test($hook, $type, $value, $params) {
1971  global $CONFIG;
1972  $value[] = $CONFIG->path . 'engine/tests/ElggTravisInstallTest.php';
1973  $value[] = $CONFIG->path . 'engine/tests/ElggCoreHelpersTest.php';
1974  $value[] = $CONFIG->path . 'engine/tests/ElggCoreRegressionBugsTest.php';
1975  $value[] = $CONFIG->path . 'engine/tests/ElggBatchTest.php';
1976  return $value;
1977 }
1978 
1987 define('ACCESS_DEFAULT', -1);
1988 define('ACCESS_PRIVATE', 0);
1989 define('ACCESS_LOGGED_IN', 1);
1990 define('ACCESS_PUBLIC', 2);
1991 define('ACCESS_FRIENDS', -2);
2001 define('ELGG_ENTITIES_ANY_VALUE', null);
2002 
2010 define('ELGG_ENTITIES_NO_VALUE', 0);
2011 
2019 define('REFERRER', -1);
2020 
2029 define('REFERER', -1);
2030 
2031 return function(\Elgg\EventsService $events, \Elgg\HooksRegistrationService $hooks) {
2032  $events->registerHandler('boot', 'system', function () {
2033  _elgg_services()->boot->boot();
2034  }, 1);
2035  $events->registerHandler('cache:flush', 'system', function () {
2036  _elgg_services()->boot->invalidateCache();
2037  });
2038 
2039  $events->registerHandler('init', 'system', '_elgg_init');
2040  $events->registerHandler('init', 'system', '_elgg_walled_garden_init', 1000);
2041 
2042  $hooks->registerHandler('unit_test', 'system', '_elgg_api_test');
2043 };
A simple directory abstraction.
Definition: Directory.php:13
elgg_http_add_url_query_elements($url, array $elements)
Sets elements in a URL's query string.
Definition: elgglib.php:1171
elgg_parse_str($str)
Parses a string using mb_parse_str() if available.
Definition: mb_wrapper.php:19
elgg_view_exists($view, $viewtype= '', $recurse=true)
Returns whether the specified view exists.
Definition: views.php:299
$object
These two snippets demonstrates triggering an event and how to register for that event.
Definition: trigger.php:7
$view
Definition: crop.php:34
elgg_get_loaded_css()
Get the loaded CSS URLs.
Definition: elgglib.php:296
elgg_get_site_entity($site_guid=0)
Get an entity (default is current site)
Definition: sites.php:18
if(!$owner||!($owner instanceof ElggUser)||!$owner->canEdit()) $error
Definition: upload.php:14
$action
Definition: full.php:125
elgg_is_xhr()
Checks whether the request was requested via ajax.
Definition: actions.php:226
elgg_unregister_plugin_hook_handler($hook, $entity_type, $callback)
Unregister a callback as a plugin hook.
Definition: elgglib.php:730
if(!array_key_exists($filename, $text_files)) $file
elgg_add_action_tokens_to_url($url, $html_encode=false)
Adds action tokens to URL.
Definition: elgglib.php:1123
_elgg_css_page_handler($page)
Serve CSS.
Definition: elgglib.php:1617
_elgg_is_valid_options_for_batch_operation($options, $type)
Checks if there are some constraints on the options array for potentially dangerous operations...
Definition: elgglib.php:1791
elgg_register_external_file($type, $name, $url, $location, $priority=500)
Core registration function for external files.
Definition: elgglib.php:312
elgg_unrequire_js($name)
Cancel a request to load an AMD module onto the page.
Definition: elgglib.php:233
elgg_is_admin_logged_in()
Returns whether or not the viewer is currently logged in and an admin user.
Definition: sessions.php:60
elgg_normalize_url($url)
Definition: output.php:290
$current_page
Definition: pagination.php:60
if($guid==elgg_get_logged_in_user_guid()) $name
Definition: delete.php:21
elgg_define_js($name, $config)
Defines a JS lib as an AMD module.
Definition: elgglib.php:171
elgg_echo($message_key, $args=array(), $language="")
Given a message key, returns an appropriately translated full-text string.
Definition: languages.php:21
elgg_view_form($action, $form_vars=array(), $body_vars=array())
Definition: views.php:1302
elgg_view_resource($name, array $vars=[])
Render a resource view.
Definition: views.php:500
elgg_sort_3d_array_by_value(&$array, $element, $sort_order=SORT_ASC, $sort_type=SORT_LOCALE_STRING)
Sorts a 3d array by specific element.
Definition: elgglib.php:1342
$e
Definition: metadata.php:12
elgg_clear_plugin_hook_handlers($hook, $type)
Clears all callback registrations for a plugin hook.
Definition: elgglib.php:743
$extensions
elgg_get_ordered_event_handlers($event, $type)
Returns an ordered array of event handlers registered for $event and $type.
Definition: elgglib.php:829
elgg_http_url_is_identical($url1, $url2, $ignore_params=array('offset', 'limit'))
Test if two URLs are functionally identical.
Definition: elgglib.php:1215
elgg_unregister_external_file($type, $name)
Unregister an external file.
Definition: elgglib.php:325
sanitise_filepath($path, $append_slash=true)
Sanitise file paths ensuring that they begin and end with slashes etc.
Definition: elgglib.php:399
elgg_get_simplecache_url($view, $subview= '')
Get the URL for the cached view.
Definition: cache.php:136
elgg()
Get a reference to the global Application object.
Definition: elgglib.php:19
$path
Definition: details.php:88
$value
Definition: longtext.php:26
elgg_register_css($name, $url, $priority=null)
Register a CSS file for inclusion in the HTML head.
Definition: elgglib.php:259
elgg_load_library($name)
Load a PHP library.
Definition: elgglib.php:56
$return
Definition: opendd.php:15
elgg_view_layout($layout_name, $vars=array())
Displays a layout with optional parameters.
Definition: views.php:679
current_page_url()
Returns the current page's complete URL.
Definition: input.php:65
_elgg_favicon_page_handler($segments)
Handle requests for /favicon.ico.
Definition: elgglib.php:1634
$default
Definition: checkbox.php:35
$src
Definition: iframe.php:11
elgg_get_system_messages()
Get a copy of the current system messages.
Definition: elgglib.php:463
elgg_register_plugin_hook_handler($hook, $type, $callback, $priority=500)
Definition: elgglib.php:715
$timestamp
Definition: date.php:34
_elgg_sql_reverse_order_by_clause($order_by)
Reverses the ordering in an ORDER BY clause.
Definition: elgglib.php:1723
elgg_trigger_before_event($event, $object_type, $object=null)
Trigger a "Before event" indicating a process is about to begin.
Definition: elgglib.php:610
$url
Definition: exceptions.php:24
$vars['entity']
_elgg_shutdown_hook()
Emits a shutdown:system event upon PHP shutdown, but before database connections are dropped...
Definition: elgglib.php:1480
_elgg_php_exception_handler($exception)
Intercepts, logs, and displays uncaught exceptions.
Definition: elgglib.php:850
$options
Elgg admin footer.
Definition: footer.php:6
register_error($error)
Display an error on next page load.
Definition: elgglib.php:452
$string
elgg_get_loaded_external_files($type, $location)
Get external resource descriptors.
Definition: elgglib.php:351
$params
Definition: login.php:72
is_not_null($string)
Returns true is string is not empty, false, or null.
Definition: elgglib.php:1419
elgg_batch_delete_callback($object)
Delete objects with a delete() method.
Definition: elgglib.php:1777
_elgg_js_page_handler($page)
Serve javascript pages.
Definition: elgglib.php:1512
$exception
elgg_unregister_css($name)
Unregister a CSS file.
Definition: elgglib.php:271
elgg_require_js($name)
Request that Elgg load an AMD module onto the page.
Definition: elgglib.php:220
elgg_get_file_list($directory, $exceptions=array(), $list=array(), $extensions=null)
Returns a list of files in $directory.
Definition: elgglib.php:367
elgg_get_ini_setting_in_bytes($setting)
Returns a PHP INI setting in bytes.
Definition: elgglib.php:1388
_elgg_api_test($hook, $type, $value, $params)
Adds unit tests for the general API.
Definition: elgglib.php:1970
elgg_load_css($name)
Load a CSS file for this page.
Definition: elgglib.php:286
elgg_register_js($name, $url, $location= 'head', $priority=null)
Register a JavaScript file for inclusion.
Definition: elgglib.php:143
generate_action_token($timestamp)
Generate an action token.
Definition: actions.php:166
elgg_http_remove_url_query_element($url, $element)
Removes an element from a URL's query string.
Definition: elgglib.php:1157
$key
Definition: summary.php:34
elgg_trigger_deprecated_event($event, $object_type, $object=null, $message, $version)
Trigger an event normally, but send a notice about deprecated use if any handlers are registered...
Definition: elgglib.php:646
static static $_instance
Reference to the loaded Application returned by elgg()
Definition: Application.php:44
get_input($variable, $default=null, $filter_result=true)
Get some input from variables passed submitted through GET or POST.
Definition: input.php:27
const REFERER
Definition: elgglib.php:2029
_elgg_ajax_page_handler($segments)
Serve individual views for Ajax.
Definition: elgglib.php:1529
elgg_load_external_file($type, $name)
Load an external resource for use on this page.
Definition: elgglib.php:338
_elgg_walled_garden_index()
Intercepts the index page when Walled Garden mode is enabled.
Definition: elgglib.php:1844
global $CONFIG
_elgg_cacheable_view_page_handler($page, $type)
Serves a JS or CSS view with headers for caching.
Definition: elgglib.php:1660
ini_get_bool($ini_get_arg)
Return the state of a php.ini setting as a bool.
Definition: elgglib.php:1368
elgg_dump($value, $to_screen=true)
Logs or displays $value.
Definition: elgglib.php:1031
elgg_set_viewtype($viewtype="")
Manually set the viewtype.
Definition: views.php:73
const ELGG_ENTITIES_ANY_VALUE
Definition: elgglib.php:2001
elgg_trigger_plugin_hook($hook, $type, $params=null, $returnvalue=null)
Definition: elgglib.php:801
_elgg_walled_garden_ajax_handler($page)
Serve walled garden sections.
Definition: elgglib.php:1857
elgg_view($view, $vars=array(), $ignore1=false, $ignore2=false, $viewtype= '')
Return a parsed view.
Definition: views.php:342
elgg_deprecated_notice($msg, $dep_version, $backtrace_level=1)
Log a notice about deprecated use of a function, view, etc.
Definition: elgglib.php:1070
elgg_register_library($name, $location)
Register a PHP file as a library.
Definition: elgglib.php:34
_elgg_services(\Elgg\Di\ServiceProvider $services=null)
Get the global service provider.
Definition: autoloader.php:17
elgg_extract($key, $array, $default=null, $strict=true)
Checks for $array[$key] and returns its value if it exists, else returns $default.
Definition: elgglib.php:1310
elgg_register_event_handler($event, $object_type, $callback, $priority=500)
Definition: elgglib.php:538
elgg_log($message, $level= 'NOTICE')
Display or log a message.
Definition: elgglib.php:1000
_elgg_walled_garden_remove_public_access($hook, $type, $accesses)
Remove public access for walled gardens.
Definition: elgglib.php:1907
const ACCESS_PUBLIC
Definition: elgglib.php:1990
forward($location="", $reason= 'system')
Forward to $location.
Definition: elgglib.php:93
elgg_get_version($human_readable=false)
Get the current Elgg version information.
Definition: elgglib.php:1043
elgg_load_js($name)
Load a JavaScript resource on this page.
Definition: elgglib.php:208
elgg_http_build_url(array $parts, $html_encode=true)
Builds a URL from the a parts array like one returned by parse_url().
Definition: elgglib.php:1088
$required
Definition: label.php:12
elgg_set_system_messages(\Elgg\SystemMessages\RegisterSet $set)
Set the system messages.
Definition: elgglib.php:474
elgg_batch_disable_callback($object)
Disable objects with a disable() method.
Definition: elgglib.php:1763
elgg_format_url($url)
Handles formatting of ampersands in urls.
Definition: output.php:91
static elggDir()
Returns a directory that points to the root of Elgg, but not necessarily the install root...
$filename
class
Definition: placeholder.php:21
elgg_trigger_after_event($event, $object_type, $object=null)
Trigger an "After event" indicating a process has finished.
Definition: elgglib.php:629
_elgg_init()
Elgg's main init.
Definition: elgglib.php:1923
exit
Definition: autoloader.php:34
elgg_register_action($action, $filename="", $access= 'logged_in')
Registers an action.
Definition: actions.php:85
elgg_get_ordered_hook_handlers($hook, $type)
Returns an ordered array of hook handlers registered for $hook and $type.
Definition: elgglib.php:815
$output
Definition: item.php:10
_elgg_normalize_plural_options_array($options, $singulars)
Normalise the singular keys in an options array to plural keys.
Definition: elgglib.php:1440
elgg_trigger_event($event, $object_type, $object=null)
Definition: elgglib.php:589
_elgg_walled_garden_init()
Checks the status of the Walled Garden and forwards to a login page if required.
Definition: elgglib.php:1884
_elgg_php_error_handler($errno, $errmsg, $filename, $linenum, $vars)
Intercepts catchable PHP errors.
Definition: elgglib.php:936
$version
Definition: version.php:14
system_message($message)
Display a system message on next page load.
Definition: elgglib.php:438
elgg_get_loaded_js($location= 'head')
Get the JavaScript URLs that are loaded.
Definition: elgglib.php:245
elgg_batch_enable_callback($object)
Enable objects with an enable() method.
Definition: elgglib.php:1749
elgg_unregister_event_handler($event, $object_type, $callback)
Unregisters a callback for an event.
Definition: elgglib.php:552
$priority
elgg_unregister_js($name)
Unregister a JavaScript file.
Definition: elgglib.php:193
count_messages($register="")
Counts the number of messages, either globally or in a particular register.
Definition: elgglib.php:425
if($composer===null) if(!isset($composer->version)) $release
Definition: version.php:30
get_entity($guid)
Loads and returns an entity object from a guid.
Definition: entities.php:204
elgg_view_page($title, $body, $page_shell= 'default', $vars=array())
Assembles and outputs a full page.
Definition: views.php:437
if(!$display_name) $type
Definition: delete.php:27