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