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