<?php
class Lingua_Stem_Ru
{
    var $VERSION = "0.02";
    var $Stem_Caching = 0;
    var $Stem_Cache = array();
    var $VOWEL = '/àåèîóûýþÿ/';
    var $PERFECTIVEGROUND = '/((èâ|èâøè|èâøèñü|ûâ|ûâøè|ûâøèñü)|((?<=[àÿ])(â|âøè|âøèñü)))$/';
    var $REFLEXIVE = '/(ñ[ÿü])$/';
    var $ADJECTIVE = '/(åå|èå|ûå|îå|èìè|ûìè|åé|èé|ûé|îé|åì|èì|ûì|îì|åãî|îãî|åìó|îìó|èõ|ûõ|óþ|þþ|àÿ|ÿÿ|îþ|åþ)$/';
    var $PARTICIPLE = '/((èâø|ûâø|óþù)|((?<=[àÿ])(åì|íí|âø|þù|ù)))$/';
    var $VERB = '/((èëà|ûëà|åíà|åéòå|óéòå|èòå|èëè|ûëè|åé|óé|èë|ûë|èì|ûì|åí|èëî|ûëî|åíî|ÿò|óåò|óþò|èò|ûò|åíû|èòü|ûòü|èøü|óþ|þ)|((?<=[àÿ])(ëà|íà|åòå|éòå|ëè|é|ë|åì|í|ëî|íî|åò|þò|íû|òü|åøü|ííî)))$/';
    var $NOUN = '/(à|åâ|îâ|èå|üå|å|èÿìè|ÿìè|àìè|åè|èè|è|èåé|åé|îé|èé|é|èÿì|ÿì|èåì|åì|àì|îì|î|ó|àõ|èÿõ|ÿõ|û|ü|èþ|üþ|þ|èÿ|üÿ|ÿ)$/';
    var $RVRE = '/^(.*?[àåèîóûýþÿ])(.*)$/';
    var $DERIVATIONAL = '/[^àåèîóûýþÿ][àåèîóûýþÿ]+[^àåèîóûýþÿ]+[àåèîóûýþÿ].*(?<=î)ñòü?$/';

    function s(&$s, $re, $to)
    {
        $orig = $s;
        $s = preg_replace($re, $to, $s);
        return $orig !== $s;
    }

    function m($s, $re)
    {
        return preg_match($re, $s);
    }

    function stem_word($word)
    {
        $word = strtolower($word);
        $word = str_replace('¸', 'å', $word);
        # Check against cache of stemmed words
        if ($this->Stem_Caching && isset($this->Stem_Cache[$word])) {
            return $this->Stem_Cache[$word];
        }
        $stem = $word;
        do {
          if (!preg_match($this->RVRE, $word, $p)) break;
          $start = $p[1];
          $RV = $p[2];
          if (!$RV) break;

          # Step 1
          if (!$this->s($RV, $this->PERFECTIVEGROUND, '')) {
              $this->s($RV, $this->REFLEXIVE, '');

              if ($this->s($RV, $this->ADJECTIVE, '')) {
                  $this->s($RV, $this->PARTICIPLE, '');
              } else {
                  if (!$this->s($RV, $this->VERB, ''))
                      $this->s($RV, $this->NOUN, '');
              }
          }

          # Step 2
          $this->s($RV, '/è$/', '');

          # Step 3
          if ($this->m($RV, $this->DERIVATIONAL))
              $this->s($RV, '/îñòü?$/', '');

          # Step 4
          if (!$this->s($RV, '/ü$/', '')) {
              $this->s($RV, '/åéøå?/', '');
              $this->s($RV, '/íí$/', 'í');
          }

          $stem = $start.$RV;
        } while(false);
        if ($this->Stem_Caching) $this->Stem_Cache[$word] = $stem;
        return $stem;
    }

    function stem_caching($parm_ref)
    {
        $caching_level = @$parm_ref['-level'];
        if ($caching_level) {
            if (!$this->m($caching_level, '/^[012]$/')) {
                die(__CLASS__ . "::stem_caching() - Legal values are '0','1' or '2'. '$caching_level' is not a legal value");
            }
            $this->Stem_Caching = $caching_level;
        }
        return $this->Stem_Caching;
    }

    function clear_stem_cache()
    {
        $this->Stem_Cache = array();
    }
}

?>
