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