Always check variable type before using readdir to avoid surprises

Port of https://github.com/owncloud/core/pull/4701, with few adjustments according to master.

@bartv2 @icewind1991 @karlitschek  or others please.