pepebe
6/12/2012 - 10:26 PM

MODx Revo: createResourceFolders Plugin

MODx Revo: createResourceFolders Plugin

<?php
/*  
   Every time a document is saved (OnDocFormSave), 
   the plugin checks if that document already has its own resource folder.
   If this is not the case, the folder is automatically created.
   Because you can't be sure if a media resource works as expected (you can't see the name of your currrent folder), 
   a textfile with a filename thats identical to the resource id is created inside this folder.

   

   Example for created folder structure: 
   id=1    => assets/0000/000/00/1/1.txt
   id=11   => assets/0000/000/10/1/11.txt
   id=111  => assets/0000/100/10/1/111.txt
   id=1111 => assets/1000/100/10/1/1111.txt
   
   you may a different directory instead of the assets directory. Just create a "resourceDir" system variable and set its value to a different folder.

   If you set resourceDir to resources/, you get a different path:
   id=1111 => resouces/1000/100/10/1/1111.txt
   
   http://wiki.modxcms.com/index.php/API:Document_(System_Event)#OnDocFormSave
*/

   /* -- Maximum number of expected documents -- */

   $maxDocs        = 9999;

   /* ------------------------------------------ */

   if ( !isset($id) OR empty($id) ) {
      return;
   }

   $docid = $id; /* $id is the id of the document */

   $baseUrl     = $modx->config['base_path'];
   
   /* Setup a resource directory in system settings. Defaults to assets */
   $resourceDir = ( !empty($modx->config['resourceDir']) ) ? $modx->config['resourceDir'] : "assets/";   
   
   $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;
   }
   
   $resourceFolder = $baseUrl.$resourceDir.$docResourcePath;
   $fileName = $id.".txt";
   
   if( !file_exists( $resourceFolder ) ) 
   {
       mkdir( $resourceFolder , 0755, TRUE );
   }

   if( file_exists( $resourceFolder ) && !file_exists( $resourceFolder."/".$fileName ) ) 
   {
       $fileHandler = fopen($resourceFolder."/".$fileName , 'w') or die();
       fclose($fileHandler);
   }

   return;