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