Photochemistry and molecular ions in oxygen-rich circumstellar envelopes