1<?php 2 3class helper_plugin_recommend_assignment 4{ 5 public static $confFile = DOKU_CONF . 'recommend_snippets.json'; 6 7 public static function getAssignments() 8 { 9 return @jsonToArray(self::$confFile); 10 } 11 12 public function addAssignment($assignment) 13 { 14 $assignments = self::getAssignments(); 15 $assignments[] = $assignment; 16 return (bool)file_put_contents(self::$confFile, json_encode($assignments, JSON_PRETTY_PRINT)); 17 } 18 19 public function removeAssignment($assignment) 20 { 21 if (empty($assignment['pattern'])) { 22 return false; 23 } 24 25 $assignments = self::getAssignments(); 26 $remaining = array_filter($assignments, function($data) use ($assignment) { 27 return !( 28 $assignment['pattern'] === $data['pattern'] 29 && $assignment['user'] === $data['user'] 30 && $assignment['message'] === $data['message'] 31 ); 32 }); 33 34 if (count($remaining) < count($assignments)) { 35 return (bool)file_put_contents(self::$confFile, json_encode($remaining, JSON_PRETTY_PRINT)); 36 } 37 return false; 38 } 39 40 /** 41 * Returns the last matching template. 42 * 43 * @return array 44 */ 45 public function loadMatchingTemplate() 46 { 47 $assignments = self::getAssignments(); 48 $hlp = $this; 49 $matches = array_filter($assignments, function ($data) use ($hlp) { 50 return $hlp::matchPagePattern($data['pattern']); 51 }); 52 53 $template = array_pop($matches); 54 return $template; 55 } 56 57 /** 58 * Check if the given pattern matches the given page 59 * 60 * @param string $pattern the pattern to check against 61 * @param string|null $page the cleaned pageid to check 62 * @param string|null $pns optimization, the colon wrapped namespace of the page, set null for automatic 63 * @return bool 64 * @author Andreas Gohr 65 * 66 */ 67 public static function matchPagePattern($pattern, $page = null, $pns = null) 68 { 69 if (is_null($page)) $page = getID(); 70 71 if (trim($pattern, ':') == '**') { 72 return true; 73 } // match all 74 75 // regex patterns 76 if ($pattern[0] == '/') { 77 return (bool) preg_match($pattern, ":$page"); 78 } 79 80 if (is_null($pns)) { 81 $pns = ':' . getNS($page) . ':'; 82 } 83 84 $ans = ':' . cleanID($pattern) . ':'; 85 if (substr($pattern, -2) == '**') { 86 // upper namespaces match 87 if (strpos($pns, $ans) === 0) { 88 return true; 89 } 90 } elseif (substr($pattern, -1) == '*') { 91 // namespaces match exact 92 if ($ans == $pns) { 93 return true; 94 } 95 } else { 96 // exact match 97 if (cleanID($pattern) == $page) { 98 return true; 99 } 100 } 101 102 return false; 103 } 104} 105