API: how can I get the origin of the visitor specified by custom variable?

We’re tracking our visitors by Piwik and I find it great.

However, I’m facing some difficulties using the APIs, especially with custom variables.

What I need to get is the very first origin of some registered user.

Imagine the flow:

  • an anonymous user comes to our website from somewhere (this is displayed on the frontend under the ‘visitor log -> first visit -> from’ section)
  • the user then registers (maybe) and starts using our website as an authenticated user, and we pass a custom variable called ‘username’ to Piwik.

How can I get the origin of the visitor - where he came from - programmatically? I don’t actually know when the user firstly came to the website. I want to create some kind of a function which would take only the user’s username and then it would return his origin - the URL of the site where he came from.

Any help appreciated.

Thank you!

(Asked @ SO as well, but it seems I won’t get the answer there…)