All perfect praise be to Allah, The Lord of The Worlds, and may His peace and blessings be upon our Prophet Muhammad and upon all of his family and companions.
In principle, distributing donations must be fulfilled according to the donor’s conditions and will, since the latter has the same conditions of the endower. Besides the endower’s condition has to be fulfilled exactly as he endowed and it is impermissible to use his endowment for a purpose other than the one it was meant for.
Moreover, Al-Imam Al-Jowayni (May Allah have mercy on his soul) said:” The condition of the donor has to be fulfilled exactly as been conditioned, such as: the eligibility of the person receiving donation, the amount of donations and the number as well the order of the beneficiaries because only the donor has the right choose what has been mentioned accordingly and to specify the amount and the method of distribution.” [Nihayat Al-Mataleb vol.8 pp.362].
Therefore, the donations given for a specific purpose can’t be distributed for a purpose other than the one for which they were donated for .i.e. if someone donated to build a well in the Mosque then it should be only for the purpose of building a well, besides it is impermissible to use his donation for another purpose save after having donor’s permission, but if this was impossible, and the Mosque wasn’t in a need for the well, then it is permitted to use the aforementioned donation for a similar purpose but after taking the permission of the party in charge of this endowment, for Allah, The Exalted, said (What means):” So fear God as much as ye can;” [Al-Tagh’abun/16]
Therefore, it is impermissible to use the donations allocated for the Mosque to build a residence for the Imam because it is not part of the Mosque save if the donor intended so or collecting donations was for this purpose so long as the donors are notified. As for using the donations to build a well, it is permissible because the well has the same rulings and conditions of the Mosque as being part of it. And Allah knows best.