Spain is to legalise about 300,000 undocumented migrants a year - at a time that many European countries are seeking to limit or deter migration.