Elgg  Version 1.12
elgglib.php
Go to the documentation of this file.
1 <?php
21 function elgg_register_library($name, $location) {
22  $config = _elgg_services()->config;
23 
24  $libraries = $config->get('libraries');
25  if ($libraries === null) {
26  $libraries = array();
27  }
28  $libraries[$name] = $location;
29  $config->set('libraries', $libraries);
30 }
31 
44  static $loaded_libraries = array();
45 
46  if (in_array($name, $loaded_libraries)) {
47  return;
48  }
49 
50  $libraries = _elgg_services()->config->get('libraries');
51 
52  if (!isset($libraries[$name])) {
53  $error = "$name is not a registered library";
54  throw new \InvalidParameterException($error);
55  }
56 
57  if (!include_once($libraries[$name])) {
58  $error = "Could not load the $name library from {$libraries[$name]}";
59  throw new \InvalidParameterException($error);
60  }
61 
62  $loaded_libraries[] = $name;
63 }
64 
80 function forward($location = "", $reason = 'system') {
81  if (!headers_sent($file, $line)) {
82  $forward_url = $location;
83  if ($location === REFERER) {
84  $forward_url = '';
85 
86  $unsafe_url = _elgg_services()->request->headers->get('Referer');
87  $safe_url = elgg_normalize_site_url($unsafe_url);
88  if ($safe_url !== false) {
89  $forward_url = $safe_url;
90  }
91  }
92 
94  // validate we forward to a (browser) supported url
95  if (!preg_match('/^(http|https|ftp|sftp|ftps):\/\//', $forward_url)) {
97  }
98 
99  // return new forward location or false to stop the forward or empty string to exit
100  $params = array(
101  'current_url' => current_page_url(),
102  'forward_url' => $forward_url,
103  'location' => $location,
104  );
106 
107  if ($forward_url) {
108  header("Location: {$forward_url}");
109  }
110  exit;
111  } else {
112  throw new \SecurityException("Redirect could not be issued due to headers already being sent. Halting execution for security. "
113  . "Output started in file $file at line $line. Search http://learn.elgg.org/ for more information.");
114  }
115 }
116 
141 function elgg_register_js($name, $url, $location = 'head', $priority = null) {
142  return elgg_register_external_file('js', $name, $url, $location, $priority);
143 }
144 
166 function elgg_define_js($name, $config) {
167  $src = elgg_extract('src', $config);
168 
169  if ($src) {
171  _elgg_services()->amdConfig->addPath($name, $url);
172  }
173 
174  // shimmed module
175  if (isset($config['deps']) || isset($config['exports'])) {
176  _elgg_services()->amdConfig->addShim($name, $config);
177  }
178 }
179 
189  return elgg_unregister_external_file('js', $name);
190 }
191 
203 function elgg_load_js($name) {
205 }
206 
207 
216  _elgg_services()->amdConfig->addDependency($name);
217 }
218 
219 
228 function elgg_get_loaded_js($location = 'head') {
229  return elgg_get_loaded_external_files('js', $location);
230 }
231 
242 function elgg_register_css($name, $url, $priority = null) {
243  return elgg_register_external_file('css', $name, $url, 'head', $priority);
244 }
245 
255  return elgg_unregister_external_file('css', $name);
256 }
257 
269 function elgg_load_css($name) {
271 }
272 
280  return elgg_get_loaded_external_files('css', 'head');
281 }
282 
295 function elgg_register_external_file($type, $name, $url, $location, $priority = 500) {
296  return _elgg_services()->externalFiles->register($type, $name, $url, $location, $priority);
297 }
298 
309  return _elgg_services()->externalFiles->unregister($type, $name);
310 }
311 
322  return _elgg_services()->externalFiles->load($type, $name);
323 }
324 
334 function elgg_get_loaded_external_files($type, $location) {
335  return _elgg_services()->externalFiles->getLoadedFiles($type, $location);
336 }
337 
350 function elgg_get_file_list($directory, $exceptions = array(), $list = array(),
351 $extensions = null) {
352 
353  $directory = sanitise_filepath($directory);
354  if ($handle = opendir($directory)) {
355  while (($file = readdir($handle)) !== false) {
356  if (!is_file($directory . $file) || in_array($file, $exceptions)) {
357  continue;
358  }
359 
360  if (is_array($extensions)) {
361  if (in_array(strrchr($file, '.'), $extensions)) {
362  $list[] = $directory . $file;
363  }
364  } else {
365  $list[] = $directory . $file;
366  }
367  }
368  closedir($handle);
369  }
370 
371  return $list;
372 }
373 
382 function sanitise_filepath($path, $append_slash = true) {
383  // Convert to correct UNIX paths
384  $path = str_replace('\\', '/', $path);
385  $path = str_replace('../', '/', $path);
386  // replace // with / except when preceeded by :
387  $path = preg_replace("/([^:])\/\//", "$1/", $path);
388 
389  // Sort trailing slash
390  $path = trim($path);
391  // rtrim defaults plus /
392  $path = rtrim($path, " \n\t\0\x0B/");
393 
394  if ($append_slash) {
395  $path = $path . '/';
396  }
397 
398  return $path;
399 }
400 
426 function system_messages($message = null, $register = "success", $count = false) {
427  if ($count) {
428  return _elgg_services()->systemMessages->count($register);
429  }
430  if ($message === null) {
431  return _elgg_services()->systemMessages->dumpRegister($register);
432  }
433  return _elgg_services()->systemMessages->addMessageToRegister($message, $register);
434 }
435 
443 function count_messages($register = "") {
444  return _elgg_services()->systemMessages->count($register);
445 }
446 
457  return _elgg_services()->systemMessages->addSuccessMessage($message);
458 }
459 
470  return _elgg_services()->systemMessages->addErrorMessage($error);
471 }
472 
533 function elgg_register_event_handler($event, $object_type, $callback, $priority = 500) {
534  return _elgg_services()->events->registerHandler($event, $object_type, $callback, $priority);
535 }
536 
547 function elgg_unregister_event_handler($event, $object_type, $callback) {
548  return _elgg_services()->events->unregisterHandler($event, $object_type, $callback);
549 }
550 
584 function elgg_trigger_event($event, $object_type, $object = null) {
585  return _elgg_services()->events->trigger($event, $object_type, $object);
586 }
587 
605 function elgg_trigger_before_event($event, $object_type, $object = null) {
606  return _elgg_services()->events->trigger("$event:before", $object_type, $object);
607 }
608 
624 function elgg_trigger_after_event($event, $object_type, $object = null) {
625  $options = array(
626  \Elgg\EventsService::OPTION_STOPPABLE => false,
627  );
628  return _elgg_services()->events->trigger("$event:after", $object_type, $object, $options);
629 }
630 
644 function elgg_trigger_deprecated_event($event, $object_type, $object = null, $message, $version) {
645  $options = array(
646  \Elgg\EventsService::OPTION_DEPRECATION_MESSAGE => $message,
647  \Elgg\EventsService::OPTION_DEPRECATION_VERSION => $version,
648  );
649  return _elgg_services()->events->trigger($event, $object_type, $object, $options);
650 }
651 
717 function elgg_register_plugin_hook_handler($hook, $type, $callback, $priority = 500) {
718  return _elgg_services()->hooks->registerHandler($hook, $type, $callback, $priority);
719 }
720 
732 function elgg_unregister_plugin_hook_handler($hook, $entity_type, $callback) {
733  _elgg_services()->hooks->unregisterHandler($hook, $entity_type, $callback);
734 }
735 
790 function elgg_trigger_plugin_hook($hook, $type, $params = null, $returnvalue = null) {
791  return _elgg_services()->hooks->trigger($hook, $type, $params, $returnvalue);
792 }
793 
812  $timestamp = time();
813  error_log("Exception at time $timestamp: $exception");
814 
815  // Wipe any existing output buffer
816  ob_end_clean();
817 
818  // make sure the error isn't cached
819  header("Cache-Control: no-cache, must-revalidate", true);
820  header('Expires: Fri, 05 Feb 1982 00:00:00 -0500', true);
821 
822  // we don't want the 'pagesetup', 'system' event to fire
823  global $CONFIG;
824  $CONFIG->pagesetupdone = true;
825 
826  try {
827  // allow custom scripts to trigger on exception
828  // $CONFIG->exception_include can be set locally in settings.php
829  // value should be a system path to a file to include
830  if (!empty($CONFIG->exception_include) && is_file($CONFIG->exception_include)) {
831  ob_start();
832  include $CONFIG->exception_include;
833  $exception_output = ob_get_clean();
834 
835  // if content is returned from the custom handler we will output
836  // that instead of our default failsafe view
837  if (!empty($exception_output)) {
838  echo $exception_output;
839  exit;
840  }
841  }
842 
843  if (elgg_is_xhr()) {
844  elgg_set_viewtype('json');
845  $response = new \Symfony\Component\HttpFoundation\JsonResponse(null, 500);
846  } else {
847  elgg_set_viewtype('failsafe');
848  $response = new \Symfony\Component\HttpFoundation\Response('', 500);
849  }
850 
851  if (elgg_is_admin_logged_in()) {
852  $body = elgg_view("messages/exceptions/admin_exception", array(
853  'object' => $exception,
854  'ts' => $timestamp
855  ));
856  } else {
857  $body = elgg_view("messages/exceptions/exception", array(
858  'object' => $exception,
859  'ts' => $timestamp
860  ));
861  }
862 
863  $response->setContent(elgg_view_page(elgg_echo('exception:title'), $body));
864  $response->send();
865  } catch (Exception $e) {
866  $timestamp = time();
867  $message = $e->getMessage();
868  http_response_code(500);
869  echo "Fatal error in exception handler. Check log for Exception at time $timestamp";
870  error_log("Exception at time $timestamp : fatal error in exception handler : $message");
871  }
872 }
873 
898 function _elgg_php_error_handler($errno, $errmsg, $filename, $linenum, $vars) {
899 
900  // Elgg 2.0 no longer uses ext/mysql, so these warnings are just a nuisance for 1.x site
901  // owners and plugin devs.
902  if (0 === strpos($errmsg, "mysql_connect(): The mysql extension is deprecated")) {
903  // only suppress core's usage
904  if (preg_match('~/classes/Elgg/Database\.php$~', strtr($filename, '\\', '/'))) {
905  return true;
906  }
907  }
908 
909  $error = date("Y-m-d H:i:s (T)") . ": \"$errmsg\" in file $filename (line $linenum)";
910 
911  switch ($errno) {
912  case E_USER_ERROR:
913  error_log("PHP ERROR: $error");
914  register_error("ERROR: $error");
915 
916  // Since this is a fatal error, we want to stop any further execution but do so gracefully.
917  throw new \Exception($error);
918  break;
919 
920  case E_WARNING :
921  case E_USER_WARNING :
922  case E_RECOVERABLE_ERROR: // (e.g. type hint violation)
923 
924  // check if the error wasn't suppressed by the error control operator (@)
925  if (error_reporting()) {
926  error_log("PHP WARNING: $error");
927  }
928  break;
929 
930  default:
931  global $CONFIG;
932  if (isset($CONFIG->debug) && $CONFIG->debug === 'NOTICE') {
933  error_log("PHP NOTICE: $error");
934  }
935  }
936 
937  return true;
938 }
939 
940 
958 function elgg_log($message, $level = 'NOTICE') {
959  static $levels = array(
960  'INFO' => 200,
961  'NOTICE' => 250,
962  'WARNING' => 300,
963  'DEBUG' => 300,
964  'ERROR' => 400,
965  );
966 
967  if ($level == 'DEBUG') {
968  elgg_deprecated_notice("The 'DEBUG' level for logging has been deprecated.", 1.9);
969  }
970 
971  $level = $levels[$level];
972  return _elgg_services()->logger->log($message, $level);
973 }
974 
989 function elgg_dump($value, $to_screen = true) {
990  _elgg_services()->logger->dump($value, $to_screen);
991 }
992 
1001 function elgg_get_version($human_readable = false) {
1002  global $CONFIG;
1003 
1004  static $version, $release;
1005 
1006  if (isset($CONFIG->path)) {
1007  if (!isset($version) || !isset($release)) {
1008  if (!include($CONFIG->path . "version.php")) {
1009  return false;
1010  }
1011  }
1012  return $human_readable ? $release : $version;
1013  }
1014 
1015  return false;
1016 }
1017 
1031 function elgg_deprecated_notice($msg, $dep_version, $backtrace_level = 1) {
1032  $backtrace_level += 1;
1033  return _elgg_services()->deprecation->sendNotice($msg, $dep_version, $backtrace_level);
1034 }
1035 
1049 function elgg_http_build_url(array $parts, $html_encode = true) {
1050  // build only what's given to us.
1051  $scheme = isset($parts['scheme']) ? "{$parts['scheme']}://" : '';
1052  $host = isset($parts['host']) ? "{$parts['host']}" : '';
1053  $port = isset($parts['port']) ? ":{$parts['port']}" : '';
1054  $path = isset($parts['path']) ? "{$parts['path']}" : '';
1055  $query = isset($parts['query']) ? "?{$parts['query']}" : '';
1056  $fragment = isset($parts['fragment']) ? "#{$parts['fragment']}" : '';
1057 
1058  $string = $scheme . $host . $port . $path . $query . $fragment;
1059 
1060  if ($html_encode) {
1061  return elgg_format_url($string);
1062  } else {
1063  return $string;
1064  }
1065 }
1066 
1084 function elgg_add_action_tokens_to_url($url, $html_encode = false) {
1086  $components = parse_url($url);
1087 
1088  if (isset($components['query'])) {
1089  $query = elgg_parse_str($components['query']);
1090  } else {
1091  $query = array();
1092  }
1093 
1094  if (isset($query['__elgg_ts']) && isset($query['__elgg_token'])) {
1095  return $url;
1096  }
1097 
1098  // append action tokens to the existing query
1099  $query['__elgg_ts'] = time();
1100  $query['__elgg_token'] = generate_action_token($query['__elgg_ts']);
1101  $components['query'] = http_build_query($query);
1102 
1103  // rebuild the full url
1104  return elgg_http_build_url($components, $html_encode);
1105 }
1106 
1119  return elgg_http_add_url_query_elements($url, array($element => null));
1120 }
1121 
1132 function elgg_http_add_url_query_elements($url, array $elements) {
1133  $url_array = parse_url($url);
1134 
1135  if (isset($url_array['query'])) {
1136  $query = elgg_parse_str($url_array['query']);
1137  } else {
1138  $query = array();
1139  }
1140 
1141  foreach ($elements as $k => $v) {
1142  if ($v === null) {
1143  unset($query[$k]);
1144  } else {
1145  $query[$k] = $v;
1146  }
1147  }
1148 
1149  // why check path? A: if no path, this may be a relative URL like "?foo=1". In this case,
1150  // the output "" would be interpreted the current URL, so in this case we *must* set
1151  // a query to make sure elements are removed.
1152  if ($query || empty($url_array['path'])) {
1153  $url_array['query'] = http_build_query($query);
1154  } else {
1155  unset($url_array['query']);
1156  }
1157  $string = elgg_http_build_url($url_array, false);
1158 
1159  return $string;
1160 }
1161 
1176 function elgg_http_url_is_identical($url1, $url2, $ignore_params = array('offset', 'limit')) {
1177  $url1 = elgg_normalize_url($url1);
1178  $url2 = elgg_normalize_url($url2);
1179 
1180  // @todo - should probably do something with relative URLs
1181 
1182  if ($url1 == $url2) {
1183  return true;
1184  }
1185 
1186  $url1_info = parse_url($url1);
1187  $url2_info = parse_url($url2);
1188 
1189  if (isset($url1_info['path'])) {
1190  $url1_info['path'] = trim($url1_info['path'], '/');
1191  }
1192  if (isset($url2_info['path'])) {
1193  $url2_info['path'] = trim($url2_info['path'], '/');
1194  }
1195 
1196  // compare basic bits
1197  $parts = array('scheme', 'host', 'path');
1198 
1199  foreach ($parts as $part) {
1200  if ((isset($url1_info[$part]) && isset($url2_info[$part]))
1201  && $url1_info[$part] != $url2_info[$part]) {
1202  return false;
1203  } elseif (isset($url1_info[$part]) && !isset($url2_info[$part])) {
1204  return false;
1205  } elseif (!isset($url1_info[$part]) && isset($url2_info[$part])) {
1206  return false;
1207  }
1208  }
1209 
1210  // quick compare of get params
1211  if (isset($url1_info['query']) && isset($url2_info['query'])
1212  && $url1_info['query'] == $url2_info['query']) {
1213  return true;
1214  }
1215 
1216  // compare get params that might be out of order
1217  $url1_params = array();
1218  $url2_params = array();
1219 
1220  if (isset($url1_info['query'])) {
1221  if ($url1_info['query'] = html_entity_decode($url1_info['query'])) {
1222  $url1_params = elgg_parse_str($url1_info['query']);
1223  }
1224  }
1225 
1226  if (isset($url2_info['query'])) {
1227  if ($url2_info['query'] = html_entity_decode($url2_info['query'])) {
1228  $url2_params = elgg_parse_str($url2_info['query']);
1229  }
1230  }
1231 
1232  // drop ignored params
1233  foreach ($ignore_params as $param) {
1234  if (isset($url1_params[$param])) {
1235  unset($url1_params[$param]);
1236  }
1237  if (isset($url2_params[$param])) {
1238  unset($url2_params[$param]);
1239  }
1240  }
1241 
1242  // array_diff_assoc only returns the items in arr1 that aren't in arrN
1243  // but not the items that ARE in arrN but NOT in arr1
1244  // if arr1 is an empty array, this function will return 0 no matter what.
1245  // since we only care if they're different and not how different,
1246  // add the results together to get a non-zero (ie, different) result
1247  $diff_count = count(array_diff_assoc($url1_params, $url2_params));
1248  $diff_count += count(array_diff_assoc($url2_params, $url1_params));
1249  if ($diff_count > 0) {
1250  return false;
1251  }
1252 
1253  return true;
1254 }
1255 
1271 function elgg_extract($key, $array, $default = null, $strict = true) {
1272  if (!is_array($array)) {
1273  return $default;
1274  }
1275 
1276  if ($strict) {
1277  return (isset($array[$key])) ? $array[$key] : $default;
1278  } else {
1279  return (isset($array[$key]) && !empty($array[$key])) ? $array[$key] : $default;
1280  }
1281 }
1282 
1303 function elgg_sort_3d_array_by_value(&$array, $element, $sort_order = SORT_ASC,
1304 $sort_type = SORT_LOCALE_STRING) {
1305 
1306  $sort = array();
1307 
1308  foreach ($array as $v) {
1309  if (isset($v[$element])) {
1310  $sort[] = strtolower($v[$element]);
1311  } else {
1312  $sort[] = null;
1313  }
1314  };
1315 
1316  return array_multisort($sort, $sort_order, $sort_type, $array);
1317 }
1318 
1329 function ini_get_bool($ini_get_arg) {
1330  $temp = strtolower(ini_get($ini_get_arg));
1331 
1332  if ($temp == '1' || $temp == 'on' || $temp == 'true') {
1333  return true;
1334  }
1335  return false;
1336 }
1337 
1349 function elgg_get_ini_setting_in_bytes($setting) {
1350  // retrieve INI setting
1351  $val = ini_get($setting);
1352 
1353  // convert INI setting when shorthand notation is used
1354  $last = strtolower($val[strlen($val) - 1]);
1355  switch($last) {
1356  case 'g':
1357  $val *= 1024;
1358  // fallthrough intentional
1359  case 'm':
1360  $val *= 1024;
1361  // fallthrough intentional
1362  case 'k':
1363  $val *= 1024;
1364  }
1365 
1366  // return byte value
1367  return $val;
1368 }
1369 
1381  if (($string === '') || ($string === false) || ($string === null)) {
1382  return false;
1383  }
1384 
1385  return true;
1386 }
1387 
1402  foreach ($singulars as $singular) {
1403  $plural = $singular . 's';
1404 
1405  if (array_key_exists($singular, $options)) {
1406  if ($options[$singular] === ELGG_ENTITIES_ANY_VALUE) {
1407  $options[$plural] = $options[$singular];
1408  } else {
1409  // Test for array refs #2641
1410  if (!is_array($options[$singular])) {
1411  $options[$plural] = array($options[$singular]);
1412  } else {
1413  $options[$plural] = $options[$singular];
1414  }
1415  }
1416  }
1417 
1418  unset($options[$singular]);
1419  }
1420 
1421  return $options;
1422 }
1423 
1443 
1444  try {
1445  _elgg_services()->logger->setDisplay(false);
1446  elgg_trigger_event('shutdown', 'system');
1447 
1448  $time = (float)(microtime(true) - $START_MICROTIME);
1449  $uri = _elgg_services()->request->server->get('REQUEST_URI', 'CLI');
1450  // demoted to NOTICE from DEBUG so javascript is not corrupted
1451  elgg_log("Page {$uri} generated in $time seconds", 'INFO');
1452  } catch (Exception $e) {
1453  $message = 'Error: ' . get_class($e) . ' thrown within the shutdown handler. ';
1454  $message .= "Message: '{$e->getMessage()}' in file {$e->getFile()} (line {$e->getLine()})";
1455  error_log($message);
1456  error_log("Exception trace stack: {$e->getTraceAsString()}");
1457  }
1458 
1459  // Prevent an APC session bug: https://bugs.php.net/bug.php?id=60657
1460  session_write_close();
1461 }
1462 
1475 function _elgg_js_page_handler($page) {
1476  return _elgg_cacheable_view_page_handler($page, 'js');
1477 }
1478 
1492 function _elgg_ajax_page_handler($segments) {
1494 
1495  if (count($segments) < 2) {
1496  return false;
1497  }
1498 
1499  if ($segments[0] === 'view' || $segments[0] === 'form') {
1500  if ($segments[0] === 'view') {
1501  // ignore 'view/'
1502  $view = implode('/', array_slice($segments, 1));
1503  } else {
1504  // form views start with "forms", not "form"
1505  $view = 'forms/' . implode('/', array_slice($segments, 1));
1506  }
1507 
1508  $allowed_views = elgg_get_config('allowed_ajax_views');
1509  if (!array_key_exists($view, $allowed_views)) {
1510  header('HTTP/1.1 403 Forbidden');
1511  exit;
1512  }
1513 
1514  // pull out GET parameters through filter
1515  $vars = array();
1516  foreach (_elgg_services()->request->query->keys() as $name) {
1517  $vars[$name] = get_input($name);
1518  }
1519 
1520  if (isset($vars['guid'])) {
1521  $vars['entity'] = get_entity($vars['guid']);
1522  }
1523 
1524  if ($segments[0] === 'view') {
1525  // Try to guess the mime-type
1526  switch ($segments[1]) {
1527  case "js":
1528  header("Content-Type: text/javascript;charset=utf-8");
1529  break;
1530  case "css":
1531  header("Content-Type: text/css;charset=utf-8");
1532  break;
1533  }
1534 
1536  } else {
1537  $action = implode('/', array_slice($segments, 1));
1538  echo elgg_view_form($action, array(), $vars);
1539  }
1540  return true;
1541  }
1542 
1543  return false;
1544 }
1545 
1557 function _elgg_css_page_handler($page) {
1558  if (!isset($page[0])) {
1559  // default css
1560  $page[0] = 'elgg';
1561  }
1562 
1563  return _elgg_cacheable_view_page_handler($page, 'css');
1564 }
1565 
1574 function _elgg_favicon_page_handler($segments) {
1575  header("HTTP/1.1 404 Not Found", true, 404);
1576 
1577  header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', strtotime("+1 week")), true);
1578  header("Pragma: public", true);
1579  header("Cache-Control: public", true);
1580 
1581  // TODO in next 1.x send our default icon
1582  //header('Content-Type: image/vnd.microsoft.icon');
1583  //readfile(elgg_get_root_path() . '_graphics/favicon.ico');
1584 
1585  return true;
1586 }
1587 
1600 
1601  switch ($type) {
1602  case 'js':
1603  $content_type = 'text/javascript';
1604  break;
1605 
1606  case 'css':
1607  $content_type = 'text/css';
1608  break;
1609 
1610  default:
1611  return false;
1612  break;
1613  }
1614 
1615  if ($page) {
1616  // the view file names can have multiple dots
1617  // eg: views/default/js/calendars/jquery.fullcalendar.min.php
1618  // translates to the url /js/<ts>/calendars/jquery.fullcalendar.min.js
1619  // and the view js/calendars/jquery.fullcalendar.min
1620  // we ignore the last two dots for the ts and the ext.
1621  // Additionally, the timestamp is optional.
1622  $page = implode('/', $page);
1623  $regex = '|(.+?)\.\w+$|';
1624  if (!preg_match($regex, $page, $matches)) {
1625  return false;
1626  }
1627  $view = "$type/{$matches[1]}";
1628  if (!elgg_view_exists($view)) {
1629  return false;
1630  }
1631  $return = elgg_view($view);
1632 
1633  header("Content-type: $content_type;charset=utf-8");
1634 
1635  // @todo should js be cached when simple cache turned off
1636  //header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', strtotime("+10 days")), true);
1637  //header("Pragma: public");
1638  //header("Cache-Control: public");
1639  //header("Content-Length: " . strlen($return));
1640 
1641  echo $return;
1642  return true;
1643  }
1644  return false;
1645 }
1646 
1659  $order_by = strtolower($order_by);
1660 
1661  if (strpos($order_by, ' asc') !== false) {
1662  $return = str_replace(' asc', ' desc', $order_by);
1663  } elseif (strpos($order_by, ' desc') !== false) {
1664  $return = str_replace(' desc', ' asc', $order_by);
1665  } else {
1666  // no order specified, so default to desc since mysql defaults to asc
1667  $return = $order_by . ' desc';
1668  }
1669 
1670  return $return;
1671 }
1672 
1685  // our db functions return the number of rows affected...
1686  return $object->enable() ? true : false;
1687 }
1688 
1699  // our db functions return the number of rows affected...
1700  return $object->disable() ? true : false;
1701 }
1702 
1713  // our db functions return the number of rows affected...
1714  return $object->delete() ? true : false;
1715 }
1716 
1727  if (!$options || !is_array($options)) {
1728  return false;
1729  }
1730 
1731  // at least one of these is required.
1732  $required = array(
1733  // generic restraints
1734  'guid', 'guids'
1735  );
1736 
1737  switch ($type) {
1738  case 'metadata':
1739  $metadata_required = array(
1740  'metadata_owner_guid', 'metadata_owner_guids',
1741  'metadata_name', 'metadata_names',
1742  'metadata_value', 'metadata_values'
1743  );
1744 
1745  $required = array_merge($required, $metadata_required);
1746  break;
1747 
1748  case 'annotations':
1749  case 'annotation':
1750  $annotations_required = array(
1751  'annotation_owner_guid', 'annotation_owner_guids',
1752  'annotation_name', 'annotation_names',
1753  'annotation_value', 'annotation_values'
1754  );
1755 
1756  $required = array_merge($required, $annotations_required);
1757  break;
1758 
1759  default:
1760  return false;
1761  }
1762 
1763  foreach ($required as $key) {
1764  // check that it exists and is something.
1765  if (isset($options[$key]) && $options[$key]) {
1766  return true;
1767  }
1768  }
1769 
1770  return false;
1771 }
1772 
1780 
1781  elgg_load_css('elgg.walled_garden');
1782  elgg_load_js('elgg.walled_garden');
1783 
1784  $content = elgg_view('core/walled_garden/login');
1785 
1786  $params = array(
1787  'content' => $content,
1788  'class' => 'elgg-walledgarden-double',
1789  'id' => 'elgg-walledgarden-login',
1790  );
1791  $body = elgg_view_layout('walled_garden', $params);
1792  echo elgg_view_page('', $body, 'walled_garden');
1793 
1794  return true;
1795 }
1796 
1797 
1806  $view = $page[0];
1807  if (!elgg_view_exists("core/walled_garden/$view")) {
1808  return false;
1809  }
1810  $params = array(
1811  'content' => elgg_view("core/walled_garden/$view"),
1812  'class' => 'elgg-walledgarden-single hidden',
1813  'id' => str_replace('_', '-', "elgg-walledgarden-$view"),
1814  );
1815  echo elgg_view_layout('walled_garden', $params);
1816  return true;
1817 }
1818 
1833  global $CONFIG;
1834 
1835  elgg_register_css('elgg.walled_garden', elgg_get_simplecache_url('css', 'walled_garden'));
1836  elgg_register_js('elgg.walled_garden', elgg_get_simplecache_url('js', 'walled_garden'));
1837 
1838  elgg_register_page_handler('walled_garden', '_elgg_walled_garden_ajax_handler');
1839 
1840  // check for external page view
1841  if (isset($CONFIG->site) && $CONFIG->site instanceof \ElggSite) {
1842  $CONFIG->site->checkWalledGarden();
1843  }
1844 }
1845 
1856  if (isset($accesses[ACCESS_PUBLIC])) {
1857  unset($accesses[ACCESS_PUBLIC]);
1858  }
1859  return $accesses;
1860 }
1861 
1875 function _elgg_engine_boot() {
1876  // Register the error handlers
1877  set_error_handler('_elgg_php_error_handler');
1878  set_exception_handler('_elgg_php_exception_handler');
1879 
1880  _elgg_services()->db->setupConnections();
1881 
1882  _elgg_services()->db->assertInstalled();
1883 
1885 
1887 
1889 
1891 
1892  _elgg_services()->systemCache->loadAll();
1893 
1894  _elgg_services()->translator->loadTranslations();
1895 }
1896 
1906 function _elgg_init() {
1907  global $CONFIG;
1908 
1909  elgg_register_action('comment/save');
1910  elgg_register_action('comment/delete');
1911 
1912  elgg_register_page_handler('js', '_elgg_js_page_handler');
1913  elgg_register_page_handler('css', '_elgg_css_page_handler');
1914  elgg_register_page_handler('ajax', '_elgg_ajax_page_handler');
1915  elgg_register_page_handler('favicon.ico', '_elgg_favicon_page_handler');
1916 
1917  elgg_register_page_handler('manifest.json', function() {
1919  $resource = new \Elgg\Http\WebAppManifestResource($site);
1920  header('Content-Type: application/json;charset=utf-8');
1921  echo json_encode($resource->get());
1922  return true;
1923  });
1924 
1925  elgg_register_plugin_hook_handler('head', 'page', function($hook, $type, array $result) {
1926  $result['links']['manifest'] = [
1927  'rel' => 'manifest',
1928  'href' => elgg_normalize_url('/manifest.json'),
1929  ];
1930 
1931  return $result;
1932  });
1933 
1934  elgg_register_js('elgg.autocomplete', 'js/lib/ui.autocomplete.js');
1935  elgg_register_js('jquery.ui.autocomplete.html', 'vendors/jquery/jquery.ui.autocomplete.html.js');
1936 
1937  elgg_define_js('jquery.ui.autocomplete.html', array(
1938  'src' => '/vendors/jquery/jquery.ui.autocomplete.html.js',
1939  'deps' => array('jquery.ui')
1940  ));
1941 
1942  elgg_register_external_view('js/elgg/UserPicker.js', true);
1943 
1944  elgg_register_js('elgg.friendspicker', 'js/lib/ui.friends_picker.js');
1945  elgg_register_js('elgg.avatar_cropper', 'js/lib/ui.avatar_cropper.js');
1946  elgg_register_js('jquery.imgareaselect', 'vendors/jquery/jquery.imgareaselect/scripts/jquery.imgareaselect.min.js');
1947  elgg_register_js('elgg.ui.river', 'js/lib/ui.river.js');
1948 
1949  elgg_register_css('jquery.imgareaselect', 'vendors/jquery/jquery.imgareaselect/css/imgareaselect-deprecated.css');
1950 
1951  // Sets a blacklist of words in the current language.
1952  // This is a comma separated list in word:blacklist.
1953  // @todo possibly deprecate
1954  $CONFIG->wordblacklist = array();
1955  $list = explode(',', elgg_echo('word:blacklist'));
1956  if ($list) {
1957  foreach ($list as $l) {
1958  $CONFIG->wordblacklist[] = trim($l);
1959  }
1960  }
1961 }
1962 
1975 function _elgg_api_test($hook, $type, $value, $params) {
1976  global $CONFIG;
1977  $value[] = $CONFIG->path . 'engine/tests/ElggTravisInstallTest.php';
1978  $value[] = $CONFIG->path . 'engine/tests/ElggCoreHelpersTest.php';
1979  $value[] = $CONFIG->path . 'engine/tests/ElggCoreRegressionBugsTest.php';
1980  $value[] = $CONFIG->path . 'engine/tests/ElggBatchTest.php';
1981  return $value;
1982 }
1983 
1992 define('ACCESS_DEFAULT', -1);
1993 define('ACCESS_PRIVATE', 0);
1994 define('ACCESS_LOGGED_IN', 1);
1995 define('ACCESS_PUBLIC', 2);
1996 define('ACCESS_FRIENDS', -2);
2006 define('ELGG_ENTITIES_ANY_VALUE', null);
2007 
2015 define('ELGG_ENTITIES_NO_VALUE', 0);
2016 
2024 define('REFERRER', -1);
2025 
2034 define('REFERER', -1);
2035 
2036 return function(\Elgg\EventsService $events, \Elgg\HooksRegistrationService $hooks) {
2037  $events->registerHandler('init', 'system', '_elgg_init');
2038  $events->registerHandler('boot', 'system', '_elgg_engine_boot', 1);
2039  $hooks->registerHandler('unit_test', 'system', '_elgg_api_test');
2040 
2041  $events->registerHandler('init', 'system', '_elgg_walled_garden_init', 1000);
2042 };
_elgg_load_autoload_cache()
Load cached data into the autoload system.
Definition: autoloader.php:49
elgg_http_add_url_query_elements($url, array $elements)
Sets elements in a URL&#39;s query string.
Definition: elgglib.php:1132
elgg_parse_str($str)
Parses a string using mb_parse_str() if available.
Definition: mb_wrapper.php:19
elgg_get_config($name, $site_guid=0)
Get an Elgg configuration value.
$view
Definition: crop.php:68
elgg_get_loaded_css()
Get the loaded CSS URLs.
Definition: elgglib.php:279
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
elgg_is_xhr()
Checks whether the request was requested via ajax.
Definition: actions.php:227
elgg_unregister_plugin_hook_handler($hook, $entity_type, $callback)
Unregister a callback as a plugin hook.
Definition: elgglib.php:732
get_input($variable, $default=null, $filter_result=true)
Get some input from variables passed submitted through GET or POST.
Definition: input.php:27
elgg_add_action_tokens_to_url($url, $html_encode=false)
Adds action tokens to URL.
Definition: elgglib.php:1084
_elgg_css_page_handler($page)
Serve CSS.
Definition: elgglib.php:1557
_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:1726
elgg_register_external_file($type, $name, $url, $location, $priority=500)
Core registration function for external files.
Definition: elgglib.php:295
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:311
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:166
current_page_url()
Returns the current page&#39;s complete URL.
Definition: input.php:65
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:1303
$e
Definition: metadata.php:12
$object
Definition: upgrade.php:12
$extensions
elgg_http_url_is_identical($url1, $url2, $ignore_params=array('offset', 'limit'))
Test if two URLs are functionally identical.
Definition: elgglib.php:1176
elgg_unregister_external_file($type, $name)
Unregister an external file.
Definition: elgglib.php:308
sanitise_filepath($path, $append_slash=true)
Sanitise file paths ensuring that they begin and end with slashes etc.
Definition: elgglib.php:382
elgg_normalize_site_url($unsafe_url)
From untrusted input, get a site URL safe for forwarding.
Definition: output.php:370
$value
Definition: longtext.php:26
elgg_register_external_view($view, $cacheable=false)
Registers a view as being available externally (i.e.
Definition: views.php:231
elgg_view_exists($view, $viewtype= '', $recurse=true)
Returns whether the specified view exists.
Definition: views.php:304
elgg_register_css($name, $url, $priority=null)
Register a CSS file for inclusion in the HTML head.
Definition: elgglib.php:242
elgg_load_library($name)
Load a PHP library.
Definition: elgglib.php:43
$return
Definition: opendd.php:15
_elgg_favicon_page_handler($segments)
Handle requests for /favicon.ico.
Definition: elgglib.php:1574
$default
Definition: checkbox.php:34
$src
Definition: iframe.php:18
exit
Definition: reorder.php:12
elgg parse_url
Parse a URL into its parts.
Definition: elgglib.js:421
_elgg_load_site_config()
Loads configuration related to this site.
elgg_register_plugin_hook_handler($hook, $type, $callback, $priority=500)
Definition: elgglib.php:717
$timestamp
Definition: date.php:35
_elgg_sql_reverse_order_by_clause($order_by)
Reverses the ordering in an ORDER BY clause.
Definition: elgglib.php:1658
elgg_trigger_before_event($event, $object_type, $object=null)
Trigger a "Before event" indicating a process is about to begin.
Definition: elgglib.php:605
$url
Definition: exceptions.php:24
_elgg_shutdown_hook()
Emits a shutdown:system event upon PHP shutdown, but before database connections are dropped...
Definition: elgglib.php:1441
$action
_elgg_php_exception_handler($exception)
Intercepts, logs, and displays uncaught exceptions.
Definition: elgglib.php:811
register_error($error)
Display an error on next page load.
Definition: elgglib.php:469
$string
elgg_get_loaded_external_files($type, $location)
Get external resource descriptors.
Definition: elgglib.php:334
$params
Definition: login.php:72
is_not_null($string)
Returns true is string is not empty, false, or null.
Definition: elgglib.php:1380
$options
Definition: index.php:14
elgg_batch_delete_callback($object)
Delete objects with a delete() method.
Definition: elgglib.php:1712
_elgg_js_page_handler($page)
Serve javascript pages.
Definition: elgglib.php:1475
$exception
elgg_unregister_css($name)
Unregister a CSS file.
Definition: elgglib.php:254
elgg_require_js($name)
Request that Elgg load an AMD module onto the page.
Definition: elgglib.php:215
elgg_get_file_list($directory, $exceptions=array(), $list=array(), $extensions=null)
Returns a list of files in $directory.
Definition: elgglib.php:350
elgg_get_ini_setting_in_bytes($setting)
Returns a PHP INI setting in bytes.
Definition: elgglib.php:1349
Save menu items.
_elgg_api_test($hook, $type, $value, $params)
Adds unit tests for the general API.
Definition: elgglib.php:1975
elgg_load_css($name)
Load a CSS file for this page.
Definition: elgglib.php:269
elgg_register_js($name, $url, $location= 'head', $priority=null)
Register a JavaScript file for inclusion.
Definition: elgglib.php:141
generate_action_token($timestamp)
Generate an action token.
Definition: actions.php:167
elgg_set_viewtype($viewtype="")
Manually set the viewtype.
Definition: views.php:70
elgg_echo($message_key, $args=array(), $language="")
Given a message key, returns an appropriately translated full-text string.
Definition: languages.php:21
elgg_get_simplecache_url($type, $view)
Definition: cache.php:117
elgg_http_remove_url_query_element($url, $element)
Removes an element from a URL&#39;s query string.
Definition: elgglib.php:1118
$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:644
const REFERER
Definition: elgglib.php:2034
_elgg_services()
Definition: autoloader.php:14
_elgg_ajax_page_handler($segments)
Serve individual views for Ajax.
Definition: elgglib.php:1492
elgg_load_external_file($type, $name)
Load an external resource for use on this page.
Definition: elgglib.php:321
_elgg_engine_boot()
Boots the engine.
Definition: elgglib.php:1875
_elgg_walled_garden_index()
Intercepts the index page when Walled Garden mode is enabled.
Definition: elgglib.php:1779
global $CONFIG
_elgg_cacheable_view_page_handler($page, $type)
Serves a JS or CSS view with headers for caching.
Definition: elgglib.php:1599
ini_get_bool($ini_get_arg)
Return the state of a php.ini setting as a bool.
Definition: elgglib.php:1329
elgg_dump($value, $to_screen=true)
Logs or displays $value.
Definition: elgglib.php:989
const ELGG_ENTITIES_ANY_VALUE
Definition: elgglib.php:2006
elgg echo
Translates a string.
Definition: languages.js:48
elgg_trigger_plugin_hook($hook, $type, $params=null, $returnvalue=null)
Definition: elgglib.php:790
elgg_register_page_handler($identifier, $function)
Registers a page handler for a particular identifier.
Definition: pagehandler.php:34
elgg_ajax_gatekeeper()
Require that the current request be an XHR.
_elgg_walled_garden_ajax_handler($page)
Serve walled garden sections.
Definition: elgglib.php:1805
global $START_MICROTIME
The time with microseconds when the Elgg engine was started.
Definition: start.php:24
elgg_deprecated_notice($msg, $dep_version, $backtrace_level=1)
Log a notice about deprecated use of a function, view, etc.
Definition: elgglib.php:1031
elgg global
Pointer to the global context.
Definition: elgglib.js:12
elgg_get_site_url($site_guid=0)
Get the URL for the current (or specified) site.
$type
Definition: add.php:8
elgg_register_library($name, $location)
Register a PHP file as a library.
Definition: elgglib.php:21
elgg_view($view, $vars=array(), $bypass=false, $ignored=false, $viewtype= '')
Return a parsed view.
Definition: views.php:340
define(function(require){var $=require('jquery');var active=false;var SHOW_DELAY=20;$('body').append('< div class="elgg-spinner">< div class="elgg-ajax-loader"></div ></div >');var module={start:function(){active=true;setTimeout(function(){if(active){$('body').addClass('elgg-spinner-active');$(module).triggerHandler('_testing_show');}}, SHOW_DELAY);}, stop:function(){active=false;$('body').removeClass('elgg-spinner-active');}};return module;})
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:1271
system_messages($message=null, $register="success", $count=false)
Queues a message to be displayed.
Definition: elgglib.php:426
elgg_view_layout($layout_name, $vars=array())
Displays a layout with optional parameters.
Definition: views.php:608
elgg_register_event_handler($event, $object_type, $callback, $priority=500)
Definition: elgglib.php:533
elgg_log($message, $level= 'NOTICE')
Display or log a message.
Definition: elgglib.php:958
_elgg_walled_garden_remove_public_access($hook, $type, $accesses)
Remove public access for walled gardens.
Definition: elgglib.php:1855
const ACCESS_PUBLIC
Definition: elgglib.php:1995
forward($location="", $reason= 'system')
Forward to $location.
Definition: elgglib.php:80
elgg_get_version($human_readable=false)
Get the current Elgg version information.
Definition: elgglib.php:1001
elgg_load_js($name)
Load a JavaScript resource on this page.
Definition: elgglib.php:203
$forward_url
Definition: login.php:73
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:1049
$content
Set robots.txt action.
Definition: set_robots.php:6
$sort
Definition: plugins.php:19
elgg_batch_disable_callback($object)
Disable objects with a disable() method.
Definition: elgglib.php:1698
elgg_format_url($url)
Handles formatting of ampersands in urls.
Definition: output.php:105
if(elgg_in_context('widget')) $count
Definition: pagination.php:21
elgg_trigger_after_event($event, $object_type, $object=null)
Trigger an "After event" indicating a process has finished.
Definition: elgglib.php:624
_elgg_init()
Elgg&#39;s main init.
Definition: elgglib.php:1906
$filename
Definition: crop.php:23
elgg_view_page($title, $body, $page_shell= 'default', $vars=array())
Assembles and outputs a full page.
Definition: views.php:423
clearfix elgg elgg elgg elgg page header
Definition: admin.php:127
elgg_register_action($action, $filename="", $access= 'logged_in')
Registers an action.
Definition: actions.php:85
_elgg_session_boot()
Initializes the session and checks for the remember me cookie.
Definition: sessions.php:408
_elgg_normalize_plural_options_array($options, $singulars)
Normalise the singular keys in an options array to plural keys.
Definition: elgglib.php:1401
elgg_trigger_event($event, $object_type, $object=null)
Definition: elgglib.php:584
_elgg_walled_garden_init()
Checks the status of the Walled Garden and forwards to a login page if required.
Definition: elgglib.php:1832
_elgg_php_error_handler($errno, $errmsg, $filename, $linenum, $vars)
Intercepts catchable PHP errors.
Definition: elgglib.php:898
$version
Definition: version.php:14
_elgg_load_application_config()
Loads configuration related to Elgg as an application.
$path
Definition: invalid.php:17
system_message($message)
Display a system message on next page load.
Definition: elgglib.php:456
elgg_view_form($action, $form_vars=array(), $body_vars=array())
Definition: views.php:1298
elgg_get_loaded_js($location= 'head')
Get the JavaScript URLs that are loaded.
Definition: elgglib.php:228
elgg_batch_enable_callback($object)
Enable objects with an enable() method.
Definition: elgglib.php:1684
elgg_unregister_event_handler($event, $object_type, $callback)
Unregisters a callback for an event.
Definition: elgglib.php:547
$priority
elgg_unregister_js($name)
Unregister a JavaScript file.
Definition: elgglib.php:188
count_messages($register="")
Counts the number of messages, either globally or in a particular register.
Definition: elgglib.php:443
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:382
if(file_exists($welcome)) $vars
Definition: upgrade.php:93