| 1 | <!--- Fusebox.org thanks Massimo Foti for contributing this code ---> |
|---|
| 2 | <cfscript> |
|---|
| 3 | /** |
|---|
| 4 | * @param startFile First file. (Required) |
|---|
| 5 | * @param endFile Second file. (Required) |
|---|
| 6 | * @return Returns a string. |
|---|
| 7 | */ |
|---|
| 8 | function fb_relativeFilePath(startFile,endFile){ |
|---|
| 9 | //In case we have absolute local paths, turn backward to forward slashes |
|---|
| 10 | var startpath = Replace(startFile,"\","/","ALL"); |
|---|
| 11 | var endPath = Replace(endFile,"\","/","ALL"); |
|---|
| 12 | //Declare variables |
|---|
| 13 | var i = 1; |
|---|
| 14 | var j = 1; |
|---|
| 15 | var endStr = ""; |
|---|
| 16 | var commonStr = ""; |
|---|
| 17 | var retVal = ""; |
|---|
| 18 | var whatsLeft = ""; |
|---|
| 19 | var slashPos = ""; |
|---|
| 20 | var slashCount = 0; |
|---|
| 21 | var dotDotSlash = ""; |
|---|
| 22 | //Be sure the paths aren't equal |
|---|
| 23 | if(startpath NEQ endPath){ |
|---|
| 24 | //If the starting path is longer, the destination path is our starting point |
|---|
| 25 | if(len(startpath) GT len(endPath)){ |
|---|
| 26 | endStr = len(endPath); |
|---|
| 27 | } |
|---|
| 28 | //Else the starting point is the start path |
|---|
| 29 | else{ |
|---|
| 30 | endStr = len(startpath); |
|---|
| 31 | } |
|---|
| 32 | //Check if the two paths share a base path and store it into the commonStr variable |
|---|
| 33 | for(i;i LT endStr; i=i+1){ |
|---|
| 34 | //Compare one character at time |
|---|
| 35 | if(mid(startpath,i,1) EQ mid(endPath,i,1)){ |
|---|
| 36 | commonStr = commonStr & mid(startpath,i,1); |
|---|
| 37 | } |
|---|
| 38 | else{ |
|---|
| 39 | break; |
|---|
| 40 | } |
|---|
| 41 | } |
|---|
| 42 | //We just need the base directory |
|---|
| 43 | commonStr=REReplaceNoCase(commonStr,"[^/]*$",""); |
|---|
| 44 | //If there is a common base path, remove it |
|---|
| 45 | if(len(commonStr) GT 0){ |
|---|
| 46 | whatsLeft = mid(startpath,len(commonStr)+1,len(startpath)); |
|---|
| 47 | } |
|---|
| 48 | else{ |
|---|
| 49 | whatsLeft = startpath; |
|---|
| 50 | } |
|---|
| 51 | slashPos = find("/",startpath); |
|---|
| 52 | //Count how many directories we have to climb |
|---|
| 53 | while(slashPos NEQ 0){ |
|---|
| 54 | slashCount = slashCount + 1; |
|---|
| 55 | slashPos = find("/",whatsLeft,slashPos+1); |
|---|
| 56 | } |
|---|
| 57 | //Append "../" for each directory we have to climb |
|---|
| 58 | for(j;j LT slashCount; j=j+1){ |
|---|
| 59 | dotDotSlash = dotDotSlash & "../"; |
|---|
| 60 | } |
|---|
| 61 | //Assemble the final path |
|---|
| 62 | retVal = dotDotSlash & mid(endPath,len(commonStr)+1,len(endPath)); |
|---|
| 63 | |
|---|
| 64 | if (find("/", retVal) EQ 0) |
|---|
| 65 | retVal = "./" & retVal; |
|---|
| 66 | } |
|---|
| 67 | //Paths are the same |
|---|
| 68 | else{ |
|---|
| 69 | retVal = ""; |
|---|
| 70 | } |
|---|
| 71 | return retVal; |
|---|
| 72 | } |
|---|
| 73 | </cfscript> |
|---|