Necessary and sufficient conditions for the chain rule in W^{1,1}_{loc}(R^N;R^d) and BV_{loc}(R^N;R^d)