Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Andrey Knupp Vital

[Resolvido] DOMDocument - XML { PHP } , Parte - 5

Recommended Posts

Olá galera.. já que falei que ia dar continuidade ao esquema da galeria, esse Domingo não tive nada pra fazer mesmo =)

então acabei fazendo o sistema todo .. não deu tempo de revisar tudo, e eu já tava cansado .. então nen todos os codigos eu comentei

mais enfim .. ele funciona com o XML criado no disco, também não fiz sistema de login, apenas simulei um ID salvo numa session

que eu creio que a maioria faça assim, enfim .. qualquer outra implementação fica por conta de vocês

as funçionalidades basicas dele:

 

  • Cria um novo Album

  • Addiciona Fotos Para um Album

  • Deleta um Album

  • Deleta Alguma Foto de um Album

  • Visualiza fotos de um album

 

Os códigos:

 

index.php

<?php session_start(); ?>
<!doctype html>
<html>
   <head>
       <meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />
       <link rel="stylesheet" type="text/css" href="<?php echo getCurrentBase() ?>/css/style.css" />
       <script type="text/javascript">

       </script>
   </head>
   <body>
       <?php
           /**
            * Simulando um sistema de login
            */
           $_SESSION['uid'] = '1048';
           /**
            * Já que vamos usar htaccess para ficar uma URL elegante
            * é bonita, sem ? ou = , usaremos essa funçao pra retornar 
            * retornar a url completa de onde nos estamos 
            */
           function getCurrentBase(){
                 $Port = isset( $_SERVER['SERVER_PORT'] ) != '80' ? $_SERVER['SERVER_PORT'] : NULL;
                 $Http = isset( $_SERVER['HTTPS'] ) ? 'https://' : 'http://';
                 return $Http.$_SERVER['SERVER_NAME'].$Port.'/'.basename(getcwd());
           }
       ?>
       <div id="painel">
           <ul>
               <li><a href="<?php echo getCurrentBase() ?>/album">Criar Novo Album</a></li>
               <li><a href="<?php echo getCurrentBase() ?>/addPhotos">Addicionar Fotos Para um Album Existente</a></li>
               <li><a href="<?php echo getCurrentBase() ?>/removePhotos">Remover Fotos</a></li>
               <li><a href="<?php echo getCurrentBase() ?>/removeAlbum">Remover um Album</a></li>
               <li><a href="<?php echo getCurrentBase() ?>/displayPhotos">Ver Fotos</a></li>
           </ul>
       </div>
       <?php   
               /**
                * Procuro por um destino na url, concatenando com .php
                * já que todos os nossos arquivos serão os mesmos nomes do que 
                * o dos links, então podemos fazer assim 
                */
               $go = isset($_GET['go']) ? stripslashes($_GET['go']).'.php' : NULL;
               if($go != NULL){
                   /**
                    * Para não disparar um erro Logico, e desnecessário
                    * Antes de chamar o arquivo, verifico se ele existe
                    * antes de fazer a chamada 
                    */
                   if(file_exists( $go )){
                          require_once $go;
                   }
               }
       ?>
   </body>
</html>

addPhotos.php

<div id="conteudo">
   <ul class="albums">
       <?php
           $DOMDocument = new DOMDocument( '1.0', 'utf-8' );
           $DOMDocument->formatOutput = true;
           $DOMDocument->preserveWhiteSpace = false;
           $DOMDocument->load( 'albums/album-'.$_SESSION['uid'].'.xml' ); 
           $DOMXPath = new DOMXPath( $DOMDocument );
           $ABID = isset( $_GET['abid'] ) ? $_GET['abid'] : NULL;
           $AlbumID = explode('-',$ABID);
           if( $ABID == NULL ){
               echo 'Selecione o Album<hr>';
               foreach( $DOMXPath->query('.//album[@usuario="'.$_SESSION['uid'].'"]/capa') as $Album ){
                             echo '<li>';
                               echo '<a href="'.getCurrentBase().'/addPhotos/'.$Album->parentNode->getAttribute('id').'-'.$Album->parentNode->getAttribute('name').'">';
                               echo '<img src="'.getCurrentBase().$Album->getAttribute('src').'" width="150" height="150" /></a>';
                             echo '</li>';
                }
           }else{
               echo '<fieldset>';
                  echo '<form method="post" enctype="multipart/form-data">';
                    echo 'Foto: <input type="file" name="photo"><br />';
                    echo 'Classificação - 1<input type="radio" name="class" value="1" />';
                    echo '2<input type="radio" name="class" value="2" />';
                    echo '3<input type="radio" name="class" value="3" />';
                    echo '4<input type="radio" name="class" value="4" />';
                    echo '5<input type="radio" name="class" value="5" /><br /><br />';
                    echo 'Descrição<br /><textarea cols="30" rows="3" name="description"></textarea><br />';
                    echo 'Addicionar: <input type="submit" name="add" value="Addicionar Foto" />';
                  echo '</form>';
               echo '</fieldset>';
               if(isset( $_POST['add'] )){
                      $Photo = $_FILES['photo'];
                      $pathInfo =  pathinfo( $Photo['name'], PATHINFO_EXTENSION );
                      $AllowedExt = explode(',','jpg,bmp,png,gif');
                      if(array_search( $pathInfo,$AllowedExt ) === false){
                           echo sprintf('<b>%s</b>','Extensão do Arquivo Enviado Não é Válida');
                           exit;
                      }
                      $PhotoName = md5(uniqid().time().$AlbumCover['name']).'.'.$pathInfo;
                      $SelectedAlbum = $DOMXPath->query(".//album[@id=".$AlbumID[0]."]");
                      $Foto = $DOMDocument->createElement( 'foto', utf8_encode(htmlentities($_POST['description'])) );
                      $Foto->setAttribute( 'classificacao', $_POST['class'] );
                      $Foto->setAttribute( 'id', $SelectedAlbum->item(0)->getElementsByTagName('foto')->length+1 );
                      $Foto->setAttribute( 'src', '/fotos/'.$PhotoName );
                      $SelectedAlbum->item(0)->appendChild( $Foto );
                      if(move_uploaded_file($Photo['tmp_name'], './fotos/'.$PhotoName)){
                         $DOMDocument->save( 'albums/album-'.$_SESSION['uid'].'.xml' );
                      }

               }
           }
       ?>
   </ul>
</div>

Album.php

<div id="conteudo">
   <fieldset>
       <form method="post" enctype="multipart/form-data">
           Nome do Album: <input type="text" size="40" name="albumName" /><br />
           Capa do Album: <input type="file" name="albumCover" /><br />
           Criar Novo Album <input type="submit" name="newAlbum" value="Criar" />
       </form>
       <?php
            if( isset($_POST['newAlbum']) ){
                $AlbumName = strip_tags( $_POST['albumName'] );
                $AlbumCover = $_FILES['albumCover'];
                $pathInfo =  pathinfo( $AlbumCover['name'], PATHINFO_EXTENSION );
                $AllowedExt = explode(',','jpg,bmp,png,gif');
                if(array_search( $pathInfo,$AllowedExt ) === false){
                    echo sprintf('<b>%s</b>','Extensão do Arquivo Enviado Não é Válida');
                    exit;
                }
                $CapaFname = md5(uniqid().time().$AlbumCover['name']).'.'.$pathInfo;
                $DOMDocument = new DOMDocument( '1.0', 'utf-8' );
                $DOMDocument->formatOutput = true;
                if(!file_exists('albums/album-'.$_SESSION['uid'].'.xml')){
                    $Albums = $DOMDocument->appendChild( $DOMDocument->createElement( 'albums', '' ) );
                    $DOMDocument->appendChild( $Albums );
                    $Album = $DOMDocument->getElementsByTagName( 'albums' )->item(0);
                    $AlbumUsuario = $DOMDocument->createElement( 'album' );
                    $AlbumUsuario->setAttribute( 'usuario', $_SESSION['uid'] );
                    $AlbumUsuario->setAttribute( 'name', $AlbumName );
                    $AlbumUsuario->setAttribute( 'id', $DOMDocument->getElementsByTagName( 'album' )->length+1 );
                    $Album = $Album->appendChild( $AlbumUsuario );
                    $Capa = $DOMDocument->createElement( 'capa' );
                    $Capa->setAttribute( 'src', '/fotos/capas/'.$CapaFname );
                    $Album->appendChild( $Capa );
                    if(move_uploaded_file($AlbumCover['tmp_name'], './fotos/capas/'.$CapaFname)){
                        $DOMDocument->save( 'albums/album-'.$_SESSION['uid'].'.xml' );
                    }
                }else{
                    $DOMDocument->load( 'albums/album-'.$_SESSION['uid'].'.xml' );
                    $Album = $DOMDocument->getElementsByTagName( 'albums' )->item(0);
                    $AlbumUsuario = $DOMDocument->createElement( 'album' );
                    $AlbumUsuario->setAttribute( 'usuario', $_SESSION['uid'] );
                    $AlbumUsuario->setAttribute( 'name', $AlbumName );
                    $AlbumUsuario->setAttribute( 'id', $DOMDocument->getElementsByTagName( 'album' )->length+1 );
                    $Album = $Album->appendChild( $AlbumUsuario );
                    $Capa = $DOMDocument->createElement( 'capa' );
                    $Capa->setAttribute( 'src', '/fotos/capas/'.$CapaFname );
                    $Album->appendChild( $Capa );
                    if(move_uploaded_file($AlbumCover['tmp_name'], './fotos/capas/'.$CapaFname)){
                        $DOMDocument->save( 'albums/album-'.$_SESSION['uid'].'.xml' );
                    }
                }
            }
       ?>
   </fieldset>
</div>

displayPhotos.php

<div id="conteudo">
   <ul class="albums">
       <?php
       $DOMDocument = new DOMDocument( '1.0', 'utf-8' );
       $DOMDocument->formatOutput = true;
       $DOMDocument->preserveWhiteSpace = false;
       $DOMDocument->load( 'albums/album-'.$_SESSION['uid'].'.xml' ); 
       $DOMXPath = new DOMXPath( $DOMDocument );
       $ABID = isset( $_GET['abid'] ) ? $_GET['abid'] : NULL;
       $AlbumID = explode('-',$ABID);
       if( $AlbumID[0] == NULL ){
           foreach( $DOMXPath->query('.//album[@usuario="'.$_SESSION['uid'].'"]/capa') as $Album ){
                     echo '<li>';
                       echo '<a href="'.getCurrentBase().'/displayPhotos/'.$Album->parentNode->getAttribute('id').'-'.$Album->parentNode->getAttribute('name').'">';
                       echo '<img src="'.getCurrentBase().$Album->getAttribute('src').'" width="150" height="150" /></a>';
                       echo '<br />', $Album->parentNode->getElementsByTagName('foto')->length, ' Fotos';
                     echo '</li>';
           }
       }else{
           foreach( $DOMXPath->query('.//album[@id="'.$AlbumID[0].'"]') as $Fotos ){
                    foreach( $Fotos->getElementsByTagName('foto') as $Foto ){
                      echo '<li>';
                         echo '<img src="'.getCurrentBase().$Foto->getAttribute('src').'" width="100" height="100" title="Descrição: '.$Foto->nodeValue.'" /></a>';
                         echo '<br />Classificação: ', $Foto->getAttribute('classificacao');
                      echo '</li>';
                    }
           }
       }
       ?>
   </ul>
</div>

removeAlbum.php

<div id="conteudo">
   <ul class="albums">
   <?php
       /**
        * Nova instancia de DOMDocument
        */
       $DOMDocument = new DOMDocument( '1.0', 'utf-8' );
       #Formatação de output, Pra quando salvar o XML, ter uma boa identação
       $DOMDocument->formatOutput = true;

       #Não preservar espaços em branco redundantes
       $DOMDocument->preserveWhiteSpace = false;

       #Carrega o xml referente ao uid salvo na sessão
       $DOMDocument->load( 'albums/album-'.$_SESSION['uid'].'.xml' ); 

       #nova instancia de domxpath
       $DOMXPath = new DOMXPath( $DOMDocument );
       #Recupera o id do album na url
       $ABID = isset( $_GET['abid'] ) ? $_GET['abid'] : NULL;
       #separa o id do album , é o nome do album
       $AlbumID = explode('-',$ABID);
       #verifica se o id do album e diferente de null
       if( $AlbumID[0] != NULL ){
           #faço uma consulta no xml por um album com id referente ao da url
           $Album = $DOMXPath->query('.//album[@id="'.$AlbumID[0].'"]');
           #recupero todos os filhos de 'album' e salvo em um array os attributos de imagem
           foreach( $Album as $Nodes ){
                    foreach( $Nodes->childNodes as $Node ){
                             $Photos[] = $Node->getAttribute('src');
                    }
                    $Src[] = $Photos;
           }
           #removo o album selecionado do xml
           $Album->item(0)->parentNode->removeChild( $Album->item(0) );
           $DOMDocument->save( 'albums/album-'.$_SESSION['uid'].'.xml' );
           #deleto todas as fotos e capa do album selecionado do diretorio
           for( $i = 0; $i < sizeOf( $Src[0] ); $i++ ){
                unlink( '.'.$Src[0][$i] );
           }
           echo '<meta http-equiv="refresh" content="0;'.getCurrentBase().'" />';
           exit;
       }
       echo 'Selecione o album a ser removido<hr>';
       foreach( $DOMXPath->query('.//album[@usuario="'.$_SESSION['uid'].'"]/capa') as $Album ){
                     echo '<li>';
                       echo '<a href="'.getCurrentBase().'/removeAlbum/'.$Album->parentNode->getAttribute('id').'-'.$Album->parentNode->getAttribute('name').'">';
                       echo '<img src="'.getCurrentBase().$Album->getAttribute('src').'" width="150" height="150" /></a>';
                     echo '</li>';
        }
   ?>
   </ul>
</div>

removePhotos.php

<div id="conteudo">
   <ul class="albums">
       <?php
           /*
            * Nova instancia de domdocument
            */
           $DOMDocument = new DOMDocument( '1.0', 'utf-8' );
           #Formatação de output, Pra quando salvar o XML, ter uma boa identação
           $DOMDocument->formatOutput = true;

           #Não preservar espaços em branco redundantes
           $DOMDocument->preserveWhiteSpace = false;
           #Carrega o xml referente ao uid salvo na sessão
           $DOMDocument->load( 'albums/album-'.$_SESSION['uid'].'.xml' ); 

           #nova instancia de domxpath
           $DOMXPath = new DOMXPath( $DOMDocument );
           #Recupera o id do album na url
           $ABID = isset( $_GET['abid'] ) ? $_GET['abid'] : NULL;
           #separa o id do album , é o nome do album
           $AlbumID = explode('-',$ABID);
           #verifica se o id do album e diferente de null e se não tiver setado nenhum id de foto
           if( $ABID == NULL && !isset( $_GET['fid']) ){
               echo 'Selecione o Album<hr>';
               #procura os albums do usuario, onde o id e referente ao salvo na session, avança para tag capa
               foreach( $DOMXPath->query('.//album[@usuario="'.$_SESSION['uid'].'"]/capa') as $Album ){
                             echo '<li>';
                               echo '<a href="'.getCurrentBase().'/removePhotos/'.$Album->parentNode->getAttribute('id').'-'.$Album->parentNode->getAttribute('name').'">';
                               echo '<img src="'.getCurrentBase().$Album->getAttribute('src').'" width="150" height="150" /></a>';
                             echo '</li>';
                }
                #se não estiver setado nenhum id de foto
           }elseif(!isset($_GET['fid'])){
                #se não estiver nenhuma foto referente ao uid, exibe a mensagem e para o script
                if( !$DOMXPath->query(".//album[@id=".$AlbumID[0]."]")->item(0)->getElementsByTagName('foto')->length ){
                     echo 'Não Existe nenhuma fotografia nesse album';
                     exit;
                }
                #pra cada album referente ao id da url, avança pra tag foto .. exibe os <li> com as fotografias
                foreach( $DOMXPath->query(".//album[@id=".$AlbumID[0]."]/foto") as $AlbumNodes ){
                            echo '<li>';
                             echo '<a href="'.getCurrentBase().'/removePhotos/albumid/'.$AlbumID[0].'/fid/'.$AlbumNodes->getAttribute('id').'">';
                             echo '<img src="'.getCurrentBase().$AlbumNodes->getAttribute('src').'" width="60" height="60" /></a>';
                            echo '</li>';  
                }
               #se estiver setado o id de alguma foto
           }elseif(isset($_GET['fid'])){
                 #pega a foto selecionada na url, e então remove a foto juntamente com foto movida para o diretorio quando fez upload
                 $SelectedPhoto = $DOMXPath->query(".//album[@id=".$_GET['aid']."]/foto[@id=".$_GET['fid']."]")->item(0);
                 if( $DOMXPath->query(".//album[@id=".$_GET['aid']."]/foto[@id=".$_GET['fid']."]")->length ){
                     $SelectedPhotoSrc = $SelectedPhoto->getAttribute( 'src' );
                     $SelectedPhoto->parentNode->removeChild( $SelectedPhoto );
                     $DOMDocument->save( 'albums/album-'.$_SESSION['uid'].'.xml' );
                     unlink('.'.$SelectedPhotoSrc);
                     echo '<meta http-equiv="refresh" content="0;'.getCurrentBase().'/removePhotos" />';
                     exit;
                 }else{
                     echo 'A Foto que você está tentando remover não existe';
                 }
           }
         ?>
</div>

css/style.css

body{
   font-family: 'Calibri', Verdana, Arial, Tahoma, Sans-serif, Monospace;
   font-size: 15px;
   font-weight: normal;
}
ul{
   list-style: none;
   margin: 0px;
   padding: 0px;
}
#painel ul{
   background-color: #ffffcb;
   width: 270px;
   padding: 10px;
   border: 1px solid #ffd986;
   float: left;
   margin: 0px;
}
#painel ul li a{
   text-decoration: none;
   color: #61a131;
   font-weight: normal;
   font-style: italic;
}
#painel ul li a:hover{
   border-bottom: 1px dotted #61a131;
   font-weight :bolder;
}
#conteudo{
   margin-left: 5px;
   float: left;
   border: 1px solid #a7d189;
   padding: 5px;
   background-color: #f6fef0;
}
fieldset{
   border: none;
}
.albums li{
   float: right;
}

 

.htaccess

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule ^album$ index.php?go=album
  RewriteRule ^addPhotos$ index.php?go=addPhotos
  RewriteRule ^removePhotos$ index.php?go=removePhotos
  RewriteRule ^removeAlbum$ index.php?go=removeAlbum
  RewriteRule ^displayPhotos$ index.php?go=displayPhotos
  RewriteRule ^displayPhotos/([a-zA-Z0-9-]*)$ index.php?go=displayPhotos&abid=$1 [NC,QSA]
  RewriteRule ^addPhotos/([a-zA-Z0-9-]*)$ index.php?go=addPhotos&abid=$1 [NC,QSA]
  RewriteRule ^removePhotos/([a-zA-Z0-9-]*)$ index.php?go=removePhotos&abid=$1 [NC,QSA]
  RewriteRule ^removePhotos/albumid/([a-zA-Z0-9-]*)/fid/([a-zA-Z0-9-]*)$ index.php?go=removePhotos&aid=$1&fid=$2 [NC,QSA]
  RewriteRule ^removeAlbum/([a-zA-Z0-9-]*)$ index.php?go=removeAlbum&abid=$1 [NC,QSA]
</IfModule>

Diretorio: /albums, /fotos, /fotos/capas

 

Quem quiser baixar os arquivos, Clique aqui

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.