I have written this function for a website, but it is too system specific.
Mine relies on dovecot (which supports mysql based authentication).
I added a database table that stores the user's password, password security question and password security answer. This table is filled when the user registers. Then whenever the user forgets his password he can recover it by answering the security question.
Hope this helped.