Elgg  Version 1.10
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  if ($location === REFERER) {
83  $location = _elgg_services()->request->headers->get('Referer');
84  }
85 
86  $location = elgg_normalize_url($location);
87 
88  // return new forward location or false to stop the forward or empty string to exit
90  $params = array('current_url' => $current_page, 'forward_url' => $location);
91  $location = elgg_trigger_plugin_hook('forward', $reason, $params, $location);
92 
93  if ($location) {
94  header("Location: {$location}");
95  }
96  exit;
97  } else {
98  throw new \SecurityException("Redirect could not be issued due to headers already being sent. Halting execution for security. "
99  . "Output started in file $file at line $line. Search http://learn.elgg.org/ for more information.");
100  }
101 }
102 
127 function elgg_register_js($name, $url, $location = 'head', $priority = null) {
128  return elgg_register_external_file('js', $name, $url, $location, $priority);
129 }
130 
152 function elgg_define_js($name, $config) {
153  $src = elgg_extract('src', $config);
154 
155  if ($src) {
157  _elgg_services()->amdConfig->addPath($name, $url);
158  }
159 
160  // shimmed module
161  if (isset($config['deps']) || isset($config['exports'])) {
162  _elgg_services()->amdConfig->addShim($name, $config);
163  }
164 }
165 
175  return elgg_unregister_external_file('js', $name);
176 }
177 
189 function elgg_load_js($name) {
191 }
192 
193 
202  _elgg_services()->amdConfig->addDependency($name);
203 }
204 
205 
214 function elgg_get_loaded_js($location = 'head') {
215  return elgg_get_loaded_external_files('js', $location);
216 }
217 
228 function elgg_register_css($name, $url, $priority = null) {
229  return elgg_register_external_file('css', $name, $url, 'head', $priority);
230 }
231 
241  return elgg_unregister_external_file('css', $name);
242 }
243 
255 function elgg_load_css($name) {
257 }
258 
266  return elgg_get_loaded_external_files('css', 'head');
267 }
268 
281 function elgg_register_external_file($type, $name, $url, $location, $priority = 500) {
282  return _elgg_services()->externalFiles->register($type, $name, $url, $location, $priority);
283 }
284 
295  return _elgg_services()->externalFiles->unregister($type, $name);
296 }
297 
308  return _elgg_services()->externalFiles->load($type, $name);
309 }
310 
320 function elgg_get_loaded_external_files($type, $location) {
321  return _elgg_services()->externalFiles->getLoadedFiles($type, $location);
322 }
323 
336 function elgg_get_file_list($directory, $exceptions = array(), $list = array(),
337 $extensions = null) {
338 
339  $directory = sanitise_filepath($directory);
340  if ($handle = opendir($directory)) {
341  while (($file = readdir($handle)) !== false) {
342  if (!is_file($directory . $file) || in_array($file, $exceptions)) {
343  continue;
344  }
345 
346  if (is_array($extensions)) {
347  if (in_array(strrchr($file, '.'), $extensions)) {
348  $list[] = $directory . $file;
349  }
350  } else {
351  $list[] = $directory . $file;
352  }
353  }
354  closedir($handle);
355  }
356 
357  return $list;
358 }
359 
368 function sanitise_filepath($path, $append_slash = true) {
369  // Convert to correct UNIX paths
370  $path = str_replace('\\', '/', $path);
371  $path = str_replace('../', '/', $path);
372  // replace // with / except when preceeded by :
373  $path = preg_replace("/([^:])\/\//", "$1/", $path);
374 
375  // Sort trailing slash
376  $path = trim($path);
377  // rtrim defaults plus /
378  $path = rtrim($path, " \n\t\0\x0B/");
379 
380  if ($append_slash) {
381  $path = $path . '/';
382  }
383 
384  return $path;
385 }
386 
416 function system_messages($message = null, $register = "success", $count = false) {
417  $session = _elgg_services()->session;
418  $messages = $session->get('msg', array());
419  if (!isset($messages[$register]) && !empty($register)) {
420  $messages[$register] = array();
421  }
422  if (!$count) {
423  if (!empty($message) && is_array($message)) {
424  $messages[$register] = array_merge($messages[$register], $message);
425  return true;
426  } else if (!empty($message) && is_string($message)) {
427  $messages[$register][] = $message;
428  $session->set('msg', $messages);
429  return true;
430  } else if (is_null($message)) {
431  if ($register != "") {
432  $returnarray = array();
433  $returnarray[$register] = $messages[$register];
434  $messages[$register] = array();
435  } else {
436  $returnarray = $messages;
437  $messages = array();
438  }
439  $session->set('msg', $messages);
440  return $returnarray;
441  }
442  } else {
443  if (!empty($register)) {
444  return sizeof($messages[$register]);
445  } else {
446  $count = 0;
447  foreach ($messages as $submessages) {
448  $count += sizeof($submessages);
449  }
450  return $count;
451  }
452  }
453  return false;
454 }
455 
463 function count_messages($register = "") {
464  return system_messages(null, $register, true);
465 }
466 
477  return system_messages($message, "success");
478 }
479 
490  return system_messages($error, "error");
491 }
492 
553 function elgg_register_event_handler($event, $object_type, $callback, $priority = 500) {
554  return _elgg_services()->events->registerHandler($event, $object_type, $callback, $priority);
555 }
556 
567 function elgg_unregister_event_handler($event, $object_type, $callback) {
568  return _elgg_services()->events->unregisterHandler($event, $object_type, $callback);
569 }
570 
604 function elgg_trigger_event($event, $object_type, $object = null) {
605  return _elgg_services()->events->trigger($event, $object_type, $object);
606 }
607 
625 function elgg_trigger_before_event($event, $object_type, $object = null) {
626  return _elgg_services()->events->trigger("$event:before", $object_type, $object);
627 }
628 
644 function elgg_trigger_after_event($event, $object_type, $object = null) {
645  $options = array(
646  \Elgg\EventsService::OPTION_STOPPABLE => false,
647  );
648  return _elgg_services()->events->trigger("$event:after", $object_type, $object, $options);
649 }
650 
664 function elgg_trigger_deprecated_event($event, $object_type, $object = null, $message, $version) {
665  $options = array(
666  \Elgg\EventsService::OPTION_DEPRECATION_MESSAGE => $message,
667  \Elgg\EventsService::OPTION_DEPRECATION_VERSION => $version,
668  );
669  return _elgg_services()->events->trigger($event, $object_type, $object, $options);
670 }
671 
737 function elgg_register_plugin_hook_handler($hook, $type, $callback, $priority = 500) {
738  return _elgg_services()->hooks->registerHandler($hook, $type, $callback, $priority);
739 }
740 
751 function elgg_unregister_plugin_hook_handler($hook, $entity_type, $callback) {
752  _elgg_services()->hooks->unregisterHandler($hook, $entity_type, $callback);
753 }
754 
809 function elgg_trigger_plugin_hook($hook, $type, $params = null, $returnvalue = null) {
810  return _elgg_services()->hooks->trigger($hook, $type, $params, $returnvalue);
811 }
812 
831  $timestamp = time();
832  error_log("Exception #$timestamp: $exception");
833 
834  // Wipe any existing output buffer
835  ob_end_clean();
836 
837  // make sure the error isn't cached
838  header("Cache-Control: no-cache, must-revalidate", true);
839  header('Expires: Fri, 05 Feb 1982 00:00:00 -0500', true);
840  // @note Do not send a 500 header because it is not a server error
841 
842  // we don't want the 'pagesetup', 'system' event to fire
843  global $CONFIG;
844  $CONFIG->pagesetupdone = true;
845 
846  try {
847  // allow custom scripts to trigger on exception
848  // $CONFIG->exception_include can be set locally in settings.php
849  // value should be a system path to a file to include
850  if (!empty($CONFIG->exception_include) && is_file($CONFIG->exception_include)) {
851  ob_start();
852  include $CONFIG->exception_include;
853  $exception_output = ob_get_clean();
854 
855  // if content is returned from the custom handler we will output
856  // that instead of our default failsafe view
857  if (!empty($exception_output)) {
858  echo $exception_output;
859  exit;
860  }
861  }
862 
863  elgg_set_viewtype('failsafe');
864 
865  if (elgg_is_admin_logged_in()) {
866  if (!elgg_view_exists("messages/exceptions/admin_exception")) {
867  elgg_set_viewtype('failsafe');
868  }
869 
870  $body = elgg_view("messages/exceptions/admin_exception", array(
871  'object' => $exception,
872  'ts' => $timestamp
873  ));
874  } else {
875  if (!elgg_view_exists("messages/exceptions/exception")) {
876  elgg_set_viewtype('failsafe');
877  }
878 
879  $body = elgg_view("messages/exceptions/exception", array(
880  'object' => $exception,
881  'ts' => $timestamp
882  ));
883  }
884  echo elgg_view_page(elgg_echo('exception:title'), $body);
885  } catch (Exception $e) {
886  $timestamp = time();
887  $message = $e->getMessage();
888  echo "Fatal error in exception handler. Check log for Exception #$timestamp";
889  error_log("Exception #$timestamp : fatal error in exception handler : $message");
890  }
891 }
892 
917 function _elgg_php_error_handler($errno, $errmsg, $filename, $linenum, $vars) {
918  $error = date("Y-m-d H:i:s (T)") . ": \"$errmsg\" in file $filename (line $linenum)";
919 
920  switch ($errno) {
921  case E_USER_ERROR:
922  error_log("PHP ERROR: $error");
923  register_error("ERROR: $error");
924 
925  // Since this is a fatal error, we want to stop any further execution but do so gracefully.
926  throw new \Exception($error);
927  break;
928 
929  case E_WARNING :
930  case E_USER_WARNING :
931  case E_RECOVERABLE_ERROR: // (e.g. type hint violation)
932 
933  // check if the error wasn't suppressed by the error control operator (@)
934  if (error_reporting()) {
935  error_log("PHP WARNING: $error");
936  }
937  break;
938 
939  default:
940  global $CONFIG;
941  if (isset($CONFIG->debug) && $CONFIG->debug === 'NOTICE') {
942  error_log("PHP NOTICE: $error");
943  }
944  }
945 
946  return true;
947 }
948 
949 
967 function elgg_log($message, $level = 'NOTICE') {
968  static $levels = array(
969  'INFO' => 200,
970  'NOTICE' => 250,
971  'WARNING' => 300,
972  'DEBUG' => 300,
973  'ERROR' => 400,
974  );
975 
976  if ($level == 'DEBUG') {
977  elgg_deprecated_notice("The 'DEBUG' level for logging has been deprecated.", 1.9);
978  }
979 
980  $level = $levels[$level];
981  return _elgg_services()->logger->log($message, $level);
982 }
983 
998 function elgg_dump($value, $to_screen = true) {
999  _elgg_services()->logger->dump($value, $to_screen);
1000 }
1001 
1010 function elgg_get_version($human_readable = false) {
1011  global $CONFIG;
1012 
1013  static $version, $release;
1014 
1015  if (isset($CONFIG->path)) {
1016  if (!isset($version) || !isset($release)) {
1017  if (!include($CONFIG->path . "version.php")) {
1018  return false;
1019  }
1020  }
1021  return $human_readable ? $release : $version;
1022  }
1023 
1024  return false;
1025 }
1026 
1055 function elgg_deprecated_notice($msg, $dep_version, $backtrace_level = 1) {
1056  // if it's a major release behind, visual and logged
1057  // if it's a 1 minor release behind, visual and logged
1058  // if it's for current minor release, logged.
1059  // bugfixes don't matter because we are not deprecating between them
1060 
1061  if (!$dep_version) {
1062  return false;
1063  }
1064 
1065  $elgg_version = elgg_get_version(true);
1066  $elgg_version_arr = explode('.', $elgg_version);
1067  $elgg_major_version = (int)$elgg_version_arr[0];
1068  $elgg_minor_version = (int)$elgg_version_arr[1];
1069 
1070  $dep_version_arr = explode('.', (string)$dep_version);
1071  $dep_major_version = (int)$dep_version_arr[0];
1072  $dep_minor_version = (int)$dep_version_arr[1];
1073 
1074  $visual = false;
1075 
1076  if (($dep_major_version < $elgg_major_version) ||
1077  ($dep_minor_version < $elgg_minor_version)) {
1078  $visual = true;
1079  }
1080 
1081  $msg = "Deprecated in $dep_major_version.$dep_minor_version: $msg";
1082 
1083  if ($visual && elgg_is_admin_logged_in()) {
1084  register_error($msg);
1085  }
1086 
1087  // Get a file and line number for the log. Never show this in the UI.
1088  // Skip over the function that sent this notice and see who called the deprecated
1089  // function itself.
1090  $msg .= " Called from ";
1091  $stack = array();
1092  $backtrace = debug_backtrace();
1093  // never show this call.
1094  array_shift($backtrace);
1095  $i = count($backtrace);
1096 
1097  foreach ($backtrace as $trace) {
1098  $stack[] = "[#$i] {$trace['file']}:{$trace['line']}";
1099  $i--;
1100 
1101  if ($backtrace_level > 0) {
1102  if ($backtrace_level <= 1) {
1103  break;
1104  }
1105  $backtrace_level--;
1106  }
1107  }
1108 
1109  $msg .= implode("<br /> -> ", $stack);
1110 
1111  elgg_log($msg, 'WARNING');
1112 
1113  return true;
1114 }
1115 
1127 function elgg_http_build_url(array $parts, $html_encode = true) {
1128  // build only what's given to us.
1129  $scheme = isset($parts['scheme']) ? "{$parts['scheme']}://" : '';
1130  $host = isset($parts['host']) ? "{$parts['host']}" : '';
1131  $port = isset($parts['port']) ? ":{$parts['port']}" : '';
1132  $path = isset($parts['path']) ? "{$parts['path']}" : '';
1133  $query = isset($parts['query']) ? "?{$parts['query']}" : '';
1134  $fragment = isset($parts['fragment']) ? "#{$parts['fragment']}" : '';
1135 
1136  $string = $scheme . $host . $port . $path . $query . $fragment;
1137 
1138  if ($html_encode) {
1139  return elgg_format_url($string);
1140  } else {
1141  return $string;
1142  }
1143 }
1144 
1162 function elgg_add_action_tokens_to_url($url, $html_encode = false) {
1164  $components = parse_url($url);
1165 
1166  if (isset($components['query'])) {
1167  $query = elgg_parse_str($components['query']);
1168  } else {
1169  $query = array();
1170  }
1171 
1172  if (isset($query['__elgg_ts']) && isset($query['__elgg_token'])) {
1173  return $url;
1174  }
1175 
1176  // append action tokens to the existing query
1177  $query['__elgg_ts'] = time();
1178  $query['__elgg_token'] = generate_action_token($query['__elgg_ts']);
1179  $components['query'] = http_build_query($query);
1180 
1181  // rebuild the full url
1182  return elgg_http_build_url($components, $html_encode);
1183 }
1184 
1197  return elgg_http_add_url_query_elements($url, array($element => null));
1198 }
1199 
1210 function elgg_http_add_url_query_elements($url, array $elements) {
1211  $url_array = parse_url($url);
1212 
1213  if (isset($url_array['query'])) {
1214  $query = elgg_parse_str($url_array['query']);
1215  } else {
1216  $query = array();
1217  }
1218 
1219  foreach ($elements as $k => $v) {
1220  if ($v === null) {
1221  unset($query[$k]);
1222  } else {
1223  $query[$k] = $v;
1224  }
1225  }
1226 
1227  // why check path? A: if no path, this may be a relative URL like "?foo=1". In this case,
1228  // the output "" would be interpreted the current URL, so in this case we *must* set
1229  // a query to make sure elements are removed.
1230  if ($query || empty($url_array['path'])) {
1231  $url_array['query'] = http_build_query($query);
1232  } else {
1233  unset($url_array['query']);
1234  }
1235  $string = elgg_http_build_url($url_array, false);
1236 
1237  return $string;
1238 }
1239 
1254 function elgg_http_url_is_identical($url1, $url2, $ignore_params = array('offset', 'limit')) {
1255  $url1 = elgg_normalize_url($url1);
1256  $url2 = elgg_normalize_url($url2);
1257 
1258  // @todo - should probably do something with relative URLs
1259 
1260  if ($url1 == $url2) {
1261  return true;
1262  }
1263 
1264  $url1_info = parse_url($url1);
1265  $url2_info = parse_url($url2);
1266 
1267  if (isset($url1_info['path'])) {
1268  $url1_info['path'] = trim($url1_info['path'], '/');
1269  }
1270  if (isset($url2_info['path'])) {
1271  $url2_info['path'] = trim($url2_info['path'], '/');
1272  }
1273 
1274  // compare basic bits
1275  $parts = array('scheme', 'host', 'path');
1276 
1277  foreach ($parts as $part) {
1278  if ((isset($url1_info[$part]) && isset($url2_info[$part]))
1279  && $url1_info[$part] != $url2_info[$part]) {
1280  return false;
1281  } elseif (isset($url1_info[$part]) && !isset($url2_info[$part])) {
1282  return false;
1283  } elseif (!isset($url1_info[$part]) && isset($url2_info[$part])) {
1284  return false;
1285  }
1286  }
1287 
1288  // quick compare of get params
1289  if (isset($url1_info['query']) && isset($url2_info['query'])
1290  && $url1_info['query'] == $url2_info['query']) {
1291  return true;
1292  }
1293 
1294  // compare get params that might be out of order
1295  $url1_params = array();
1296  $url2_params = array();
1297 
1298  if (isset($url1_info['query'])) {
1299  if ($url1_info['query'] = html_entity_decode($url1_info['query'])) {
1300  $url1_params = elgg_parse_str($url1_info['query']);
1301  }
1302  }
1303 
1304  if (isset($url2_info['query'])) {
1305  if ($url2_info['query'] = html_entity_decode($url2_info['query'])) {
1306  $url2_params = elgg_parse_str($url2_info['query']);
1307  }
1308  }
1309 
1310  // drop ignored params
1311  foreach ($ignore_params as $param) {
1312  if (isset($url1_params[$param])) {
1313  unset($url1_params[$param]);
1314  }
1315  if (isset($url2_params[$param])) {
1316  unset($url2_params[$param]);
1317  }
1318  }
1319 
1320  // array_diff_assoc only returns the items in arr1 that aren't in arrN
1321  // but not the items that ARE in arrN but NOT in arr1
1322  // if arr1 is an empty array, this function will return 0 no matter what.
1323  // since we only care if they're different and not how different,
1324  // add the results together to get a non-zero (ie, different) result
1325  $diff_count = count(array_diff_assoc($url1_params, $url2_params));
1326  $diff_count += count(array_diff_assoc($url2_params, $url1_params));
1327  if ($diff_count > 0) {
1328  return false;
1329  }
1330 
1331  return true;
1332 }
1333 
1349 function elgg_extract($key, array $array, $default = null, $strict = true) {
1350  if (!is_array($array)) {
1351  return $default;
1352  }
1353 
1354  if ($strict) {
1355  return (isset($array[$key])) ? $array[$key] : $default;
1356  } else {
1357  return (isset($array[$key]) && !empty($array[$key])) ? $array[$key] : $default;
1358  }
1359 }
1360 
1381 function elgg_sort_3d_array_by_value(&$array, $element, $sort_order = SORT_ASC,
1382 $sort_type = SORT_LOCALE_STRING) {
1383 
1384  $sort = array();
1385 
1386  foreach ($array as $v) {
1387  if (isset($v[$element])) {
1388  $sort[] = strtolower($v[$element]);
1389  } else {
1390  $sort[] = null;
1391  }
1392  };
1393 
1394  return array_multisort($sort, $sort_order, $sort_type, $array);
1395 }
1396 
1407 function ini_get_bool($ini_get_arg) {
1408  $temp = strtolower(ini_get($ini_get_arg));
1409 
1410  if ($temp == '1' || $temp == 'on' || $temp == 'true') {
1411  return true;
1412  }
1413  return false;
1414 }
1415 
1427 function elgg_get_ini_setting_in_bytes($setting) {
1428  // retrieve INI setting
1429  $val = ini_get($setting);
1430 
1431  // convert INI setting when shorthand notation is used
1432  $last = strtolower($val[strlen($val) - 1]);
1433  switch($last) {
1434  case 'g':
1435  $val *= 1024;
1436  // fallthrough intentional
1437  case 'm':
1438  $val *= 1024;
1439  // fallthrough intentional
1440  case 'k':
1441  $val *= 1024;
1442  }
1443 
1444  // return byte value
1445  return $val;
1446 }
1447 
1459  if (($string === '') || ($string === false) || ($string === null)) {
1460  return false;
1461  }
1462 
1463  return true;
1464 }
1465 
1480  foreach ($singulars as $singular) {
1481  $plural = $singular . 's';
1482 
1483  if (array_key_exists($singular, $options)) {
1484  if ($options[$singular] === ELGG_ENTITIES_ANY_VALUE) {
1485  $options[$plural] = $options[$singular];
1486  } else {
1487  // Test for array refs #2641
1488  if (!is_array($options[$singular])) {
1489  $options[$plural] = array($options[$singular]);
1490  } else {
1491  $options[$plural] = $options[$singular];
1492  }
1493  }
1494  }
1495 
1496  unset($options[$singular]);
1497  }
1498 
1499  return $options;
1500 }
1501 
1519 
1520  try {
1521  elgg_trigger_event('shutdown', 'system');
1522 
1523  $time = (float)(microtime(true) - $START_MICROTIME);
1524  $uri = _elgg_services()->request->server->get('REQUEST_URI', 'CLI');
1525  // demoted to NOTICE from DEBUG so javascript is not corrupted
1526  elgg_log("Page {$uri} generated in $time seconds", 'INFO');
1527  } catch (Exception $e) {
1528  $message = 'Error: ' . get_class($e) . ' thrown within the shutdown handler. ';
1529  $message .= "Message: '{$e->getMessage()}' in file {$e->getFile()} (line {$e->getLine()})";
1530  error_log($message);
1531  error_log("Exception trace stack: {$e->getTraceAsString()}");
1532  }
1533 
1534  // Prevent an APC session bug: https://bugs.php.net/bug.php?id=60657
1535  session_write_close();
1536 }
1537 
1550 function _elgg_js_page_handler($page) {
1551  return _elgg_cacheable_view_page_handler($page, 'js');
1552 }
1553 
1566 function _elgg_ajax_page_handler($page) {
1567  if (is_array($page) && sizeof($page)) {
1568  // throw away 'view' and form the view name
1569  unset($page[0]);
1570  $view = implode('/', $page);
1571 
1572  $allowed_views = elgg_get_config('allowed_ajax_views');
1573  if (!array_key_exists($view, $allowed_views)) {
1574  header('HTTP/1.1 403 Forbidden');
1575  exit;
1576  }
1577 
1578  // pull out GET parameters through filter
1579  $vars = array();
1580  foreach (_elgg_services()->request->query->keys() as $name) {
1581  $vars[$name] = get_input($name);
1582  }
1583 
1584  if (isset($vars['guid'])) {
1585  $vars['entity'] = get_entity($vars['guid']);
1586  }
1587 
1588  // Try to guess the mime-type
1589  switch ($page[1]) {
1590  case "js":
1591  header("Content-Type: text/javascript");
1592  break;
1593  case "css":
1594  header("Content-Type: text/css");
1595  break;
1596  }
1597 
1599  return true;
1600  }
1601  return false;
1602 }
1603 
1615 function _elgg_css_page_handler($page) {
1616  if (!isset($page[0])) {
1617  // default css
1618  $page[0] = 'elgg';
1619  }
1620 
1621  return _elgg_cacheable_view_page_handler($page, 'css');
1622 }
1623 
1632 function _elgg_favicon_page_handler($segments) {
1633  header("HTTP/1.1 404 Not Found", true, 404);
1634 
1635  header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', strtotime("+1 week")), true);
1636  header("Pragma: public", true);
1637  header("Cache-Control: public", true);
1638 
1639  // TODO in next 1.x send our default icon
1640  //header('Content-Type: image/vnd.microsoft.icon');
1641  //readfile(elgg_get_root_path() . '_graphics/favicon.ico');
1642 
1643  return true;
1644 }
1645 
1658 
1659  switch ($type) {
1660  case 'js':
1661  $content_type = 'text/javascript';
1662  break;
1663 
1664  case 'css':
1665  $content_type = 'text/css';
1666  break;
1667 
1668  default:
1669  return false;
1670  break;
1671  }
1672 
1673  if ($page) {
1674  // the view file names can have multiple dots
1675  // eg: views/default/js/calendars/jquery.fullcalendar.min.php
1676  // translates to the url /js/<ts>/calendars/jquery.fullcalendar.min.js
1677  // and the view js/calendars/jquery.fullcalendar.min
1678  // we ignore the last two dots for the ts and the ext.
1679  // Additionally, the timestamp is optional.
1680  $page = implode('/', $page);
1681  $regex = '|(.+?)\.\w+$|';
1682  if (!preg_match($regex, $page, $matches)) {
1683  return false;
1684  }
1685  $view = "$type/{$matches[1]}";
1686  if (!elgg_view_exists($view)) {
1687  return false;
1688  }
1689  $return = elgg_view($view);
1690 
1691  header("Content-type: $content_type");
1692 
1693  // @todo should js be cached when simple cache turned off
1694  //header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', strtotime("+10 days")), true);
1695  //header("Pragma: public");
1696  //header("Cache-Control: public");
1697  //header("Content-Length: " . strlen($return));
1698 
1699  echo $return;
1700  return true;
1701  }
1702  return false;
1703 }
1704 
1717  $order_by = strtolower($order_by);
1718 
1719  if (strpos($order_by, ' asc') !== false) {
1720  $return = str_replace(' asc', ' desc', $order_by);
1721  } elseif (strpos($order_by, ' desc') !== false) {
1722  $return = str_replace(' desc', ' asc', $order_by);
1723  } else {
1724  // no order specified, so default to desc since mysql defaults to asc
1725  $return = $order_by . ' desc';
1726  }
1727 
1728  return $return;
1729 }
1730 
1743  // our db functions return the number of rows affected...
1744  return $object->enable() ? true : false;
1745 }
1746 
1757  // our db functions return the number of rows affected...
1758  return $object->disable() ? true : false;
1759 }
1760 
1771  // our db functions return the number of rows affected...
1772  return $object->delete() ? true : false;
1773 }
1774 
1785  if (!$options || !is_array($options)) {
1786  return false;
1787  }
1788 
1789  // at least one of these is required.
1790  $required = array(
1791  // generic restraints
1792  'guid', 'guids'
1793  );
1794 
1795  switch ($type) {
1796  case 'metadata':
1797  $metadata_required = array(
1798  'metadata_owner_guid', 'metadata_owner_guids',
1799  'metadata_name', 'metadata_names',
1800  'metadata_value', 'metadata_values'
1801  );
1802 
1803  $required = array_merge($required, $metadata_required);
1804  break;
1805 
1806  case 'annotations':
1807  case 'annotation':
1808  $annotations_required = array(
1809  'annotation_owner_guid', 'annotation_owner_guids',
1810  'annotation_name', 'annotation_names',
1811  'annotation_value', 'annotation_values'
1812  );
1813 
1814  $required = array_merge($required, $annotations_required);
1815  break;
1816 
1817  default:
1818  return false;
1819  }
1820 
1821  foreach ($required as $key) {
1822  // check that it exists and is something.
1823  if (isset($options[$key]) && $options[$key]) {
1824  return true;
1825  }
1826  }
1827 
1828  return false;
1829 }
1830 
1838 
1839  elgg_load_css('elgg.walled_garden');
1840  elgg_load_js('elgg.walled_garden');
1841 
1842  $content = elgg_view('core/walled_garden/login');
1843 
1844  $params = array(
1845  'content' => $content,
1846  'class' => 'elgg-walledgarden-double',
1847  'id' => 'elgg-walledgarden-login',
1848  );
1849  $body = elgg_view_layout('walled_garden', $params);
1850  echo elgg_view_page('', $body, 'walled_garden');
1851 
1852  return true;
1853 }
1854 
1855 
1864  $view = $page[0];
1865  $params = array(
1866  'content' => elgg_view("core/walled_garden/$view"),
1867  'class' => 'elgg-walledgarden-single hidden',
1868  'id' => str_replace('_', '-', "elgg-walledgarden-$view"),
1869  );
1870  echo elgg_view_layout('walled_garden', $params);
1871  return true;
1872 }
1873 
1888  global $CONFIG;
1889 
1890  elgg_register_css('elgg.walled_garden', elgg_get_simplecache_url('css', 'walled_garden'));
1891  elgg_register_js('elgg.walled_garden', elgg_get_simplecache_url('js', 'walled_garden'));
1892 
1893  elgg_register_page_handler('walled_garden', '_elgg_walled_garden_ajax_handler');
1894 
1895  // check for external page view
1896  if (isset($CONFIG->site) && $CONFIG->site instanceof \ElggSite) {
1897  $CONFIG->site->checkWalledGarden();
1898  }
1899 }
1900 
1911  if (isset($accesses[ACCESS_PUBLIC])) {
1912  unset($accesses[ACCESS_PUBLIC]);
1913  }
1914  return $accesses;
1915 }
1916 
1930 function _elgg_engine_boot() {
1931  // Register the error handlers
1932  set_error_handler('_elgg_php_error_handler');
1933  set_exception_handler('_elgg_php_exception_handler');
1934 
1935  _elgg_services()->db->setupConnections();
1936 
1937  _elgg_services()->db->assertInstalled();
1938 
1940 
1942 
1944 
1946 
1947  _elgg_services()->systemCache->loadAll();
1948 
1949  _elgg_services()->translator->loadTranslations();
1950 }
1951 
1961 function _elgg_init() {
1962  global $CONFIG;
1963 
1964  elgg_register_action('comment/save');
1965  elgg_register_action('comment/delete');
1966 
1967  elgg_register_page_handler('js', '_elgg_js_page_handler');
1968  elgg_register_page_handler('css', '_elgg_css_page_handler');
1969  elgg_register_page_handler('ajax', '_elgg_ajax_page_handler');
1970  elgg_register_page_handler('favicon.ico', '_elgg_favicon_page_handler');
1971 
1972  elgg_register_page_handler('manifest.json', function() {
1974  $resource = new \Elgg\Http\WebAppManifestResource($site);
1975  header('Content-Type: application/json');
1976  echo json_encode($resource->get());
1977  return true;
1978  });
1979 
1980  elgg_register_plugin_hook_handler('head', 'page', function($hook, $type, array $result) {
1981  $result['links']['manifest'] = [
1982  'rel' => 'manifest',
1983  'href' => elgg_normalize_url('/manifest.json'),
1984  ];
1985 
1986  return $result;
1987  });
1988 
1989  elgg_register_js('elgg.autocomplete', 'js/lib/ui.autocomplete.js');
1990  elgg_register_js('jquery.ui.autocomplete.html', 'vendors/jquery/jquery.ui.autocomplete.html.js');
1991 
1992  elgg_register_external_view('js/elgg/UserPicker.js', true);
1993 
1994  elgg_register_js('elgg.friendspicker', 'js/lib/ui.friends_picker.js');
1995  elgg_register_js('elgg.avatar_cropper', 'js/lib/ui.avatar_cropper.js');
1996  elgg_register_js('jquery.imgareaselect', 'vendors/jquery/jquery.imgareaselect/scripts/jquery.imgareaselect.min.js');
1997  elgg_register_js('elgg.ui.river', 'js/lib/ui.river.js');
1998 
1999  elgg_register_css('jquery.imgareaselect', 'vendors/jquery/jquery.imgareaselect/css/imgareaselect-deprecated.css');
2000 
2001  // Trigger the shutdown:system event upon PHP shutdown.
2002  register_shutdown_function('_elgg_shutdown_hook');
2003 
2004  // Sets a blacklist of words in the current language.
2005  // This is a comma separated list in word:blacklist.
2006  // @todo possibly deprecate
2007  $CONFIG->wordblacklist = array();
2008  $list = explode(',', elgg_echo('word:blacklist'));
2009  if ($list) {
2010  foreach ($list as $l) {
2011  $CONFIG->wordblacklist[] = trim($l);
2012  }
2013  }
2014 }
2015 
2028 function _elgg_api_test($hook, $type, $value, $params) {
2029  global $CONFIG;
2030  $value[] = $CONFIG->path . 'engine/tests/ElggTravisInstallTest.php';
2031  $value[] = $CONFIG->path . 'engine/tests/ElggCoreHelpersTest.php';
2032  $value[] = $CONFIG->path . 'engine/tests/ElggCoreRegressionBugsTest.php';
2033  $value[] = $CONFIG->path . 'engine/tests/ElggBatchTest.php';
2034  return $value;
2035 }
2036 
2045 define('ACCESS_DEFAULT', -1);
2046 define('ACCESS_PRIVATE', 0);
2047 define('ACCESS_LOGGED_IN', 1);
2048 define('ACCESS_PUBLIC', 2);
2049 define('ACCESS_FRIENDS', -2);
2059 define('ELGG_ENTITIES_ANY_VALUE', null);
2060 
2068 define('ELGG_ENTITIES_NO_VALUE', 0);
2069 
2077 define('REFERRER', -1);
2078 
2087 define('REFERER', -1);
2088 
2089 elgg_register_event_handler('init', 'system', '_elgg_init');
2090 elgg_register_event_handler('boot', 'system', '_elgg_engine_boot', 1);
2091 elgg_register_plugin_hook_handler('unit_test', 'system', '_elgg_api_test');
2092 
2093 elgg_register_event_handler('init', 'system', '_elgg_walled_garden_init', 1000);
_elgg_load_autoload_cache()
Load cached data into the autoload system.
Definition: autoloader.php:55
$messages
Definition: admin.php:27
elgg_http_add_url_query_elements($url, array $elements)
Sets elements in a URL&#39;s query string.
Definition: elgglib.php:1210
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:265
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_unregister_plugin_hook_handler($hook, $entity_type, $callback)
Unregister a callback as a plugin hook.
Definition: elgglib.php:751
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:1162
_elgg_css_page_handler($page)
Serve CSS.
Definition: elgglib.php:1615
_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:1784
elgg_register_external_file($type, $name, $url, $location, $priority=500)
Core registration function for external files.
Definition: elgglib.php:281
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
$current_page
Definition: pagination.php:49
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:152
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:1381
$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:1254
elgg_unregister_external_file($type, $name)
Unregister an external file.
Definition: elgglib.php:294
sanitise_filepath($path, $append_slash=true)
Sanitise file paths ensuring that they begin and end with slashes etc.
Definition: elgglib.php:368
if(is_callable('mb_internal_encoding')) elgg_parse_str($str)
Parses a string using mb_parse_str() if available.
Definition: mb_wrapper.php:21
$value
Definition: longtext.php:29
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:318
elgg_register_css($name, $url, $priority=null)
Register a CSS file for inclusion in the HTML head.
Definition: elgglib.php:228
elgg_load_library($name)
Load a PHP library.
Definition: elgglib.php:43
if(!$autoload_available) _elgg_services()
Definition: autoloader.php:20
$return
Definition: opendd.php:15
_elgg_favicon_page_handler($segments)
Handle requests for /favicon.ico.
Definition: elgglib.php:1632
$default
Definition: checkbox.php:36
$src
Definition: iframe.php:18
exit
Definition: reorder.php:12
elgg parse_url
Parse a URL into its parts.
Definition: elgglib.js:432
elgg_extract($key, array $array, $default=null, $strict=true)
Checks for $array[$key] and returns its value if it exists, else returns $default.
Definition: elgglib.php:1349
_elgg_load_site_config()
Loads configuration related to this site.
elgg_register_plugin_hook_handler($hook, $type, $callback, $priority=500)
Register a callback as a plugin hook handler.
Definition: elgglib.php:737
$timestamp
Definition: date.php:35
_elgg_sql_reverse_order_by_clause($order_by)
Reverses the ordering in an ORDER BY clause.
Definition: elgglib.php:1716
_elgg_ajax_page_handler($page)
Serve individual views for Ajax.
Definition: elgglib.php:1566
elgg_trigger_before_event($event, $object_type, $object=null)
Trigger a "Before event" indicating a process is about to begin.
Definition: elgglib.php:625
$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:1517
_elgg_php_exception_handler($exception)
Intercepts, logs, and displays uncaught exceptions.
Definition: elgglib.php:830
register_error($error)
Display an error on next page load.
Definition: elgglib.php:489
$string
elgg_get_loaded_external_files($type, $location)
Get external resource descriptors.
Definition: elgglib.php:320
$params
Definition: login.php:72
is_not_null($string)
Returns true is string is not empty, false, or null.
Definition: elgglib.php:1458
$options
Definition: index.php:14
elgg_batch_delete_callback($object)
Delete objects with a delete() method.
Definition: elgglib.php:1770
_elgg_js_page_handler($page)
Serve javascript pages.
Definition: elgglib.php:1550
$exception
elgg_unregister_css($name)
Unregister a CSS file.
Definition: elgglib.php:240
elgg_require_js($name)
Request that Elgg load an AMD module onto the page.
Definition: elgglib.php:201
elgg_get_file_list($directory, $exceptions=array(), $list=array(), $extensions=null)
Returns a list of files in $directory.
Definition: elgglib.php:336
elgg_get_ini_setting_in_bytes($setting)
Returns a PHP INI setting in bytes.
Definition: elgglib.php:1427
Save menu items.
_elgg_api_test($hook, $type, $value, $params)
Adds unit tests for the general API.
Definition: elgglib.php:2028
elgg_load_css($name)
Load a CSS file for this page.
Definition: elgglib.php:255
elgg_register_js($name, $url, $location= 'head', $priority=null)
Register a JavaScript file for inclusion.
Definition: elgglib.php:127
generate_action_token($timestamp)
Generate an action token.
Definition: actions.php:156
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
if(!$limit=(int) elgg_extract('limit', $vars, elgg_get_config('default_limit'))) $count
Definition: pagination.php:26
elgg_http_remove_url_query_element($url, $element)
Removes an element from a URL&#39;s query string.
Definition: elgglib.php:1196
$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:664
const REFERER
Definition: elgglib.php:2087
elgg_load_external_file($type, $name)
Load an external resource for use on this page.
Definition: elgglib.php:307
_elgg_engine_boot()
Boots the engine.
Definition: elgglib.php:1930
_elgg_walled_garden_index()
Intercepts the index page when Walled Garden mode is enabled.
Definition: elgglib.php:1837
global $CONFIG
_elgg_cacheable_view_page_handler($page, $type)
Serves a JS or CSS view with headers for caching.
Definition: elgglib.php:1657
ini_get_bool($ini_get_arg)
Return the state of a php.ini setting as a bool.
Definition: elgglib.php:1407
elgg_dump($value, $to_screen=true)
Logs or displays $value.
Definition: elgglib.php:998
const ELGG_ENTITIES_ANY_VALUE
Definition: elgglib.php:2059
elgg echo
Translates a string.
Definition: languages.js:43
elgg_trigger_plugin_hook($hook, $type, $params=null, $returnvalue=null)
Trigger a Plugin Hook and run all handler callbacks registered to that hook:type. ...
Definition: elgglib.php:809
elgg_register_page_handler($identifier, $function)
Registers a page handler for a particular identifier.
Definition: pagehandler.php:34
_elgg_walled_garden_ajax_handler($page)
Serve walled garden sections.
Definition: elgglib.php:1863
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)
Sends a notice about deprecated use of a function, view, etc.
Definition: elgglib.php:1055
elgg global
Pointer to the global context.
Definition: elgglib.js:12
$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:354
system_messages($message=null, $register="success", $count=false)
Queues a message to be displayed.
Definition: elgglib.php:416
elgg_view_layout($layout_name, $vars=array())
Displays a layout with optional parameters.
Definition: views.php:618
elgg_register_event_handler($event, $object_type, $callback, $priority=500)
Register a callback as an Elgg event handler.
Definition: elgglib.php:553
elgg_log($message, $level= 'NOTICE')
Display or log a message.
Definition: elgglib.php:967
_elgg_walled_garden_remove_public_access($hook, $type, $accesses)
Remove public access for walled gardens.
Definition: elgglib.php:1910
const ACCESS_PUBLIC
Definition: elgglib.php:2048
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:1010
elgg_load_js($name)
Load a JavaScript resource on this page.
Definition: elgglib.php:189
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:1127
$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:1756
elgg_format_url($url)
Handles formatting of ampersands in urls.
Definition: output.php:105
elgg_trigger_after_event($event, $object_type, $object=null)
Trigger an "After event" indicating a process has finished.
Definition: elgglib.php:644
_elgg_init()
Elgg&#39;s main init.
Definition: elgglib.php:1961
$filename
Definition: crop.php:23
elgg_view_page($title, $body, $page_shell= 'default', $vars=array())
Assembles and outputs a full page.
Definition: views.php:437
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:1479
elgg_trigger_event($event, $object_type, $object=null)
Trigger an Elgg Event and attempt to run all handler callbacks registered to that event...
Definition: elgglib.php:604
_elgg_walled_garden_init()
Checks the status of the Walled Garden and forwards to a login page if required.
Definition: elgglib.php:1887
_elgg_php_error_handler($errno, $errmsg, $filename, $linenum, $vars)
Intercepts catchable PHP errors.
Definition: elgglib.php:917
$session
Definition: login.php:9
$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:476
elgg_get_loaded_js($location= 'head')
Get the JavaScript URLs that are loaded.
Definition: elgglib.php:214
elgg_batch_enable_callback($object)
Enable objects with an enable() method.
Definition: elgglib.php:1742
elgg_unregister_event_handler($event, $object_type, $callback)
Unregisters a callback for an event.
Definition: elgglib.php:567
$priority
elgg_unregister_js($name)
Unregister a JavaScript file.
Definition: elgglib.php:174
count_messages($register="")
Counts the number of messages, either globally or in a particular register.
Definition: elgglib.php:463
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