<?php
//ini_set('display_errors', 'on');
//error_reporting(1);
function get_pdf_pages($document)
{
  $f = $document;
  $stream = fopen($f, "r");
  $content = fread ($stream, filesize($f));
  if(!$stream || !$content)
    return 0;
  $count = 0;
  $regex  = "/\/Count\s+(\d+)/";
  $regex2 = "/\/Page\W*(\d+)/";
  $regex3 = "/\/N\s+(\d+)/";
  if(preg_match_all($regex, $content, $matches)){
    $count = count($matches);
  }else if(preg_match_all($regex2, $content, $matches)){
    $count = count($matches);
  }else if(preg_match_all($regex3, $content, $matches)){
    $count = count($matches);    
  }
  return $count;
}

function get_num_pages_docx($filename)
{
  $zip = new ZipArchive();
  if($zip->open($filename) === true)
  {
    if(($index = $zip->locateName('docProps/app.xml')) !== false)
    {
      $data = $zip->getFromIndex($index);
      $zip->close();
      $xml = new SimpleXMLElement($data);
      return $xml->Pages;
    }
    $zip->close();
  }
  return 0;
}


function get_pages_total($tmp){
  include("../core/utils/Utils.php");
  $utils = new Utils();
  $path = "../../uploads/tmp/".$tmp."/";
  $files = scandir($path);
  $files = array_diff(scandir($path), array('.', '..'));
  $total_files = 0;
  foreach($files as $item){
    $ext =strtolower($utils->GetFileExtension($item));
    if($ext=="txt" || $ext=="png" || $ext=="jpg" || $ext=="bmp"){
      $total_files+=1;
    }
    if($ext=="pdf"){
      $total_files+=get_pdf_pages("../../uploads/tmp/".$tmp."/".$item);
    }
    if($ext=="docx" || $ext=="doc"){
      $total_files+=get_num_pages_docx("../../uploads/tmp/".$tmp."/".$item);
    }
  }
  return $total_files;
}
