Usually people are referring to the latter when a student contributes a significant amount of work towards a project that eventually gets published as part of the PI's lab's research focus.
So basically, a PI is an investigator that is an expert in some field X. He has postdocs, grad students, UGs that work for him to try to answer questions (e.g. projects) that contribute towards moving field X forward. Ideally speaking this would mean that at the end of each project, something novel has been discovered and thus gets a story written up about said phenomena. Now an UG may work on part of a postdoc's or grad student's project(s) or even their own. They would carry out experiments, analyze data and report their findings to the PI (or postdoc or grad student). Once enough experiments have been carried out to put together a coherent "narrative", the work is drafted for publication. Now some PI's are more hands on with the writing portion and may write up the discussion of the paper, other's are more hands off and will have the students draft portions and edit them afterwards. Depending on how much work the student contributed to the project will be seen from their authorship position: 1st author = significant contribution, 2nd author = good sized contribution, middle author = some contribution.
The story is then submitted to a journal of interest (to the PI), reviewed, then it's either rejected or returned with revision suggestions (this usually means additional experiments), and the cycle repeats until the journal finally accepts the "narrative". Then the work is published. Now there are a lot of nuances to the process and I glossed over some parts but hopefully this helps you understand a bit of what the publication process entails.