Generally, I'm not clear on why this function is doing so much checking and optional modification of current state before creating the link. It would be helpful to describe its purpose, and then beneficial to simply what it's doing if at all possible. For example, I made a suggestion about not checking permission, and just trying the create to see what happens. Perhaps putting into words the purpose of the function will help clarify any opportunities to simplify it.