DataObjects/Images.php
[Pman.Core] / DataObjects / Images.php
1 <?php
2 /**
3  * Table Definition for Images
4  */
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
6
7 class Pman_Core_DataObjects_Images extends DB_DataObject 
8 {
9     ###START_AUTOCODE
10     /* the code below is auto generated do not remove the above tag */
11
12     public $__table = 'Images';                          // table name
13     public $id;                              // int(11)  not_null primary_key auto_increment
14     public $filename;                        // string(255)  not_null
15     public $ontable;                         // string(32)  not_null multiple_key
16     public $onid;                            // int(11)  not_null
17     public $mimetype;                        // string(64)  not_null
18     public $width;                           // int(11)  not_null
19     public $height;                          // int(11)  not_null
20     public $filesize;                        // int(11)  not_null
21     public $displayorder;                    // int(11)  not_null
22     public $language;                        // string(6)  not_null
23     public $parent_image_id;                 // int(11)  not_null
24     public $created;                         // datetime(19)  not_null binary
25     public $imgtype;                         // string(32)  not_null
26     public $linkurl;                         // string(254)  not_null
27     public $descript;                        // blob(65535)  not_null blob
28     public $title;                           // string(128)  not_null
29     
30     /* the code above is auto generated do not remove the tag below */
31     ###END_AUTOCODE
32     function applyFilters($q, $au, $roo)
33     {
34         $tn = $this->tableName();
35         
36         if(!empty($q['search']['filename'])){
37             $this->whereAdd("
38                 $tn.filename LIKE '%{$this->escape($q['search']['filename'])}%'
39             ");
40                 echo $this->whereAdd("
41                 $tn.filename LIKE '%{$this->escape($q['search']['filename'])}%'
42             "); die;
43         }
44         
45
46     }
47     
48     function checkPerm($lvl, $au)
49     {
50         // default permissons are to
51         // allow create / edit / if the user has
52         
53         if (!$au) {
54             return false;
55         }
56         
57         $o = $this->object();
58         //print_r($o);
59         if (method_exists($o, 'checkPerm')) {
60             // edit permissions on related object needed...
61             return $o->checkPerm( $lvl == 'S' ? 'S' : 'E' , $au);
62             
63         }
64         
65         return true; //// ??? not really that safe...
66         
67     }
68     
69     function beforeInsert($q, $roo) 
70     {
71         if (isset($q['_remote_upload'])) {
72             require_once 'System.php';
73             
74             $tmpdir  = System::mktemp("-d remote_upload");
75             
76             $path = $tmpdir . '/' . basename($q['_remote_upload']);
77             
78             if(!file_exists($path)){
79                file_put_contents($path, file_get_contents($q['_remote_upload'])); 
80             }
81             
82             $imageInfo = getimagesize($path);
83             
84             require_once 'File/MimeType.php';
85             $y = new File_MimeType();
86             $ext = $y->toExt(trim((string) $imageInfo['mime'] ));
87             
88             if (!preg_match("/\." . $ext."$/", $path, $matches)) {
89                 rename($path,$path.".".$ext);
90                 $path.= ".".$ext;
91             }
92             
93             if (!$this->createFrom($path)) {
94                 $roo->jerr("erro making image" . $q['_remote_upload']);
95             }
96             
97             if(!empty($q['_return_after_create'])){
98                 return;
99             }
100             
101             $roo->addEvent("ADD", $this, $this->toEventString());
102         
103             $r = DB_DataObject::factory($this->tableName());
104             $r->id = $this->id;
105             $roo->loadMap($r);
106             $r->limit(1);
107             $r->find(true);
108             $roo->jok($r->URL(-1,'/Images') . '#attachment-'.  $r->id);
109         }
110         
111     }
112     
113      
114     /**
115      * create an email from file.
116      * these must have been set first.
117      * ontable / onid.
118      * 
119      */
120     function createFrom($file, $filename=false)
121     {
122         // copy the file into the storage area..
123         if (!file_exists($file) || !filesize($file)) {
124             $this->err = "File $file did not exist or is 0 size";
125             return false;
126         }
127         
128         $filename = empty($filename) ? $file : $filename;
129         
130         if (empty($this->mimetype)) {
131             require_once 'File/MimeType.php';
132             $y = new File_MimeType();
133             $this->mimetype = $y->fromFilename($filename);
134         }
135         
136         $this->mimetype = strtolower($this->mimetype);
137         
138         $mta = explode('/', $this->mimetype);
139         if (array_shift($mta) == 'image') { 
140         
141             $imgs = @getimagesize($file);
142             
143             if (empty($imgs) || empty($imgs[0]) || empty($imgs[1])) {
144                 // it's a file!!!!
145             } else {
146                 list($this->width , $this->height)  = $imgs;
147             }
148         }
149         
150         if($this->mimetype == 'application/pdf'){
151             $this->no_of_pages = $this->getPdfPages($file);
152         }
153         
154         $this->filesize = filesize($file);
155         $this->created = date('Y-m-d H:i:s');
156          
157         
158         if (empty($this->filename)) {
159             $this->filename = basename($filename);
160         }
161         
162         //DB_DataObject::debugLevel(1);
163         if (!$this->id) {
164             $this->insert();
165         } else {
166             $this->update();
167         }
168         
169         
170         
171         $f = $this->getStoreName();
172         $dest = dirname($f);
173         if (!file_exists($dest)) {
174             // currently this is 0775 due to problems using shared hosing (FTP)
175             // it makes all the files unaccessable..
176             // you can normally solve this by giving the storedirectory better perms
177             // if needed on a dedicated server..
178             $oldumask = umask(0);
179             mkdir($dest, 0775, true);
180             umask($oldumask);  
181         }
182         
183         copy($file,$f);
184         
185         // fill in details..
186         
187         /* thumbnails */
188         
189      
190        // $this->createThumbnail(0,50);
191         return true;
192         
193     }
194
195     /**
196      * Calculate target file name
197      *
198      * @return - target file name
199      */
200     function getStoreName() 
201     {
202         $opts = HTML_FlexyFramework::get()->Pman;
203         $fn = preg_replace('/[^a-z0-9\.]+/i', '_', $this->filename);
204         return implode( '/', array(
205             $opts['storedir'], '_images_', date('Y/m', strtotime($this->created)), $this->id . '-'. $fn
206         ));
207           
208     }
209      
210     /**
211      * deletes all the image instances of it...
212      * 
213      * 
214      */
215     function beforeDelete($dependants_array, $roo)
216     {
217         
218         $opts = HTML_FlexyFramework::get()->Pman;
219         $deldir = $opts['storedir']. '/_deleted_images_';
220         if (!file_exists( $deldir )) {
221             mkdir($deldir, 0755);
222         }
223             
224         $fn = $this->getStoreName();
225         $b = basename($fn);
226         if (file_exists($fn)) {
227             
228             if (file_exists($deldir . '/'. $b)) {
229                 unlink($fn);
230             } else {
231                 rename($fn, $deldir .'/'. $b);
232             }
233             
234             
235         }
236         // delete thumbs..
237         
238         $d = dirname($fn);
239         if (file_exists($d)) {
240                 
241             $dh = opendir($d);
242             while (false !== ($fn = readdir($dh))) {
243                 if (substr($fn, 0, strlen($b)) == $b) {
244                     
245                     if (file_exists($deldir . '/'. $fn)) {
246                         unlink($d. '/'. $fn);
247                         continue;
248                     }
249                     rename($d. '/'. $fn, $deldir .'/'. $fn);
250                     
251                 }
252             }
253         }
254         
255     }
256     /**
257      * check mimetype against type
258      * - eg. img.is(#image#)
259      *
260      */
261     function is($type)
262     {
263         if (empty($this->mimetype)) {
264             return false;
265         }
266         return 0 === strcasecmp($type, array_shift(explode('/',$this->mimetype)));
267     }
268   
269     /**
270      * onUpload (singlely attached image to a table)
271      */
272     
273     function onUploadWithTbl($tbl,  $fld)
274     {
275         if ( $tbl->__table == 'Images') {
276             return; // not upload to self...
277         }
278         if (empty($_FILES['imageUpload']['tmp_name']) || 
279             empty($_FILES['imageUpload']['name']) || 
280             empty($_FILES['imageUpload']['type'])
281         ) {
282             return false;
283         }
284         if ($tbl->$fld) {
285             HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
286             exit;
287             $image = DB_DataObject::factory('Images');
288             $image->get($tbl->$fld);
289             $image->beforeDelete();
290             $image->delete();
291         }
292         
293         $image = DB_DataObject::factory('Images');
294         $image->onid = $tbl->id;
295         $image->ontable = $tbl->__table;
296         $image->filename = $_FILES['imageUpload']['name']; 
297         $image->mimetype = $_FILES['imageUpload']['type'];
298        
299         if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
300             return false;
301         }
302         $old = clone($tbl);
303         $tbl->$fld = $image->id;
304         $tbl->update($old);
305          
306     }
307     
308     // direct via roo...
309     /// ctrl not used??
310     function onUpload($roo)
311     {
312         //print_r($_FILES); echo $_FILES['imageUpload']['type'];exit;
313         if (empty($_FILES['imageUpload']['tmp_name']) || 
314             empty($_FILES['imageUpload']['name']) || 
315             empty($_FILES['imageUpload']['type'])
316         ) {
317             
318             $emap = array( 
319                 0=>"There is no error, the file uploaded with success", 
320                 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini", 
321                 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" ,
322                 3=>"The uploaded file was only partially uploaded",
323                 4=>"No file was uploaded",
324                 6=>"Missing a temporary folder" 
325             ); 
326             $estr = (empty($_FILES['imageUpload']['error']) ? '?': $emap[$_FILES['imageUpload']['error']]);
327             $this->err = "Missing file details : Error=". $estr;
328             return false;
329         }
330         
331         if ($this->id) {
332             HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
333             exit;
334             $this->beforeDelete();
335         }
336         if ( empty($this->ontable)) {
337             $this->err = "Missing  ontable";
338             return false;
339         }
340         
341         if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
342             // then its an upload 
343             $img  = DB_DataObject::factory('Images');
344             $img->onid = $this->onid;
345             $img->ontable = $this->ontable;
346             $img->imgtype = $this->imgtype;
347             
348             $img->find();
349             while ($img->fetch()) {
350                 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
351                 exit;
352                 $img->beforeDelete();
353                 $img->delete();
354             }
355             
356         }
357         
358         
359         
360         require_once 'File/MimeType.php';
361         $y = new File_MimeType();
362         $this->mimetype = $_FILES['imageUpload']['type'];
363         if (in_array($this->mimetype, array(
364                         'text/application',
365                         'application/octet-stream',
366                         'image/x-png',  // WTF does this?
367                         'image/pjpeg',  // WTF does this?
368                         'application/x-apple-msg-attachment', /// apple doing it's magic...
369                         'application/vnd.ms-excel',   /// sometimes windows reports csv as excel???
370                         'application/csv-tab-delimited-table', // windows again!!?
371                 ))) { // weird tyeps..
372             $inf = pathinfo($_FILES['imageUpload']['name']);
373             $this->mimetype  = $y->fromExt($inf['extension']);
374         }
375         
376         
377         $ext = $y->toExt(trim((string) $this->mimetype ));
378         
379         $this->filename = empty($this->filename) ? 
380             $_FILES['imageUpload']['name'] : ($this->filename .'.'. $ext); 
381         
382         
383         
384         if (!$this->createFrom($_FILES['imageUpload']['tmp_name'])) {
385             $this->err  =  isset($this->err)  ?  $this->err  : "createFrom Image failed";
386             return false;
387         }
388         return true;
389          
390     }
391      
392     
393     
394     /**
395      * return a list of images for an object, optionally with a mime regex.
396      * eg. '%/pdf' or 'image/%'
397      *
398      * usage:
399      *
400      * $i = DB_DataObject::factory('Images');
401      * $i->imgtype = 'LOGO';
402      * $ar = $i->gather($somedataobject, 'image/%');
403      * 
404      * @param {DB_DataObject} dataobject  = the object to gather data on.
405      * @param {String} mimelike  LIKE query to use for search
406      
407      */
408     function gather($obj, $mime_like='', $opts=array())
409     {
410         //DB_DataObject::debugLevel(1);
411         if (empty($obj->id)) {
412             return array();
413         }
414         
415         $c = clone($this);
416         $c->whereAddIn($this->tableName() . '.ontable', array( $obj->tableName(), $obj->__table) , 'string');
417         $c->onid = $obj->id;
418         $c->autoJoin();
419         if (!empty($mime_like)) {
420             $c->whereAdd("Images.mimetype LIKE '". $c->escape($mime_like) ."'");
421         }
422         $c->orderBy('created DESC');
423
424         return $c->fetchAll();
425     }
426      
427     
428     /**
429     * set or get the dataobject this image is associated with
430     * @param DB_DataObject $obj An object to associate this image with
431     *        (does not store it - you need to call update() to do that)
432     * @return DB_DataObject the dataobject this image is attached to.
433     */
434     function object($obj=false)
435     {
436         if ($obj === false) {
437             if (empty($this->ontable) || empty($this->onid)) {
438                 return false;
439             }
440             $ret = DB_DataObject::factory($this->ontable);
441             $ret->get($this->onid);
442             return $ret;
443         }
444         
445         
446         $this->ontable = $obj->tableName();
447         $this->onid = $obj->id; /// assumes our nice standard of using ids..
448         return $obj;
449     }
450     
451      
452     function toRooArray($req) {
453         
454         $ret= $this->toArray();
455       
456         static $ff = false;
457         if (!$ff) {
458             $ff = HTML_FlexyFramework::get();
459         }
460         
461         $ret['public_baseURL'] = isset($ff->Pman_Images['public_baseURL']) ?
462                     $ff->Pman_Images['public_baseURL'] : $ff->baseURL;
463         
464         if (!empty($req['query']['imagesize'])) {
465             // query/imageBaseURL ... depricated...? -- set it in config?
466             
467             $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : $ret['public_baseURL'];
468             
469             $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
470             
471             $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);    
472             
473             if (!empty($req['query']['imagesize'])) {
474                 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
475             }
476         }
477         
478          
479          
480         return $ret;
481     }
482     
483     /**
484      * URL - create  a url for the image.
485      * size - use -1 to show full size.
486      * provier = baseURL + /Images/Thumb ... use '/Images/' for full
487      * 
488      * 
489      */
490     function URL($size , $provider = '/Images/Thumb', $baseURL=false)
491     {
492         if (!$this->id) {
493             return 'about:blank';
494             
495         }
496
497         $ff = HTML_FlexyFramework::get();
498         $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
499         if (preg_match('#^http[s]*://#', $provider)) {
500             $baseURL = '';
501         }
502        
503         if ($size < 0) {
504             $provider = preg_replace('#/Thumb$#', '', $provider);
505             
506             return $baseURL . $provider . "/{$this->id}/{$this->filename}";
507         }
508         //-- max?
509         //$size = max(100, (int) $size);
510         //$size = min(1024, (int) $size);
511         // the size should 200x150 to convert
512         $sizear = preg_split('/(x|c)/', $size);
513         if(empty($sizear[1])){
514             $sizear[1] = 0;
515         }
516         $size = implode(strpos($size,'c') > -1 ? 'c' : 'x', $sizear);
517 //        print_r($size);
518         $fc = $this->toFileConvert();
519 //        print_r($size);
520 //        exit;
521         $mt = $this->mimetype;
522         if (!preg_match('#^image/#i',$mt)) {
523             $mt = 'image/jpeg';
524         }
525         
526         $fc->convert($mt, $size);
527         
528         return $baseURL . $provider . "/$size/{$this->id}/{$this->filename}";
529     }
530     /**
531      * size could be 123x345
532      * 
533      * 
534      */
535     function toHTML($size, $provider = '/Images/Thumb') 
536     {
537         
538         
539         
540         $sz = explode('x', $size);
541         $sx = $sz[0];
542         //var_dump($sz);
543         if (!$this->id || empty($this->width)) {
544             $this->height = $sx;
545             $this->width = empty($sz[1]) ? $sx : $sz[1];
546             $sy = $this->width ;
547         }
548         if (empty($sz[1])) {
549             $ratio =  empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
550             $sy = $ratio * $sx;
551         } else {
552             $sy = $sz[1];
553         }
554         // create it?
555         $extra = '';
556         if (strlen($this->title)) {
557             $extra = ' title="'. htmlspecialchars($this->title) . '"';
558         }
559         
560         return '<img src="' . $this->URL($size, $provider) . '"' .
561                 $extra .
562                 ' width="'. $sx . '"' .
563                 ' height="'. $sy . '">';
564         
565         
566     }
567     
568     /**
569      * 
570      * #2142 [new] CMS - image link urls
571      * 
572      * 
573      * 
574      */
575     function toLinkHTML($size, $provider = '/Images/Thumb')
576     {
577         if(empty($this->linkurl)){
578             return $this->toHTML($size, $provider = '/Images/Thumb');
579         }
580         
581         return '<a href="'.$this->linkurl.'" target="_blank">'.$this->toHTML($size, $provider = '/Images/Thumb').'</a>';
582         
583     }
584     
585     
586     /**
587      * to Fileconvert object..
588      *
589      *
590      *
591      */
592     function toFileConvert()
593     {
594         require_once 'File/Convert.php';
595         $fc = new File_Convert($this->getStoreName(), $this->mimetype);
596         return $fc;
597         
598     }
599     
600     function fileExt()
601     {
602         require_once 'File/MimeType.php';
603         
604         $y = new File_MimeType();
605         return  $y->toExt($this->mimetype);
606         
607         
608     }
609     
610     /**
611      *
612      *
613      *
614      */
615     
616     
617     function setFromRoo($ar, $roo)
618     {
619         // not sure why we do this.. 
620         
621         // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
622         if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
623             $this->setFrom($ar);
624             $this->limit(1);
625             if ($this->find(true)) {
626                 $roo->old = clone($this);
627             }
628         }   
629             
630         
631         if (!empty($ar['_copy_from'])) {
632             
633             if (!$this->checkPerm( 'A' , $roo->authUser))  {
634                 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
635             }
636             
637             $copy = DB_DataObject::factory('Images');
638             $copy->get($ar['_copy_from']);
639             $this->setFrom($copy->toArray());
640             $this->setFrom($ar);
641             $this->createFrom($copy->getStoreName());
642             
643             $roo->addEvent("ADD", $this, $this->toEventString());
644             
645             $r = DB_DataObject::factory($this->tableName());
646             $r->id = $this->id;
647             $roo->loadMap($r);
648             $r->limit(1);
649             $r->find(true);
650             $roo->jok($r->toArray());
651             
652             
653         }
654         
655          
656         
657         // FIXME - we should be checking perms here...
658        
659         // this should be doign update
660         $this->setFrom($ar);
661          
662         if (!$this->checkPerm($this->id ? 'A' : 'E', $roo->authUser))  {
663             $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
664         }
665         
666         
667         
668         if (!isset($_FILES['imageUpload'])) {
669             return; // standard update...
670         }
671         
672         
673 //        print_r(!$this->onUpload($this));
674         
675         if ( !$this->onUpload($this)) { 
676             $roo->jerr("File upload failed : error = ". (!empty($this->err) ? $this->err : ''));
677         }
678         
679         $this->addEvent($ar, $roo);
680         
681         $r = DB_DataObject::factory($this->tableName());
682         $r->id = $this->id;
683         $roo->loadMap($r);
684         $r->limit(1);
685         $r->find(true);
686         $roo->jok($r->toArray());
687          
688     }
689     
690     function addEvent($ar, $roo)
691     {
692         $roo->addEvent("ADD", $this, $this->toEventString());
693     }
694     
695     function toEventString()
696     {
697         
698         //$p = DB_DataObject::factory($this->ontable);
699         //if (!is_$p) {
700         //    return "ERROR unknown table? {$this->ontable}";
701        // }
702         //$p->get($p->onid);
703         
704         return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
705         //$p->toEventString();
706     }
707     
708     function onUploadFromData($data, $roo)
709     {
710         if (empty($data)) {
711             $this->err = "Missing file details";
712             return false;
713         }
714         
715         if ($this->id) {
716             HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
717             exit;
718             $this->beforeDelete();
719         }
720         
721         if (empty($this->ontable)) {
722             $this->err = "Missing  ontable";
723             return false;
724         }
725         
726         if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
727             // then its an upload 
728             $img  = DB_DataObject::factory('Images');
729             $img->onid = $this->onid;
730             $img->ontable = $this->ontable;
731             $img->imgtype = $this->imgtype;
732             
733             $img->find();
734             while ($img->fetch()) {
735                 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
736                 exit;
737                 $img->beforeDelete();
738                 $img->delete();
739             }
740             
741         }
742         
743         require_once 'File/MimeType.php';
744         $y = new File_MimeType();
745         
746         if (in_array($this->mimetype, array(
747                         'text/application',
748                         'application/octet-stream',
749                         'image/x-png',  // WTF does this?
750                         'image/pjpeg',  // WTF does this?
751                         'application/x-apple-msg-attachment', /// apple doing it's magic...
752                         'application/vnd.ms-excel',   /// sometimes windows reports csv as excel???
753                         'application/csv-tab-delimited-table', // windows again!!?
754                 ))) { // weird tyeps..
755             $inf = pathinfo($this->filename);
756             $this->mimetype  = $y->fromExt($inf['extension']);
757         }
758         
759         $ext = $y->toExt(trim((string) $this->mimetype ));
760         
761         if(array_pop(explode('.', $this->filename)) != $ext){
762             $this->filename = $this->filename .'.'. $ext; 
763         }
764         
765         if (!$this->createFromData($data)) {
766             return false;
767         }
768         
769         return true;
770          
771     }
772     
773     function createFromData($data)
774     {   
775         
776         $this->mimetype= strtolower($this->mimetype);
777         
778         if (array_shift(explode('/', $this->mimetype)) == 'image') { 
779         
780             $imgs = @getimagesize($data);
781             
782             if (!empty($imgs) && !empty($imgs[0]) && !empty($imgs[1])) {
783                 list($this->width , $this->height)  = $imgs;
784             }
785         }
786         
787         $this->created = date('Y-m-d H:i:s');
788         
789         if (!$this->id) {
790             $this->insert();
791         } else {
792             $this->update();
793         }
794         
795         $f = $this->getStoreName();
796         $dest = dirname($f);
797         if (!file_exists($dest)) {
798             $oldumask = umask(0);
799             mkdir($dest, 0775, true);
800             umask($oldumask);  
801         }
802         
803         file_put_contents($f, file_get_contents("data://" . $data));
804         
805         $o = clone($this);
806         
807         $this->filesize = filesize($f);
808         
809         if($this->mimetype == 'application/pdf'){
810             $this->no_of_pages = $this->getPdfPages($f);
811         }
812         
813         $this->update($o);
814         
815         return true;
816         
817     }
818     
819     function toBase64()
820     {
821         if(!preg_match('/^image\//', $this->mimetype)){
822             return false;
823         }
824         
825         $file = $this->getStoreName();
826         
827         if(!file_exists($file)){
828             return false;
829         }
830         
831         $data = file_get_contents($file);
832         
833         $base64 = 'data:' . $this->mimetype . ';base64,' . base64_encode($data);
834         
835         return $base64;
836     }
837     
838     function getPdfPages($file)
839     {
840         require_once 'System.php';
841         
842         $page = 0;
843
844         $pdfinfo = System::which('pdfinfo');
845
846         if (!file_exists($file) || empty($pdfinfo)) {
847             return $page;
848         }
849         
850         $cmd = "{$pdfinfo} {$file}";
851
852         $ret = `$cmd`;
853
854         $info = explode("\n", $ret);
855
856         foreach ($info as $i){
857
858             if(!preg_match('/^Pages:[\s]*([0-9]+)/', $i, $matches)){
859                 continue;
860             }
861             
862             $page = (empty($matches[1])) ? 0 : $matches[1];
863         }
864         
865         return $page;
866     }
867     
868  }