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