+ $keys = array_keys($array);
+ if (in_array($key, $keys)) {
+ return $key;
+ }
+
+ if (($pos = strpos($key, '.php')) !== false) {
+ $key = substr($key, 0, $pos);
+ }
+
+ $has_end = in_array("#final#", $keys);
+ if (strlen($key) > 24 && $has_end) {
+ return "#final#";
+ }
+
+ foreach ($keys as $k) {
+ if ($k == "#final#") {
+ continue;
+ }
+ $lev = levenshtein($key, $k);
+
+ if ((!isset($val) || $lev < $val)
+ && ($lev <= strlen($k)/2 || strpos($k, $key) !== false || strpos($key, $k) !== false)) {
+ $val = $lev;
+ $best = $k;
+ }
+ }
+ if (!isset($best) && $has_end) {
+ return "#final#";
+ } else if (isset($best)) {
+ return $best;
+ }
+ return null;
+ }
+
+ public function near_hook()
+ {
+ $hooks = array();
+ $leafs = array();
+ foreach ($this->__hooks as $hook=>$handler) {
+ if (!$this->check_perms($handler['perms'])) {
+ continue;
+ }
+ $parts = split('/', $hook);
+ $place =& $hooks;
+ foreach ($parts as $part) {
+ if (!isset($place[$part])) {
+ $place[$part] = array();
+ }
+ $place =& $place[$part];
+ }
+ $leaf = $parts[count($parts)-1];
+ if (!isset($leafs[$leaf])) {
+ $leafs[$leaf] = $hook;
+ } else if (is_array($leafs[$leaf])) {
+ $leafs[$leaf][] = $hook;
+ } else {
+ $leafs[$leaf] = array($hook, $leafs[$leaf]);
+ }
+ $place["#final#"] = array();
+ }
+
+ // search for the nearest full path
+ $p = split('/', $this->path);
+ $place =& $hooks;
+ $link = '';
+ foreach ($p as $k) {
+ if (!isset($ended)) {
+ $key = $this->find_nearest_key($k, $place);
+ } else {
+ $key = $k;
+ }
+ if ($key == "#final#") {
+ if (!array_key_exists($link, $this->__hooks)) {
+ $link = '';
+ break;
+ }
+ $key = $k;
+ $ended = true;
+ }
+ if (!is_null($key)) {
+ if (!empty($link)) {
+ $link .= '/';
+ }
+ $link .= $key;
+ $place =& $place[$key];
+ } else {
+ $link = '';
+ break;
+ }
+ }
+ if ($link == $this->path) {
+ $link = '';
+ }
+ if ($link && levenshtein($link, $this->path) < strlen($link)/3) {
+ return $link;
+ }
+
+ // search for missing namespace (the given name is a leaf)
+ $leaf = array_shift($p);
+ $args = count($p) ? '/' . implode('/', $p) : '';
+ if (isset($leafs[$leaf]) && !is_array($leafs[$leaf]) && $leafs[$leaf] != $this->path) {
+ return $leafs[$leaf] . $args;
+ }
+ unset($val);
+ $best = null;
+ foreach ($leafs as $k=>&$path) {
+ if (is_array($path)) {
+ continue;
+ }
+ $lev = levenshtein($leaf, $k);
+
+ if ((!isset($val) || $lev < $val)
+ && ($lev <= strlen($k)/2 || strpos($k, $leaf) !== false || strpos($leaf, $k) !== false)) {
+ $val = $lev;
+ $best = $path;
+ }
+ }
+ return $best == null ? ( $link ? $link : null ) : $best . $args;
+ }