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