pepebe
8/3/2013 - 10:38 PM

MODX Snippet: Translate id of a resource into a nested folder structure 0000/000/00/1 for resource id 1 9000/900/90/9 for resource id 9999

MODX Snippet: Translate id of a resource into a nested folder structure 0000/000/00/1 for resource id 1 9000/900/90/9 for resource id 9999

<?php
    $maxDocs        = 9999;
    
    /* Use docid or pageid to generate a path to the resource */
    if( isset($docid) ){
      $docid = $docid;
        //$modx->log(modX::LOG_LEVEL_ERROR, "id2path - param: " . $docid );
	}
    elseif( is_Object($modx->resource) ) {
	    if( $modx->getPlaceholder('id') ) {
	        $docid = $modx->getPlaceholder('id');
            //$modx->log(modX::LOG_LEVEL_ERROR, "id2path - placeholder: " . $docid );
	    }    
	    else {
	        $docid = $modx->resource->get('id');
            //$modx->log(modX::LOG_LEVEL_ERROR, "id2path - is_Object: " . $docid );
	    }
    }
    
    else { 
        //try to get the actual resource out from HTTP_REFERER
    
        $parsedUrl = parse_url($_SERVER['HTTP_REFERER']);
        
        parse_str($parsedUrl['query'], $parsedQuery);
        
        if (isset($parsedQuery['amp;id']) ) {
            $docid = $parsedQuery['amp;id'];
        }
        if (isset($parsedQuery['id'])) {
            $docid = $parsedQuery['id'];
        }   
            //$modx->log(modX::LOG_LEVEL_ERROR, "id2path - referer: " . $docid );
    }
        
    
    $maxKey         = count( str_split( $maxDocs ) ) - 1;
    
    $digits         = str_split( $docid );
    $numberOfDigits = count( $digits );

    /* mirrow array */
    $digits = array_reverse($digits);
    
    /* increase array */
    for( $key=0; $key <= $maxKey ;$key++ ){
        if( !array_key_exists( $key, $digits ) ) {
            $digits[$key] = "0";
        }
    }

    /* mirrow array */
    $digits = array_reverse($digits);

    /* add trailing zeros to array values */
    foreach( $digits as $key => $value ) {
        $suffix = "";
        for( $i=$key; $i < $maxKey; $i++ ) {
	    $suffix .= "0";
        }
      $digits[$key] = $value.$suffix."/";
    }

    $docResourcePath = "";
    
    /* combine all values to a path*/
    foreach ( $digits as $key => $value ){
        $docResourcePath .= $value;
    }

  
    $modx->log(modX::LOG_LEVEL_ERROR, "id2path [" . $docid . "]" . $id2path );
  
    return $docResourcePath;