How to set the CMS language as the preferred language of the contact?
This is only a partial answer - but the PHP $_SERVER global variable contain the requested language code (e.g. en_US) (See here).  civicrm_option_value stores the "Languages" option group, which provides a mapping from the language code to the language option value ID.  

It seems like you could parse the requested language (en and en-US must be mapped to en_US), add an API call to OptionValue.get to get the correct ID value, and set the default value for preferred language.

Note that this is slightly different from what you're requesting - a French-speaking user on an English-localised web browser will get English, not French - but the concept should be applicable.