Core  3.2
PHP API documentation
 All Data Structures Namespaces Files Functions Variables Pages
exportfile.php
Go to the documentation of this file.
1 <?php
2 /*
3  * @author Anakeen
4  * @package FDL
5 */
6 /**
7  * Export Vault Files
8  *
9  * @author Anakeen
10  * @version $Id: exportfile.php,v 1.21 2008/05/20 15:26:48 eric Exp $
11  * @package FDL
12  * @subpackage
13  */
14 /**
15  */
16 
17 include_once ("FDL/Class.Doc.php");
18 include_once ("FDL/Class.DocAttr.php");
19 include_once ("FDL/Lib.Vault.php");
20 include_once ("VAULT/Class.VaultFile.php");
21 
22 define("RESIZEDIR", DEFAULT_PUBDIR . "/var/cache/file/");
23 // --------------------------------------------------------------------
24 function exportfile(Action & $action)
25 {
26  $dbaccess = $action->dbaccess;
27  $usage = new ActionUsage($action);
28  $usage->setDefinitionText("Download document attached file");
29  $docid = $usage->addOptionalParameter("docid", "document identifier", null, 0);
30  if (!$docid) {
31  $docid = $usage->addHiddenParameter("id", "document identifier");
32  }
33 
34  $vid = $usage->addHiddenParameter("vid", "vault file identifier - used for tmp file"); // only for construct url
35  $usage->addHiddenParameter("filename", "vault file name - not used"); // only for construct url
36  $attrid = $usage->addOptionalParameter("attrid", "attribute identifier");
37  $vaultid = $usage->addOptionalParameter("vaultid", "public file identifier");
38 
39  if (!$docid && $attrid === "-" && $vid > 0) {
40  $vaultid = $vid;
41  }
42  $index = $usage->addOptionalParameter("index", "attribute index identifier");
43  $imgwidth = $usage->addOptionalParameter("width", "image width use only when file is image");
44  $inline = ($usage->addOptionalParameter("inline", "inline download", array(
45  "yes",
46  "no"
47  )) == "yes");
48  $cache = ($usage->addOptionalParameter("cache", "use http cache", array(
49  "yes",
50  "no"
51  ) , "yes") == "yes");
52  $latest = $usage->addOptionalParameter("latest", "use latest revision", array(
53  "Y",
54  "N"
55  ));
56  $state = $usage->addOptionalParameter("state", "search doc in this state");
57  $type = $usage->addOptionalParameter("type", "transformation type", array(
58  "png",
59  "pdf"
60  ));
61  $pngpage = $usage->addOptionalParameter("page", "page number if type=pdf");
62 
63  $cvViewId = $usage->addOptionalParameter("cvViewid", "view control id");
64 
65  $usage->setStrictMode(false);
66  $usage->verify();
67  $isControled = false;
68  $othername = '';
69  if ($vaultid == 0) {
70 
72  if ($state != "") {
73  $docid = $doc->getRevisionState($state, true);
74  if ($docid == 0) {
75  header('HTTP/1.0 404 Document Not Found');
76  $action->exitError(sprintf(_("Document %s in %s state not found") , $doc->title, _($state)));
77  }
79  } else {
80  if (($latest == "Y") && ($doc->locked == - 1)) {
81  // get latest revision
82  $docid = $doc->getLatestId();
84  }
85  }
86  if (!$doc->isAffected()) {
87  header('HTTP/1.0 404 Document Not Found');
88  $action->exitError(sprintf(_("Document %s not found") , $docid));
89  }
90  // ADD CONTROL ACCESS HERE
91  $err = $doc->control("view");
92  if ($err != "") {
93  header('HTTP/1.0 403 Forbidden');
94  $action->exiterror($err);
95  }
96  $isControled = true;
97  $oa = null;
98 
99  if ($attrid !== "icon") {
100  $oa = $doc->getAttribute($attrid);
101  if (!$oa) {
102  header('HTTP/1.0 404 Attribute Not Found');
103  $action->exitError(sprintf(_("attribute %s not found") , $attrid));
104  } else {
105  if ($oa->type !== "file" && $oa->type !== "image") {
106  header('HTTP/1.0 403 Incorrect Attribute');
107  $action->exitError(sprintf("Not file attribute : %s ", $attrid));
108  }
109 
110  if ($cvViewId != "" && $doc->cvid > 0) {
111  /**
112  * @var \Dcp\Family\Cvdoc $cvdoc
113  */
114  $cvdoc = new_Doc($dbaccess, $doc->cvid);
115  $cvdoc = clone $cvdoc;
116  $cvdoc->Set($doc);
117  /*
118  * Apply mask from requested view
119  */
120  $err = $cvdoc->control($cvViewId); // control special view
121  if ($err != "") {
122  header('HTTP/1.0 403 Forbidden');
123  $action->exitError($err);
124  }
125  $tview = $cvdoc->getView($cvViewId);
126  if ($tview) {
127  $mask = $tview["CV_MSKID"];
128  if ($mask) {
129  $doc->applyMask($mask);
130  }
131  }
132  } else {
133  $doc->applyMask(Doc::USEMASKCVVIEW);
134  }
135  if ($oa->mvisibility == "I") {
136  header('HTTP/1.0 403 Forbidden');
137  $action->exitError(sprintf(_("Cannot see attribute %s") , $attrid));
138  }
139  }
140  }
141 
142  $ovalue = getExportFileDocumentValue($doc, $attrid, $index);
143 
144  if ($ovalue == "") {
145  header('HTTP/1.0 404 File Not Found');
146  print (sprintf(_("no file referenced for %s document") , $doc->title));
147  exit;
148  }
149 
150  if ($oa && $oa->getOption("preventfilechange") == "yes") {
151  if (preg_match(PREGEXPFILE, $ovalue, $reg)) {
152  $vaultid = $reg[2];
153  $othername = vault_uniqname($vaultid);
154  }
155  }
156 
157  preg_match(PREGEXPFILE, $ovalue, $reg);
158  $vaultid = $reg["vid"];
159  $mimetype = $reg["mime"];
160  $fileName = $reg["name"];
161 
163 
164  if ($fileName !== $fileInfo->name) {
165  // header('HTTP/1.0 403 Forbidden');
166  // $action->exitError(sprintf("Incorrect file identifier"));
167 
168  }
169  } else {
170  $mimetype = "";
171  }
172 
173  DownloadVault($action, $vaultid, $isControled, $mimetype, $imgwidth, $inline, $cache, $type, $pngpage, $othername);
174  exit;
175 }
176 
177 function getExportFileDocumentValue(\Doc $doc, $attrid, $index = - 1)
178 {
179 
180  if ($doc->control("view")) {
181  return "";
182  }
183 
184  if ($doc->doctype == "C") {
185  /*
186  * @var DocFam $doc
187  */
188  $ovalue = $doc->getParameterRawValue($attrid);
189  if (!$ovalue) $ovalue = $doc->getDefValue($attrid);
190  } else $ovalue = $doc->getRawValue($attrid);
191 
192  if (ctype_digit((string)$index) && ((int)$index >= 0)) {
193  $index = (int)$index;
194  $tvalue = Doc::rawValueToArray($ovalue);
195  if (!isset($tvalue[$index])) {
196  header('HTTP/1.0 404 File Not Found');
197  throw new Exception(sprintf(_("File not found at index '%s'") , $index));
198  }
199  $ovalue = $tvalue[$index];
200  }
201 
202  if ($attrid !== "icon") {
203  $oa = $doc->getAttribute($attrid);
204  if (!$oa) {
205  header('HTTP/1.0 404 Attribute Not Found');
206  throw new Exception(sprintf(_("attribute %s not found") , $attrid));
207  } else {
208  if ($oa->type !== "file" && $oa->type !== "image") {
209  header('HTTP/1.0 403 Incorrect Attribute');
210  throw new Exception(sprintf("Not file attribute : %s ", $attrid));
211  }
212  $doc->applyMask(Doc::USEMASKCVVIEW);
213  if ($oa->mvisibility == "I") {
214  header('HTTP/1.0 403 Forbidden');
215  throw new Exception(sprintf(_("Cannot see attribute %s") , $attrid));
216  }
217  }
218  } else {
219  $ovalue = $doc->icon;
220  }
221 
222  return $ovalue;
223 }
224 
225 function getExportFileDocumentPath(\Doc $doc, $attrid, $index = - 1)
226 {
227  $filePath = "";
228 
229  $fileValue = getExportFileDocumentValue($doc, $attrid, $index);
230 
231  if ($fileValue && preg_match(PREGEXPFILE, $fileValue, $reg)) {
232  $vaultid = $reg["vid"];
234  $filePath = $fileInfo->path;
235  }
236  return $filePath;
237 }
238 /**
239  * Idem like exportfile instead that download first file attribute found
240  * @param Action $action
241  * @throws \Dcp\Core\Exception
242  */
243 function exportfirstfile(Action & $action)
244 {
245 
246  $dbaccess = $action->dbaccess;
247  $docid = $action->getArgument("docid", $action->getArgument("id", 0));
248 
250  if (!$doc->isAffected()) {
251  $action->exitError(sprintf(_("unknow document reference '%s'") , $docid));
252  }
253  $attr = $doc->GetFirstFileAttributes();
254  if (!$attr) $action->exiterror(_("no attribute file found"));
255 
256  setHttpVar("attrid", $attr->id);
257 
258  exportfile($action);
259 }
260 // --------------------------------------------------------------------
261 function DownloadVault(Action & $action, $vaultid, $isControled, $mimetype = "", $width = "", $inline = false, $cache = true, $type = "", $pngpage = 0, $othername = '')
262 {
263  $dbaccess = $action->dbaccess;
265  /*
266  * @var vaultFileInfo $info
267  */
268  $info = null;
269  if ($type == "pdf") {
270  $teng_name = 'pdf';
271  $err = $vf->Show($vaultid, $info, $teng_name);
272  if ($err != "") $err = sprintf(_("PDF conversion not found")) . "\n$err";
273  } else {
274  $err = $vf->Show($vaultid, $info);
275  if (substr($info->mime_s, 0, 5) == "image") {
276  $type = "original";
277  }
278 
279  if ($type == "png") {
280  $teng_name = 'pdf';
281  $err = $vf->Show($vaultid, $info, $teng_name);
282  if ($err == "") {
283  $filecache = sprintf("%s/var/cache/file/vid-%s-%d.png", DEFAULT_PUBDIR, $info->id_file, $pngpage);
284  if (file_exists($filecache)) {
285  // print_r2($filecache);
286  $resample = true;
287  if ($resample) {
288  $filename = $filecache;
289  $imageSize = getimagesize($filename);
290  if ($imageSize === false) {
291  $err = ErrorCode::getError('FILE0001', $filename);
292  error_log($err);
294  }
295  $owidth = $imageSize[0];
296  $oheight = $imageSize[1];
297  if ($owidth == 0 || $oheight == 0) {
298  $err = ErrorCode::getError('FILE0002', $owidth, $oheight, $filename);
299  error_log($err);
301  }
302  $newwidth = $width;
303  $newheight = $oheight * ($width / $owidth);
304  // chargement
305  $thumb = imagecreatetruecolor($newwidth, $newheight);
306  $source = imagecreatefrompng($filename);
307  // Redimensionnement
308  imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $owidth, $oheight);
309  // Affichage
310  header('Content-type: image/png');
311  imagepng($thumb);
312  exit;
313  } else {
314  Http_DownloadFile($filecache, $info->name . ".png", "image/png", $inline, $cache);
315  exit;
316  }
317  }
318 
319  $cible = uniqid(getTmpDir() . "/thumb") . ".png";
320  if (!$width) $width = 150;
321  $quality = 200;
322  $resample = false;
323  // option 1
324  //$cmd=sprintf("gs -q -dSAFER -dBATCH -dNOPAUSE -sDEVICE=png16m -r%d -sOutputFile=- -dFirstPage=%d -dLastPage=%d %s | convert - -thumbnail %s %s", min(intval($width/8.06),$quality),$pngpage+1,$pngpage+1,$info->path,$width,$cible);
325  // option 2
326  $cmd = sprintf("convert -strip -thumbnail %s -auto-orient -density %d %s[%d] %s 2>&1", escapeshellarg($width) , $quality, escapeshellarg($info->path) , $pngpage, escapeshellarg($cible));
327  // option 3
328  //$cmd=sprintf("gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=png16m -r%d -sOutputFile=%s -dFirstPage=%d -dLastPage=%d %s", min(intval($width/8.06),$quality),$cible,$pngpage+1,$pngpage+1,$info->path);
329  // option 4
330  //$cmd=sprintf("gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=png16m -r%d -sOutputFile=%s -dFirstPage=%d -dLastPage=%d %s", min(intval($width/8.06),$quality),$cible,$pngpage+1,$pngpage+1,$info->path); $resample=true;
331  // option 5
332  //$cmd=sprintf("gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=png16m -r%d -sOutputFile=%s -dFirstPage=%d -dLastPage=%d %s", intval($width/8.06),$cible,$pngpage+1,$pngpage+1,$info->path);
333  exec($cmd, $out, $ret);
334 
335  if ($ret == 1) $err = implode("\n", $out);
336  if (file_exists($cible)) {
337  // update cache
338  if ($pngpage == 0) {
339  createPdf2Png($info->path, $info->id_file);
340  }
341  if ($resample) {
342  $filename = $cible;
343  $imageSize = getimagesize($filename);
344  if ($imageSize === false) {
345  $err = ErrorCode::getError('FILE0003', $filename);
346  error_log($err);
348  }
349  $owidth = $imageSize[0];
350  $oheight = $imageSize[1];
351  if ($owidth == 0 || $oheight == 0) {
352  $err = ErrorCode::getError('FILE0004', $owidth, $oheight, $filename);
353  error_log($err);
355  }
356  list($owidth, $oheight) = getimagesize($filename);
357  $newwidth = $width;
358  $newheight = $oheight * ($width / $owidth);
359  // chargement
360  $thumb = imagecreatetruecolor($newwidth, $newheight);
361  $source = imagecreatefrompng($filename);
362  // Redimensionnement
363  imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $owidth, $oheight);
364  // Affichage
365  header('Content-type: image/png');
366  imagepng($thumb);
367  exit;
368  } else {
369  Http_DownloadFile($cible, $info->name . ".png", "image/png", $inline, $cache);
370  }
371  unlink($cible);
372  exit;
373  } else $err = sprintf(_("cannot get image transformation for %s") , $info->name) . "\n$err";
374  } else {
376  $vf->Show($vaultid, $info);
377  if ($info) $err = sprintf(_("conversion png not found for %s") , $info->name) . "\n$err";
378  }
379  } else {
380 
381  if ((substr($info->mime_s, 0, 5) == "image") && ($width > 0)) {
382  $dest = rezizelocalimage($info->path, $width, $width . "-" . $info->id_file . ".png");
383  if ($dest) Http_DownloadFile($dest, $info->name . ".png", "image/png", $inline);
384  }
385  }
386  }
387 
388  if ($err != "") {
390  // Http_DownloadFile("FREEDOM/Images/doc.gif", "unknow", "image/gif");
391 
392  } else {
393  if ($info->mime_s) $mimetype = $info->mime_s;
394  //Header("Location: $url");
395  if ($isControled || ($info->public_access) || ($info->id_tmp)) {
396  $vf->storage->updateAccessDate($info->id_file);
397 
398  if (($mimetype != "image/jpeg") || ($width == 0)) {
399  if ($othername) $info->name = $othername;
400  Http_DownloadFile($info->path, $info->name, $mimetype, $inline, $cache);
401  } else {
402  $filename = $info->path;
403 
404  $name = str_replace('"', '-', $info->name);
405  $uName = iconv("UTF-8", "ASCII//TRANSLIT", $name);
406  $name = rawurlencode($name);
407  if ($inline) {
408  global $_SERVER;
409  $nav = $_SERVER['HTTP_USER_AGENT'];
410  $pos = strpos($nav, "MSIE");
411  if ($pos) {
412  // add special header for extension
413  header("Content-Disposition: inline;filename=\"$uName\";filename*=UTF-8''$name;");
414  }
415  } else {
416  header("Content-Disposition: attachment;filename=\"$uName\";filename*=UTF-8''$name;");
417  }
418  // header("Cache-Control: private, max-age=3600"); // use cache client (one hour) for speed optimsation
419  // header("Expires: ".gmdate ("D, d M Y H:i:s T\n",time()+3600)); // for mozilla
420  // header("Pragma: "); // HTTP 1.0
421  header('Content-type: image/jpeg');
422  // Calcul des nouvelles dimensions
423  list($owidth, $oheight) = getimagesize($filename);
424  $newwidth = $width;
425  $newheight = $oheight * ($width / $owidth);
426  // chargement
427  $thumb = imagecreatetruecolor($newwidth, $newheight);
428  $source = imagecreatefromjpeg($filename);
429  // Redimensionnement
430  imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $owidth, $oheight);
431  // Affichage
432  imagejpeg($thumb);
433  exit;
434  }
435  if (!$info->public_access) AddlogMsg(sprintf(_("%s has be sended") , $info->name));
436  } else {
437  $action->exiterror(_("file must be controlled : read permission needed"));
438  }
439  }
440 
441  exit;
442 }
443 /**
444  * send a text in a image file
445  * @param string $text text to display in the image
446  */
447 function sendimgerror($text)
448 {
449  // Set font size
450  $font_size = 4;
451 
452  if (seems_utf8($text)) $text = utf8_decode($text); // support only iso8859
453  $ts = explode("\n", $text);
454  $width = 0;
455  foreach ($ts as $string) {
456  $width = max($width, strlen($string));
457  }
458  // Create image width dependant on width of the string
459  $width = imagefontwidth($font_size) * $width;
460  // Set height to that of the font
461  $height = imagefontheight($font_size) * count($ts);
462  $el = imagefontheight($font_size);
463  $em = imagefontwidth($font_size);
464  // Create the image pallette
465  $img = imagecreatetruecolor($width, $height);
466  // Dark red background
467  $bg = imagecolorallocate($img, 0xAA, 0x00, 0x00);
468  // White font color
469  imagefilledrectangle($img, 0, 0, $width, $height, $bg);
470  $color = imagecolorallocate($img, 255, 255, 255);
471 
472  foreach ($ts as $k => $string) {
473  // Length of the string
474  $len = strlen($string);
475  // Y-coordinate of character, X changes, Y is static
476  // Loop through the string
477  for ($i = 0; $i < $len; $i++) {
478  // Position of the character horizontally
479  $xpos = $i * $em;
480  $ypos = $k * $el;
481  // Draw character
482  imagechar($img, $font_size, $xpos, $ypos, $string, $color);
483  // Remove character from string
484  $string = substr($string, 1);
485  }
486  }
487  // Return the image
488  header("Content-Type: image/png");
489  imagepng($img);
490  // Remove image
491  imagedestroy($img);
492  exit;
493 }
494 
496 {
497  $source = $img;
498 
500 
501  if (!is_dir(RESIZEDIR)) {
502  mkdir(RESIZEDIR);
503  }
504  if (!file_exists($dest)) {
505  $cmd = sprintf("convert -strip -auto-orient -thumbnail %d %s %s", $size, escapeshellarg($source) , escapeshellarg($dest));
506  system($cmd);
507  if (file_exists($dest)) return $dest;
508  } else {
509  return $dest;
510  }
511  return false;
512 }
513 
514 function createPdf2Png($file, $vid)
515 {
516  if (file_exists($file) && ($vid > 0)) {
517  $density = 200;
518  $width = 1200;
519  $nbpages = trim(shell_exec(sprintf('grep -c "/Type[[:space:]]*/Page>" %s', escapeshellarg($file))));
520  /* Remove existing cached files for the given $vid */
521  $dh = opendir(sprintf("%s/var/cache/file", DEFAULT_PUBDIR));
522  if ($dh !== false) {
523  while (($f = readdir($dh)) !== false) {
524  if ($f == '.' || $f == '..') {
525  continue;
526  }
527  if (preg_match(sprintf('/^vid-%s-/', preg_quote($vid, '/')) , $f)) {
528  unlink(sprintf("%s/var/cache/file/%s", DEFAULT_PUBDIR, $f));
529  }
530  }
531  }
532  /* Generate pages in background */
533  $cmd = array();
534  for ($i = 0; $i < $nbpages; $i++) {
535  $cible = DEFAULT_PUBDIR . "/var/cache/file/vid-${vid}-${i}.png";
536  $cmd[] = sprintf("nice convert -strip -interlace plane -thumbnail %d -density %d %s[%d] %s", $width, $density, escapeshellarg($file) , $i, escapeshellarg($cible));
537  }
538  bgexec($cmd, $result, $err);
539  }
540 }
$dest
Definition: resizeimg.php:231
vault_uniqname($idfile, $teng_name="")
Definition: Lib.Vault.php:127
seems_utf8($Str)
Definition: Lib.Common.php:759
global $action
newFreeVaultFile($dbaccess)
Definition: Lib.Util.php:17
& getAttribute($idAttr, &$oa=null, $useMask=true)
Definition: Class.Doc.php:2152
exportfirstfile(Action &$action)
Definition: exportfile.php:243
getExportFileDocumentValue(\Doc $doc, $attrid, $index=-1)
Definition: exportfile.php:177
const RESIZEDIR
Definition: exportfile.php:22
static rawValueToArray($v)
Definition: Class.Doc.php:6228
$vaultid
$size
Definition: resizeimg.php:110
$ret
$filename
$file
const PREGEXPFILE
Definition: Class.Doc.php:54
$mimetype
Definition: geticon.php:24
DownloadVault(Action &$action, $vaultid, $isControled, $mimetype="", $width="", $inline=false, $cache=true, $type="", $pngpage=0, $othername= '')
Definition: exportfile.php:261
static getError($code, $args=null)
Definition: ErrorCode.php:27
const DEFAULT_PUBDIR
Definition: Lib.Prefix.php:28
const USEMASKCVVIEW
Definition: Class.Doc.php:60
sendimgerror($text)
Definition: exportfile.php:447
createPdf2Png($file, $vid)
Definition: exportfile.php:514
exitError($texterr, $exit=true, $code="")
foreach($argv as $arg) $cmd
$docid
Definition: cleanFamily.php:13
static getFileInfo($idfile, $teng_name="")
Verify arguments for action function.
print
Definition: checklist.php:49
getTmpDir($def= '/tmp')
Definition: Lib.Common.php:150
global $_SERVER
switch($command) exit
Definition: checkVault.php:46
new_Doc($dbaccess, $id= '', $latest=false)
Http_DownloadFile($filename, $name, $mime_type= '', $inline=false, $cache=true, $deleteafter=false)
Definition: Lib.Http.php:225
$vf
Definition: geticon.php:28
static getArgument($k, $def= '')
$dbaccess
Definition: checkVault.php:17
getExportFileDocumentPath(\Doc $doc, $attrid, $index=-1)
Definition: exportfile.php:225
$info
Definition: geticon.php:30
rezizelocalimage($img, $size, $basedest)
Definition: exportfile.php:495
bgexec($tcmd, &$result, &$err)
Definition: Lib.Common.php:621
if($file) if($subject==""&&$file) if($subject=="") $err
getRawValue($idAttr, $def="")
Definition: Class.Doc.php:3117
$usage
$latest
control($aclname, $strict=false)
Definition: Class.Doc.php:6593
$basedest
Definition: resizeimg.php:230
← centre documentaire © anakeen