################ CULTURAL SALIENCE DATA ##################

tab <- read.csv(file = "SUPPLEMENTARY_MATERIAL_2.csv")

for (i in 1:545) {
  
  apicode <- tab$url_species[i]
  
  flickrr <- function(uu1){
    u1file <- tab$csv[i]
    u1<-uu1
    download.file(u1, u1file)
    u1<- readChar(u1file,nchars=1e6)
    u1 <- strsplit(u1, "photo id")
    u1<- u1[[1]]
    u1 <- u1[2:length(u1)]
    
    photos2 <- as.data.frame(matrix(0,nrow=length(u1), ncol = 6))
    colnames(photos2)<- c("PhotID", "User", "Date", "long", "lat", "url")
    for(j in 1:length(u1)){
      
      u2<- substr(u1[j],3,
                  regexpr(" owner", (u1[j]))[1]-2)
      
      photos2[j,1]<-u2
      
      u2 <-
        paste("https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=XXXXXXXXXXXXXXXX&photo_id="
              , u2, sep="", collapse="")
      
      download.file(u2,u1file)
      u2<- readChar(u1file,nchars=1e6)
      
      photos2[j,2]<-substr(u2, regexpr("dateuploaded=", u2)[1]+14,
                           regexpr("dateuploaded=", u2)[1]+23)
      photos2[j,3]<-substr(u2, regexpr("dateuploaded=", u2)[1]+14,
                           regexpr("dateuploaded=", u2)[1]+23)
      
      photos2[j,4]<-substr(u2, regexpr("longitude", u2)[1]+11, regexpr(" accuracy", u2)[1]-
                             2)
      photos2[j,5]<-substr(u2, regexpr("latitude", u2)[1]+10, regexpr("longitude", u2)[1]-3)
      photos2[j,6] <- substr(u2, regexpr("https://www.flickr.com", u2)[1], nchar(u2))
      
      photos2[j,6]<-substr(photos2[j,6],0,regexpr("url",photos2[j,6])[1]-3)
    }
    photos2$Date <- as.POSIXct(as.numeric(photos2$Date), origin="1970-01-01")
    photos2
  }
  
  searched.photos <- flickrr(apicode)
  write.csv(searched.photos, tab$csv[i])
  
}