define some variables to reduce warnings
[Pman.Cms] / DataObjects / Cms_page.php
1 <?php
2 /**
3  * Table Definition for cms_page
4  */
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
6
7 class Pman_Cms_DataObjects_Cms_page extends DB_DataObject 
8 {
9     ###START_AUTOCODE
10     /* the code below is auto generated do not remove the above tag */
11
12     public $__table = 'cms_page';                         // table name
13     public $id;                              // int(11)  not_null primary_key auto_increment
14     public $title;                           // string(200)  multiple_key
15     public $published;                       // datetime(19)  binary
16     public $body;                            // blob(-1)  blob
17     public $extra_css;
18     public $comments_no;                     // int(11)  
19     public $trackbacks_no;                   // int(11)  
20     public $extended;                        // blob(-1)  blob
21     public $has_extended;                    // int(1)  
22     public $author_id;                       // int(11)  
23     public $category_id;                     // int(11)  
24     public $updated;                         // datetime(19)  not_null binary
25     public $created;                         // datetime(19)  not_null binary
26     public $to_replace_id;                   // int(11)  
27     public $page_link;                       // string(128)  not_null
28     public $parent_id;                       // int(11)  
29     public $keywords;                       // int(11)  
30     public $descriptions;                       // int(11)  
31     public $language;                       // int(11)  
32     public $menu_page_id;                       // int(11)  
33
34     public $in_rss;                          // int(1)  not_null
35     public $is_draft;                        // int(1)  
36     public $is_attachment;                        // int(1)  
37     public $is_element;                        // int(1)  
38     public $is_menuitem;
39
40
41     public $template_id;                       // int(11)  
42     public $element_id;                       // int(11)  
43     public $page_type_id;
44     public $translation_of_id;              //int(11)
45     public $is_system_page;                  //int(2)
46     public $is_static;                      //int(2)
47     public $seq_id;
48
49     // used on templates?
50     public $author_id_name;
51     public $comments;
52     
53     /* the code above is auto generated do not remove the tag below */
54     ###END_AUTOCODE
55     
56     function setFromRoo($ar)
57     {
58         // replace the links in contents
59         $ret = parent::setFrom($ar);
60         $ff = HTML_FlexyFramework::get();
61         if (empty($this->author_id)) {
62             $this->author_id = $ff->page->authUser->id;
63         }
64         
65         return $ret;
66         
67     }
68     function applyFilters($q, $au, $roo)
69     { 
70         if(!empty($q['_dump_pages'])){
71             $this->dump_pages($q, $au, $roo);
72         }
73         
74         if(!empty($q['_stylesheets'])){
75             $this->stylesheets($roo);
76         }
77         
78         if(!empty($q['_list_elements'])){
79             $this->applyFilterTemplateElements($q, $au, $roo);
80         }
81         
82         if (!empty($q['_preview'])) {
83             $roo->sessionState(0);
84             if (!$this->get($q['_preview'])) {
85                 $roo->jerr("invalid page");
86             }
87             return $this->preview($roo);
88         }
89         
90         $tn = $this->tableName();
91
92         if (!empty($q['_update_old'])) {
93             $t = clone($this);
94             foreach($t->fetchAll() as $t) {
95                 $t->convertOld();
96             }
97             $roo->jok("done");
98             
99         }
100         // default is to hide deleted entries... (we show deleted and not-deleted if _show_Deleted is set.)
101         // not filtering if we are doing an update...
102         if (empty($q['_show_deleted']) && empty($q['_is_update_request'])) {
103             $this->is_deleted =  0 ;
104         }
105         
106         if (isset($q['search'])) {
107             if(!empty($q['search']['name'])){
108                 $s = $this->escape($q['search']['name']);
109                 $this->whereAdd("{$tn}.page_link like '%$s%' OR {$tn}.title like '%$s%' ");
110             }
111             
112 //            if(!empty($q['search']['category'])){
113 //                $category_id = (int)$q['search']['category'];
114 //                $this->whereAdd("{$tn}.category_type_id = {$category_id}");
115 //            }
116             
117             if (!empty($q['search']['page_link_no_empty'])) {
118                 $this->whereAdd("{$tn}.page_link != ''");
119             }
120             
121         }
122         
123         $this->_extra_cols  = array('language_name');
124         $this->selectAdd("i18n_translate('l' , {$tn}.language, 'en') as language_name");
125         
126         if(!empty($q['translation_of_id'])){
127             $this->whereAdd("{$tn}.translation_of_id > 0");
128         }
129         
130         
131          
132         //do the select option if page == element
133         if(!empty($q['_page_type_id'])){
134             
135             $this->build_tree_sequence($q['_page_type_id']);
136             
137             //$eid = DB_DataObject::factory('core_enum')->lookup('cms_page_type', 'element');
138 //            $pid = DB_DataObject::factory('core_enum')->lookup('cms_page_type', 'page');
139 //            $mid = DB_DataObject::factory('core_enum')->lookup('cms_page_type', 'menu');
140             
141             $this->page_type_id = $q['_page_type_id'];
142             
143             // show all pages, not just top level?
144             // technically elements with missing parents might need something like this?
145             //if(in_array($q['_page_type_id'], array($pid, $mid))){
146             //    $this->parent_id = 0;
147             //}
148         }
149         
150         if(!empty($q['_category_id'])){
151             $cms_page_category = DB_DataObject::factory('cms_page_category');
152             $cms_page_category->setFrom(array(
153                 'category_id' => $q['_category_id']
154             ));
155             
156             $page_ids = $cms_page_category->fetchAll('page_id');
157             
158             $this->whereAddIn('cms_page.id', $page_ids, 'int');
159         }
160         
161         if(!empty($q['_with_primary_image'])){
162             $this->selectAdd("
163                 (
164                     SELECT
165                             id
166                     FROM
167                             Images
168                     WHERE
169                             Images.ontable = 'cms_page'
170                         AND
171                             Images.onid = cms_page.id
172                     ORDER BY 
173                             Images.displayorder ASC
174                     LIMIT 1
175                 ) AS primary_image_id
176             ");
177         }
178         
179         if(!empty($q['_page_type'])){
180             $core_enum = DB_DataObject::factory('core_enum');
181             $core_enum->setFrom(array(
182                 'etype' => 'cms_page_type'
183             ));
184             $core_enum->whereAddIn('name', array_unique(array_filter(explode(',', $q['_page_type']))), 'string');
185             
186             $this->whereAddIn('cms_page.page_type_id', $core_enum->fetchAll('id'), 'int');
187         }
188         
189         if(!empty($q['_with_fullpath'])){
190             $this->selectAdd("
191                 (SELECT cms_page_fullpath(cms_page.id, '/')) AS fullpath,
192                 (SELECT cms_page_fullpath(cms_page.id, ' - ')) AS display_fullpath
193             ");
194         }
195         
196         if(!empty($q['_with_translation_type'])){
197             $this->selectAdd("
198                 (
199                     SELECT
200                             GROUP_CONCAT(cp.language SEPARATOR ',')
201                     FROM
202                             cms_page AS cp
203                     WHERE
204                             cp.translation_of_id = cms_page.id
205                 ) AS translation_type
206             ");
207         }
208         
209         $pid = DB_DataObject::factory('core_enum')->lookup('cms_page_type', 'page');
210
211         if(!empty($q['_page_type_id']) && $q['_page_type_id'] == $pid) {
212             
213             $this->selectAdd("
214                 (
215                     SELECT
216                             COUNT(cp.id)
217                     FROM
218                             cms_page AS cp
219                     WHERE
220                             cp.is_element = 1
221                         AND
222                             cp.parent_id = cms_page.id
223                         AND
224                             element_id IN (
225                                 SELECT  
226                                         cms_template_element.id
227                                 FROM
228                                         cms_template_element
229                                 WHERE
230                                         cms_template_element.template_id = cms_page.template_id
231                             )
232                 ) AS has_child,
233                 
234                 (SELECT core_enum_id_by_name('cms_page_type', 'element')) AS element_page_type_id,
235                 
236                 (
237                     SELECT
238                             COUNT(cms_template_element.id)
239                     FROM
240                             cms_template_element
241                     WHERE
242                             cms_template_element.template_id = cms_page.template_id
243                 ) AS has_child_element_type
244                 
245                 
246             ");
247             
248         }
249         
250     }
251     function author()
252     {
253         $p = DB_DataObject::Factory('core_person');
254         $p->get($this->author_id);
255         return $p;
256    
257     }
258     function company()
259     {
260         $au = $this->author();
261         return $au->company();
262    
263     }
264     var $company = false;
265     function loadCompany()
266     {
267         $this->company = $this->company();
268         
269     }
270     var $companyPage = false;
271     /**
272      *
273      * assigns companypage
274      * - this is very project specific... (it's used on RIS)
275      * - we should think of a better way to handle this
276      * 
277      */
278     
279     
280     function loadCompanyPage($lang = 'en')
281     {
282         $pg = $this;
283         if ($this->parent_id && !empty($this->language) &&  $this->language !='en') {
284             $pg = DB_DataObject::factory("cms_page");
285             $pg->get($this->parent_id);
286             
287         }
288         
289         $company = $pg->company();
290         $companyPar = DB_DataObject::factory("cms_page");
291         $companyPar->get('page_link', 'companies');
292         
293         $companyEntry = DB_DataObject::factory("cms_page");
294         $companyEntry->parent_id = $companyPar->pid();
295         
296         if ($companyEntry->get('page_link', $company->name)) {
297             $this->companyPage = $companyEntry;
298             
299             
300             $others = DB_DataObject::factory("cms_page");
301             $others->parent_id = $companyEntry->id;
302             $others->language = $lang;
303             if ($others->find(true)) {
304                 $this->companyPage = $others;
305             }
306             return true;
307             
308         }
309         return false;
310     }
311     
312     
313     function published($format)
314     {
315         return date($format,strtotime($this->published));
316     }
317     // depricated..
318     function link($field, $set_args = array()) { return $this->URL(); }
319     
320     function URL() 
321     {
322         
323         
324         $ff = HTML_FlexyFramework::get();
325         
326         if ($this->is_attachment) {
327             $f = $this->firstImage('%');
328             return $f->URL(-1);
329         }
330         
331         if(empty($this->page_link) && !empty($this->menu_page_id)){
332             $link = DB_DataObject::factory('cms_page');
333             if($link->get($this->menu_page_id)){
334                 return $link->URL();
335             }
336         }
337         
338         if(!empty($this->target_url)){
339             return ($this->target_url[0] == '/') ? ($ff->page->baseURL . $this->target_url) : ($ff->page->baseURL . '/' . $this->target_url);
340         }
341         
342         $x = explode('/',$this->page_link);
343         if (!empty($ff->Pman_Cms['view_name'])) { 
344     
345             $d = array_shift($x);
346             
347         // check domains match!
348             
349             if(empty($d)){
350                 return $ff->page->baseURL;
351             }
352         }
353         
354         return $ff->page->baseURL . '/' . implode('/', $x);
355     }
356     
357     function bodyToDisplayHtml()
358     {   
359         return ($this->body) ? $this->hashLinksToHtml($this->body) : '';
360     }
361     
362     function extendedToDisplayHtml()
363     {
364         return ($this->extended) ? $this->hashLinksToHtml($this->extended) : '';
365     }
366     
367     function pageLinkToClass() // conver the page_link into a string that can be used as a css class
368     {
369         return preg_replace('/[^a-z0-9]+/i','-', $this->page_link);
370         
371     }
372     
373     function hashLinksToHtml($str)
374     {
375         // for reference on children..
376         $images = DB_DataObject::factory('Images');
377         $ff = HTML_FlexyFramework::get();
378         
379         $all_images = $images->gather($this);
380         $imap = array();
381         foreach($all_images as $i) {
382             $imap[$i->id] = $i;
383             $imap[$i->title] = $i;
384             
385         }
386         
387         //print_r($imap);
388         libxml_use_internal_errors (true);
389         $doc = new DOMDocument('1.0', 'utf-8');;
390         
391         if (version_compare(PHP_VERSION, '5.3.6') >= 0) {
392         
393             $doc->loadHTML('<?xml encoding="UTF-8"><div id="pman-cms-page-wrapper">' . $str.'</div>');
394         } else {
395             $doc->loadHTML( trim($str));
396         }
397         libxml_use_internal_errors (false);
398         $xpath = new DOMXpath($doc);
399         foreach ($xpath->query('//a[@href]') as $a) {
400             $href = $a->getAttribute('href');
401             //var_dump($href);
402             $matches = array();
403             // named attachment.
404             if (preg_match("/#attachment-(.*)$/", $href, $matches)) {
405                 //var_Dump($matches[1]);
406                  if (isset($imap[$matches[1]])) {
407                      $a->setAttribute('href', $imap[$matches[1]]->URL(-1,'/Images'));
408                  }
409                  continue;
410             }
411             // first attachment
412             if (preg_match("/#attachment$/", $href)) {
413                 if($all_images){
414                     $a->setAttribute('href', $all_images[0]->URL(-1,'/Images'));
415                 }
416                 continue;
417             }
418             if (preg_match("/#page-(.*)$/", $href)) {
419                 
420                 // find the page.. then ask the page provider to delivery the page.
421                 $pg = DB_DataObject::factory($this->tableName());
422                 $pg->is_element = 0;
423                 $lk = preg_replace("/^#page-/", '',  $href);
424                 if (!$pg->get('page_link', $lk)) {
425                     $a->setAttribute('href', "#page-not-found-". $lk);
426                     continue;
427                 }
428                 if (method_exists($ff->page,'pageToURL')) {
429                     $a->setAttribute('href', $ff->page->pageToURL($pg));
430                     continue;
431                 }
432                 // finally use the old standard way of doing it..
433                 $a->setAttribute('href', preg_replace('/#page-/', "{$ff->page->baseURL}/", $href));
434                 continue;
435             }
436         }
437          
438         foreach ($xpath->query('//img[@src]') as $a) {
439             $src = $a->getAttribute('src');
440             $matches = array();
441             //var_Dump($src);
442             if (!preg_match("/#attachment-(.*)$/", $src, $matches)) {
443                 
444                 $matches = array();
445                 if (!preg_match("/#image-(.*)$/", $src, $matches)) {
446                     continue;
447                 }
448             } 
449             
450             // valid attachment. (we do not support globalized attachments yet...)
451             if (!isset($imap[$matches[1]])) {
452                 continue;
453             }
454             $width = $a->hasAttribute('width') ? $a->getAttribute('width') : false;
455             $height= $a->hasAttribute('height') ? $a->getAttribute('height') : false;
456             $width = $width == false || strpos($width,'%') != -1 ? false : (int) $width;
457             $height = $height== false || strpos($height,'%') != -1 ? false : (int) $height;
458             
459             // convert into scaled...
460             switch(true) {
461                 case ($width === false && $height == false):
462                     $a->setAttribute('src', $imap[$matches[1]]->URL(-1,'/Images'));
463                     continue 2;
464                 
465                 case ($width === false ||  $height === false):
466                     // should result in Wx0 or 0xH ????
467                     $width = $width ? $width : '';
468                     $height = $height ? $height : '';
469                     // conteinue through..
470                     
471                 case ($width !== false && $height !== false):
472                     // make sure it will exist..
473                     
474                     $fc = $imap[$matches[1]]->toFileConvert();
475                     $res = $fc->convert($fc->mimetype, $width, $height);
476                     //var_dump(array($width,  $height,  $res));
477                     
478                     
479                     $a->setAttribute('src', $imap[$matches[1]]->URL("{$width}x{$height}",'/Images/Thumb'));
480                     continue 2;
481                 
482             }
483             
484             
485         }
486         
487         if (version_compare(PHP_VERSION, '5.3.6') >= 0) {
488             $wrap = $doc->getElementById('pman-cms-page-wrapper');
489
490             $html = '';
491             for ($i = 0; $i < $wrap->childNodes->length; $i++) {
492                 /** @var $domElement \DOMElement */
493                 
494                 $html .= $doc->saveHTML($wrap->childNodes->item($i));
495             }
496         } else {
497             $html = preg_replace(
498             '/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''),
499                     $doc->saveHTML()));
500             $html = preg_replace('/<p>\s*<\/p>/i', "<p></p>", $html);
501             $html = preg_replace('/<\/p>\s*<p>/i', "</p><p>", $html);
502             
503             $html = preg_replace('/^\s*<p>\s*<\/p>+/i', "", $html);
504             $html = preg_replace('/^<p><p/i', "<p", trim($html));
505             $html = preg_replace('/^<p><p/i', "<p", trim($html));
506             
507             $html = preg_replace('/<p>\s*<\/p>\s*+$/i', "", $html);
508             $html = preg_replace('/<\/p><\/p>$/i', "</p>", trim($html));
509         }
510         
511         //$bodys = $doc->getElementsByTagName('BODY');
512         
513         
514         return $html;
515     }
516     
517     
518     function logReferrer($referer) 
519     {
520         //DB_DataObject::debugLevel(1);
521         if (!strlen(trim($referer))) {
522             return;
523         }
524         $url = parse_url($referer);
525         if ( empty($url['host']) || 
526                 ($url['host'] == $_SERVER['HTTP_HOST']) || 
527                 preg_match('#^[0-9\.]+$#',$url['host'])
528                 
529         ) {
530             return;
531         }
532         
533          
534         
535         // locate previous record?
536         $ref = DB_DataObject::factory('CmsRefer');
537         $ref->blog_id = $this->id;
538         $ref->setFrom($url);
539         if (!$ref->clean()) {
540             return;
541         }
542         if ($ref->find(true)) {
543             $ref->seen++;
544             $ref->update();
545         } else {
546             $ref->day = date('Y-m-d');
547             $ref->seen = 1;
548             $ref->insert();
549         }
550          
551     } 
552     function referrers($showgoogle=false) 
553     {
554         //DB_DataObject::debugLevel(1);
555         
556         
557         $r =  DB_DataObject::factory('CmsRefer');
558         $r->blog_id = $this->id;
559         $r->orderBy('checked asc');
560         // dont validate google
561         
562         $r->whereAdd("host like '%planet%'");
563         $r->whereAdd('checked_success < 1');
564         // check old?
565         $r->limit(1);
566         if ($r->find(true)) {
567             
568             $r->checkValid();
569         }
570         
571         $r =  DB_DataObject::factory('CmsRefer');
572         $r->blog_id = $this->id;
573         $r->whereAdd('checked_success > 0');;
574         $r->selectAdd();
575         $r->selectAdd('distinct(title), day,sum(seen) as seen,
576             scheme,host,port,path,id,checked_success,query');
577         $r->groupBy('title');
578         $r->orderBy('seen desc, host DESC, title ASC');
579         //$r->orderBy('blog_id desc');
580         if (!$showgoogle) {
581             $r->whereAdd("host != 'google.com'");
582         }
583         $r->limit(20);
584         $r->find();
585         
586         return   $r->fetchAll();
587          
588     }
589     function cleanTitle()
590     {
591         return preg_replace('/[^a-z0-9_]+/i','',preg_replace('/\s+/','_',$this->title));
592     }
593     
594     function postListFilter($data, $authUser, $q) 
595     {
596 //        if (!empty($q['_treeview'])) {
597 //        
598 //            $pid = DB_DataObject::factory('core_enum')->lookup('cms_page_type', 'page');
599 //            $mid = DB_DataObject::factory('core_enum')->lookup('cms_page_type', 'menu');
600 //            
601 //            $c = DB_DAtaObject::Factory('core_enum');
602 //            if (empty($q['_page_type_id']) || !in_array($q['_page_type_id'] , array($pid,$mid))) {
603 //                
604 //                return $data;
605 //            }
606 //                    
607 //            $data = $this->buildTree($data);
608 //            
609 //        }
610         
611         return $data;
612     }
613     
614     function buildTree($data, $depth= 0) {
615         // data contains a list of the top level eleemnts
616         // we need to add all children (and depth flag?)
617         
618         // build a static query with all the data...
619         static $all = false;
620         static $menu_id = false;
621         if (!$menu_id) {
622              $menu_id = DB_DataObject::factory('core_enum')->lookup('cms_page_type', 'menu');
623         }
624         
625         
626         if (!$all) {
627             $cb = DB_DataObject::factory('cms_page');
628             $cb->autoJoin(array('exclude' => array('extended', 'body')));
629             $tn = $this->tableName();
630             
631             // this query is very outdated - should be using page types..
632             
633             $cb->whereAdd("
634                 ( 
635                     {$tn}.in_rss = 0
636                 OR
637                     (
638                         {$tn}.in_rss = 1
639                     AND
640                         LENGTH({$tn}.page_link) > 0
641                     )
642                 )
643                 AND
644                     cms_page.parent_id != 0
645                 AND
646                     cms_page.translation_of_id = 0
647             " );
648             $cb->is_menuitem = $this->is_menuitem;
649             if ($cb->is_menuitem) {
650                 $cb->orderBy('cms_page.seq_id ASC');
651             } else {
652                 $cb->orderBy('cms_page.is_element DESC, cms_page.page_link ASC');
653             }
654             $cb->is_deleted = (empty($_REQUEST['_show_deleted'])) ? 0 : 1;
655 //            $disabled = DB_DataObject::factory('core_enum')->lookup('cms_page_type', 'disabled');
656             
657             $cb->find();
658             while ($cb->fetch())
659             {
660                 if (!isset($all[$cb->parent_id])) {
661                     $all[$cb->parent_id] = array();
662                 }
663 //                if($cb->page_type_id == $disabled){// does not show the disabled item.... #2012
664 //                    continue;
665 //                }
666                 $all[$cb->parent_id][]  = $cb->toArray();
667             }
668             
669             
670         }
671         
672         
673         $ret = array();
674         foreach($data as $d) {
675             $d['depth'] = $depth;
676             $ret[] = $d;
677             if (empty($all[$d['id']])) { 
678                 continue;
679             }
680             // elements first, then order by page link
681             //$cb->orderBy('is_element DESC, page_link ASC');
682             //$add = $cb->fetchAll(false,false,'toArray');
683             
684             $add = $this->buildTree($all[$d['id']], $depth +1);
685             foreach($add as $r) {
686                 $ret[] = $r;
687             }
688             
689         }
690         
691         return $ret;
692         
693         
694     }
695     
696     function firstImage($filter='image/%')
697     {
698         $i = DB_DataObject::factory('Images');
699 //        DB_DataObject::debugLevel(1);
700         $i->orderBy('displayorder ASC, id ASC');
701         $im = $i->gather($this, $filter);
702         if (empty($im)) {
703             return false;
704         }
705         return $im[0];
706     }
707     
708     function firstImageTag($size =-1, $base="/Images/Thumb", $filter='image/%')
709     {
710         $fm = $this->firstImage($filter);
711          if (empty($fm)) {
712             return '';
713         }
714         return $fm->toHTML($size, $base);
715     }
716     function template()
717     {
718         $d = DB_DataObject::Factory('cms_template');
719         $d->get($this->template_id);
720         return $d;
721     }
722     function toEventString()
723     {
724         return $this->title;
725     }
726     
727     function toRooSingleArray($req)
728     {
729         $ret = $this->toArray();
730         if ( !empty($this->template_id_template )) {
731             $ret['template_id_template_clean'] = preg_replace(
732                     '#\.html$#i', '', $this->template_id_template
733             );
734         }
735         
736         $ret = $this->toRooSingleArrayInterests($ret, $req);
737         $ret = $this->toRooSingleArrayCategory($ret, $req);
738         $ret = $this->toRooSingleArrayPageClass($ret, $req);
739         
740         return $ret;
741         
742     }
743     
744     function toRooSingleArrayCategory($ret, $req)
745     {
746         $li = array();
747         $cms_page_category = DB_DataObject::factory('cms_page_category');
748         $cms_page_category->autoJoin();
749         $cms_page_category->page_id = $this->id;
750         
751         $cms_page_category->selectAdd("
752             cms_page_fullpath(cms_page_category.category_id, ' - ') AS category_id_fullpath
753         ");
754         
755         $categories = $cms_page_category->fetchAll('category_id', 'category_id_fullpath');
756
757         foreach($categories as $k => $v) {
758             $li[] = array(
759                 'id' => $k,
760                 'display_fullpath' => $v
761             );
762         }
763
764         $ret["categories"] = json_encode($li);
765         
766         return $ret;
767     }
768     
769     function toRooSingleArrayPageClass($ret, $req)
770     {
771         if(empty($ret['page_cls'])){
772             return $ret;
773         }
774         
775         $li = array();
776         $core_enum = DB_DataObject::factory('core_enum');
777         $core_enum->setFrom(array(
778             'etype' => 'cms_page_class'
779         ));
780         $core_enum->whereAddIn('name', explode(',', $ret['page_cls']), 'string');
781
782         foreach($core_enum->fetchAll('name', 'display_name') as $k => $v) {
783             $li[] = array(
784                 'name' => $k,
785                 'display_name' => $v
786             );
787         }
788
789         $ret["page_classes"] = json_encode($li);
790         
791         return $ret;
792     }
793     
794     
795     function parent()
796     {
797         $c = DB_DataObject::Factory($this->tableName());
798         $c->autoJoin();
799         $c->get($this->parent_id);
800         return $c;
801     }
802     
803     
804     function inLanguage($lang)
805     {
806         if ($lang == $this->language) {
807             return $this;
808         }
809         $x = DB_DataObject::factory("cms_page");
810         $x->autoJoin();
811         $x->is_element = $this->is_element;
812         $x->is_draft = $this->is_draft;
813         $x->is_deleted = 0;
814         $x->language =  $lang;
815         if ($x->get('translation_of_id', $this->id)) {
816             return $x;
817         }
818         return $this;
819          
820     }
821     
822     function children($cfg)
823     {
824         // DB_DataObject::debugLevel(1);
825         $cfg['type']     = isset($cfg['type'] ) ? $cfg['type'] : '';
826         $cfg['language'] = isset($cfg['language'] ) ? $cfg['language'] : $this->language;
827         
828         $tn = $this->tableName();
829         $nc = false; // named column.
830         
831         $p = DB_DataObject::factory('cms_page');
832         $p->autoJoin();
833         if (!isset($this->id)) {
834             return array();
835         }
836         
837         $p->parent_id =  !empty($this->translation_of_id) ? $this->translation_of_id : $this->id;
838         
839         $p->is_deleted = 0 ;
840         $p->is_draft = 0;
841         
842         $p->language = $cfg['language'];
843         
844 //        print_r($cfg);
845         switch($cfg['type']) {//FIXME in the new cms_page code this is not work?
846             
847             case 'named_blocks':
848                 // for childnre..
849                 // if language != english..
850                 //DB_DataObject::debugLevel(1);
851                 $p->page_type_id = DB_DataObject::factory('core_enum')->lookup("cms_page_type", 'element');
852                 $nc = 'element_id_name';
853                 $p->whereAdd("{$tn}.element_id != 0");
854                 $p->orderBy("{$tn}.page_link ASC");
855                 $p->language = 'en'; // default to the english ..
856                 // we will translate later..
857                 break;
858             
859             case 'pages':
860                 //DB_DataObject::debugLevel(1);
861                 $p->page_type_id = DB_DataObject::factory('core_enum')->lookup("cms_page_type", 'page');
862                 $p->is_element = 0;
863                 $p->orderBy(" {$tn}.seq_id, {$tn}.page_link ASC");
864
865                 break;
866             
867              case 'elements':
868                 $p->page_type_id = DB_DataObject::factory('core_enum')->lookup("cms_page_type", 'element');
869                 
870                 $p->orderBy(" {$tn}.seq_id, {$tn}.page_link ASC");
871
872                 break;
873             
874             
875             
876             case 'blog':
877                 //$p->in_rss = 1;
878                 $p->page_type_name('blog');
879                 $c = DB_DataObject::Factory('cms_category_type');
880                 $c->get('name', $cfg['category']);
881                 $p->category_type_id = $c->id;
882                 $p->orderBy("{$tn}.published DESC");
883                 break;
884                 
885             
886             case 'menu':
887                 $p->page_type_id = DB_DataObject::factory('core_enum')->lookup("cms_page_type", 'menu');
888 //                $p->is_menu = 1;
889                 //DB_DataObject::debugLevel(1);
890                 //$p->is_menuitem = 1; //?? needed???
891                 $p->orderBy("
892                     CASE WHEN {$tn}.translation_of_id > 0
893                         THEN
894                             join_translation_of_id_id.seq_id 
895                         ELSE
896                             {$tn}.seq_id  
897                         END ASC
898                      ");
899                
900                // $p->orderBy("{$tn}.seq_id ASC");
901                 break;
902             
903             default:
904                 die("bad config for cms_page call - needs type");
905             
906         }
907         
908         
909         if (!empty($cfg['limit'])) { //ofsset..
910             $p->limit((int)$cfg['limit']);
911         }
912         
913         if (!$nc) {
914             if($cfg['type'] == 'menu'){// if not found the language translate then get the en
915 //            print_r($p);
916 //                $pp = clone($p);
917                 if($p->count() > 0){
918                     return $p->fetchAll();
919                 }
920                 $p->language = 'en';
921                 return $p->fetchAll();
922             }
923             return $p->fetchAll();
924         }
925         
926         $p->find();
927         $ret = array();
928         
929         while($p->fetch()) {
930             
931             // if we have multiple children... with the same block name...
932             if (isset($ret[$p->{$nc}])) {
933                 if (!is_array($ret[$p->{$nc}])) {
934                     $ret[$p->{$nc}]  = array($ret[$p->{$nc}]);
935                 }
936             
937                 $ret[$p->{$nc}][] = clone($p);
938                 
939             } else {
940                 $ret[$p->{$nc}] = clone($p);
941             }
942         }
943         if (empty($ret)) {
944             return $ret;
945         }
946         
947         if ($cfg['language'] != 'en' && $cfg['type'] == 'named_blocks') {
948             // our search results are currently english.
949             // find the 'id's of the
950             $ids = array();
951             // DB_DataObject::debugLevel(1);
952             foreach($ret as $k=>$v) {
953                 $ids[] = is_object($v) ? $v->id : $v[0]->id;
954             }
955             
956             $pg = DB_DAtaObject::Factory('cms_page');
957             $pg->autoJoin();
958             $pg->whereAddIn("{$tn}.translation_of_id", $ids, 'int');
959             $pg->language = $cfg['language'];
960             $pg->is_deleted = 0;
961             $pg->find();
962             
963             $tr = array();
964             while ($pg->fetch()) {
965                 $tr[$pg->translation_of_id] = clone($pg);
966             }
967             foreach($ret as $k=>$v) {
968                 $id = is_object($v) ? $v->id : $v[0]->id;
969                 if (isset($tr[$id])) {
970                     $ret[$k] = $tr[$id];
971                 }    
972             }
973             
974             
975         } 
976         
977         return $ret;
978         
979     }
980     
981     function youtube() // asTech project - depricated - do not use..
982     {
983         return $this->videoPageLink('page_link');
984     }
985     
986     function videoPageLink($prop = 'title') //prettybooked 
987     {
988         $ar = parse_url($this->{$prop});
989         if(empty($ar['host'])){
990             return $this->{$prop};
991         }
992         switch(true) {
993             
994             case preg_match('/youtube/',$ar['host']):
995                 $t= array_pop(explode('/', $ar['query']));
996                 $t = array_pop(explode('v=', $t));
997                 return 'http://www.youtube.com/embed/' . $t;
998             case preg_match('/vimeo/',$ar['host']):
999                 $t= array_pop(explode('/', $ar['path']));
1000                 return "http://player.vimeo.com/video/". $t;
1001             default:// detault does not work?
1002                 return $this->{$prop};
1003         }
1004     }
1005     
1006     // this will be depricated
1007     function beforeInsert($request,$roo)
1008     {
1009         if(!empty($request['_copy_of'])){
1010             $this->copy($request['_copy_of'], $roo);
1011         }
1012         
1013         if(isset($request['_stylesheets'])){
1014             $this->updateStylesheets($request['_stylesheets'], $roo);
1015         }
1016         
1017         if(isset($request['page_type_id'])){
1018             $this->assignOldConditions($request);
1019         }
1020         if(empty($request['language'])){
1021             $this->language = 'en';
1022         }
1023         if (!empty($request['translation_of_id'])) {
1024             $p = DB_DataObject::Factory('cms_page');
1025             $p->get($request['translation_of_id']);
1026             $this->page_type_id = $p->page_type_id;
1027             
1028             $dupe = DB_DataObject::Factory('cms_page');
1029             $dupe->translation_of_id = $this->translation_of_id;
1030             $dupe->language = $this->language;
1031             if ($dupe->count()) {
1032                 $roo->jerr("a translated version already exists");
1033             }
1034             
1035         }
1036         
1037         
1038         $this->validateParent($roo);
1039         
1040         
1041         //check the page link is duplicate, then return error
1042         if(!empty($request['page_link'])){
1043             
1044             $eid = DB_DataObject::factory('core_enum')->lookup('cms_page_type', 'element');
1045             
1046             if($this->page_type_id != $eid){
1047                 
1048                 $x = DB_DataObject::factory('cms_page');
1049                 $x->page_type_id = $this->page_type_id;
1050
1051                 if(!empty($request['page_link']) && $x->get('page_link', $request['page_link'])){
1052                     $roo->jerr('Sorry, this page link exists already.');
1053                 }
1054             }
1055             
1056         }
1057         
1058     }
1059     
1060     function onInsert($q,$roo)
1061     {
1062         $this->retrieveAutoSave();
1063         
1064         if(isset($q['interest']) && strpos($roo->appModules, 'Crm') !== false){
1065             $this->updateInterests($q['interest'], $roo);
1066         }
1067         
1068         if(isset($q['category'])){
1069             $this->updatecategory(empty($q['category']) ? array() : array_unique(array_filter(explode(',', $q['category']))), $roo);
1070         }
1071         
1072     }
1073     
1074     function onUpdate($old, $q,$roo)
1075     {
1076         if(isset($q['interest']) && strpos($roo->appModules, 'Crm') !== false){
1077             $this->updateInterests($q['interest'], $roo);
1078         }
1079         
1080         if(isset($q['category'])){
1081             $this->updatecategory(empty($q['category']) ? array() : array_unique(array_filter(explode(',', $q['category']))), $roo);
1082         }
1083     }
1084     
1085     function retrieveAutoSave()
1086     {
1087         $events = DB_DataObject::factory('Events');
1088         $events->on_table = $this->tableName();
1089         $events->on_id = 0;
1090         $events->action = 'AUTOSAVE';
1091         
1092         foreach ($events->fetchAll() as $e){
1093             $ee = clone($e);
1094             $e->on_id = $this->id;
1095             $e->update($ee);
1096         }
1097     }
1098     
1099     function validateParent($roo)
1100     {
1101         
1102         if ($this->id && $this->parent_id == $this->id) {
1103             $roo->jerr("parent must not be same as page");
1104         }
1105         if (!empty($this->parent_id)) {
1106             $p = DB_DataObject::factory('cms_page');
1107             $p->get($this->parent_id);
1108             switch($this->page_type()->name) {
1109                 case 'page':
1110                 case 'element':
1111                     if ($p->page_type()->name != 'page') {
1112                         $roo->jerr("parent must be of type page");
1113                     }
1114                     break;
1115                 
1116                 case 'menu':
1117                     if ($p->page_type()->name != 'menu') {
1118                         $roo->jerr("parent must be of type menu");
1119                     }
1120                     break;
1121                 
1122                 case 'blog':
1123                 case 'category':
1124                     if ($p->page_type()->name != 'category') {
1125                         $roo->jerr("parent must be of type menu");
1126                     }
1127                     break;
1128                 
1129                 default: // unknow type?!?!
1130                     break;
1131             }
1132         }
1133     }
1134     
1135     
1136     function beforeUpdate($old, $request,$roo)
1137     {
1138         if(!empty($request['_move'])){
1139             $this->updatePageSeq($request['_move'], $roo);
1140         }
1141         
1142         if(isset($request['page_type_id'])){
1143             $this->assignOldConditions($request);
1144         }
1145         
1146         $this->validateParent($roo);
1147         
1148         if(!empty($request['page_link'])){
1149             //checking for the system page, then cannot be edit page link
1150             if($old->is_system_page &&
1151                
1152                
1153                 (
1154                     ($old->page_link != $request['page_link'])
1155                     ||
1156                     ($old->element_id != $request['element_id'])
1157                 )
1158             )
1159                 
1160             {
1161                 $roo->jerr('Sorry, you cannot change the page link, or block for system items.');
1162             }
1163
1164             //check the page link is duplicate, then return error
1165             if(!empty($request['page_link'])){
1166                 
1167                 
1168                 $eid = DB_DataObject::factory('core_enum')->lookup('cms_page_type', 'element');
1169                 
1170                 if($this->page_type_id != $eid){ // element ignore page link checking..
1171                     
1172                     $x = DB_DataObject::factory('cms_page');
1173                     
1174                     $x->page_type_id = $this->page_type_id; // make sure they are of the same type..
1175                     
1176                     if($x->get('page_link', $request['page_link']) && ($old->page_link != $request['page_link'])){
1177                     $roo->jerr('Sorry, this page link is existing on the system.');
1178                 }
1179                     
1180                 }
1181                 
1182                 
1183             }
1184         }
1185         
1186         $page_type = $this->page_type();
1187         
1188         if(
1189                 $page_type->name == 'blog' && 
1190                 $old->is_draft == 1 && 
1191                 $this->is_draft == 0 && 
1192                 (
1193                         empty($this->published) || 
1194                         $this->published == '0000-00-00 00:00:00'
1195                 )
1196         ){
1197             $this->published = date('Y-m-d');
1198         }
1199     }
1200     
1201     function page_type()
1202     {
1203         $c = DB_DataObject::factory('core_enum');
1204         $c->get($this->page_type_id);
1205         return $c;
1206     }
1207     /**
1208      * get or set page type...
1209      */
1210     function page_type_name()
1211     {
1212         $args = func_get_args();
1213         if (!$args) {
1214             return isset($this->page_type_id_name) ? $this->page_type_id_name : $this->page_type()->name;
1215         }
1216         $cid = DB_DataObject::factory('core_enum')->lookup("cms_page_type", $args[0]);
1217         if ($cid) {
1218             $this->page_type_id = $cid;
1219             return $args[0];
1220         }
1221         return false;
1222         
1223     }
1224     
1225     
1226     function assignOldConditions($request)
1227     {
1228         $c = DB_DataObject::factory('core_enum');
1229         $c->get($request['page_type_id']);
1230         switch ($c->name)
1231         {
1232             case 'page' : 
1233                 $this->in_rss = 0;
1234                 $this->is_element = 0;
1235                 $this->is_menuitem = 0;
1236                 break;
1237             case 'element' : 
1238                 $this->in_rss = 0;
1239                 $this->is_element = 1;
1240                 $this->is_menuitem = 0;
1241                 break;
1242             case 'blog' : 
1243                 $this->in_rss = 1;
1244                 $this->is_element = 0;
1245                 $this->is_menuitem = 0;
1246                 break;
1247             case 'menu' :
1248                 $this->in_rss = 0;
1249                 $this->is_element = 0;
1250                 $this->is_menuitem = 1;
1251                 break;
1252             case 'category' : 
1253                 $this->in_rss = 0;
1254                 $this->is_element = 0;
1255                 $this->is_menuitem = 0;
1256                 break;
1257         }
1258     }
1259     
1260     
1261     function convertOld()
1262     {
1263         static $map = false;
1264         if (!$map) {
1265             $c = DB_DataObject::factory('core_enum');
1266             $c->etype = 'cms_page_type';
1267             $c->active = 1;
1268             $map = $c->fetchAll('name', 'id');
1269         }
1270         $old = clone($this);
1271         $opt = $this->page_type_id ;
1272         switch(true) {
1273             case  (!$this->in_rss && ! $this->is_element && ! $this->is_menuitem):
1274                 $this->page_type_id = $map['page'];
1275                 break;
1276             
1277             case  (!$this->in_rss &&  $this->is_element && ! $this->is_menuitem):
1278                 $this->page_type_id = $map['element'];
1279                 break;
1280             
1281             case  (!$this->in_rss &&  !$this->is_element && $this->is_menuitem):
1282                 $this->page_type_id = $map['menu'];
1283                 break;
1284             
1285             case  ($this->in_rss &&  !$this->is_element && !$this->is_menuitem):
1286                 $this->page_type_id = $map['blog'];
1287                 break;
1288             
1289         }
1290         //echo "NEW: {$this->page_type_id }  / old: {$old->page_type_id}\n";
1291         if ($this->page_type_id != $old->page_type_id) {
1292             $this->update($old);
1293         }
1294         
1295         
1296     }
1297     
1298     function initMenu($data = array())
1299     {
1300         echo "Starting Menu ..... \n";
1301         $menu_id = DB_DataObject::factory('core_enum')->lookup('cms_page_type', 'menu');
1302         foreach($data as $parent){
1303             $prt = DB_DataObject::factory($this->tableName());
1304             if($prt->get('page_link', $parent['page_link'])){
1305                 continue;
1306             }
1307             
1308             $prt->title = $parent['title'];
1309             $prt->is_menuitem = 1;
1310             $prt->is_system_page = 1;
1311             $prt->language = 'en';
1312             $prt->created = Date('Y-m-d H:i:s');
1313             $prt->page_type_id = $menu_id;
1314             $prt->insert();
1315             
1316             
1317             foreach($parent['cn'] as $child){
1318                 $c = DB_DataObject::factory($this->tableName());
1319                 
1320                 $page_link = (!empty($child['hide_parent'])) ? $child['page_link'] : ($prt->page_link.'/'.$child['page_link']);
1321                 
1322                 if(!$c->get('page_link', $page_link)){
1323                     $c->title = empty($child['title']) ? '' : $child['title'];
1324                     $c->is_menuitem = 1;
1325 //                    $c->is_system_page = 1;
1326                     $c->created = Date('Y-m-d H:i:s');
1327                     $c->parent_id = $prt->id;
1328                     $c->language = 'en';
1329                     $c->page_type_id = $menu_id;
1330                     $c->seq_id = empty($child['seq_id']) ? 0 : $child['seq_id'];
1331                     $c->target_url = empty($child['target_url']) ? '' : $child['target_url'];
1332                     $c->insert();
1333                 }
1334             }
1335         }
1336     }
1337     
1338     function preview($roo)
1339     {
1340         // $this->autoJoin(); not needed called already in roo.
1341         
1342         if ($this->page_type_id_name == 'element') {
1343             
1344             return $this->parent()->preview($roo);
1345         }
1346         
1347         // set up the template engine to render from the site..
1348         $opts = HTML_FlexyFramework::get()->Pman_Cms;
1349         if (!isset($opts['basePHP'])) {
1350             $roo->jerr(" Pman_Cms[basePHP] is not set ");
1351         }
1352         
1353         
1354         $basePHP = $opts['basePHP'];
1355         
1356         // for blog
1357         if ($this->page_type_id_name == 'blog' && empty($this->page_link)) {
1358             
1359             if(!isset($opts['blog'])){
1360                 $roo->jerr("Pman_Cms['blog'] is not set");
1361             }
1362             
1363             header('Location: ' . $roo->rootURL .'/'.  $opts['blog'] . '/' . $this->id);
1364             exit;
1365             
1366         }
1367         
1368         // for page
1369         $strip = 0;
1370         $pl = $this->page_link;
1371         if (is_array($opts['basePHP'])) {
1372             foreach($opts['basePHP'] as $k=>$v) {
1373                 if ($k == substr($pl,0, strlen($k))) {
1374                     $pl = substr($pl, strlen($k)+1);
1375                     $basePHP = $v;
1376                     $matched = true;
1377                     break;
1378                 }
1379             }
1380             if (!$matched) {
1381                 $roo->jerr(" page link does not match any configured site.");
1382             }
1383         }
1384         
1385         switch($pl) {
1386             case 'Home':
1387             case 'Site':
1388                 $pl = '';
1389                 break;
1390             default:
1391                 $pl = '/' . $pl;
1392                 break; // do nothing.
1393         }
1394         
1395         header('Location: ' . $roo->rootURL .'/'. $basePHP . $pl );
1396         exit;
1397         
1398         /*
1399         require_once 'Pman/Cms/Preview.php';
1400         
1401         $p = new Pman_Cms_Preview();
1402         // set up the basic params..
1403         $p->rootURL = $roo->rootURL;
1404         $p->baseURL = $roo->rootURL . '/'. $opts['basePHP'] ;
1405         $p->loadPage('Site'); // loads any blocks from site.
1406         $p->loadPage('Site/*'); // loads any blocks from site.
1407         $p->loadPage('Home'); // loads any blocks from site.
1408         
1409         $p->page = $p->loadPage($this->page_link);
1410         
1411         
1412         $fo = &PEAR::getStaticProperty('HTML_Template_Flexy', 'options');
1413         
1414         $fo['templateDir'] = $opts['templateDir'];
1415         $fo['forceCompile'] = true;
1416         if (isset($opts['url_rewrite'])) {
1417             $fo['url_rewrite'] = $opts['url_rewrite'];
1418         }
1419         
1420         
1421         $p->output();
1422         exit;
1423         
1424         */
1425         
1426         
1427     }
1428     
1429     function getStoreName()
1430     {
1431         $opts = HTML_FlexyFramework::get()->Pman;
1432         
1433         $dir = "{$opts['storedir']}/cms_page";
1434         
1435         if(!file_exists($dir)){
1436             $oldumask = umask(0);
1437             mkdir($dir, 0775, true);
1438             umask($oldumask);
1439         }
1440         
1441         return implode( '/', array(
1442             $dir, $this->id . '.png'
1443         ));
1444         
1445     }
1446     
1447     function syncTemplatePage($pgdata)
1448     {
1449         
1450         if (empty($pgdata['page_link'])) {
1451             return; // shoud not happen..
1452         }
1453         $link = $pgdata['page_link'];
1454             
1455         $page_id = DB_DataObject::factory('core_enum')->lookup('cms_page_type', 'page');
1456         $cmsPage = DB_DataObject::factory('cms_page');
1457         $cmsPage->setFrom(array(
1458             'page_link'  => $link,
1459             'page_type_id'  => $page_id,
1460             'translation_of_id' => 0,
1461             'is_element' => 0,
1462         ));
1463         
1464         $parent = 0;
1465         if(!$cmsPage->find(true)){
1466             $cmsPage = DB_DataObject::factory('cms_page');
1467         } else {
1468                 // existing parent..
1469             $parent = $cmsPage->parent_id;
1470         }
1471         
1472         // attempt to find the parent..
1473         if (!$parent && strpos($link,'/') !== false) {
1474             $par = explode('/', $link);
1475             array_pop($par);
1476             $pname = implode('/', $par);
1477             $cmsPageP = DB_DataObject::factory('cms_page');
1478             if ($cmsPageP->get('page_link',$pname)) {
1479                 $parent = $cmsPageP->id;
1480             }
1481         }
1482             
1483            
1484
1485 //            echo "$ori_n <<<< $is_static \n";
1486         $run_opts  = HTML_FlexyFramework::get()->page->opts;
1487             
1488         $cmsPage->setFrom(array(
1489             'parent_id' => $parent,
1490             'page_link'  => $link,
1491             
1492             'page_type_id'  => $page_id,
1493             'template_id' => !empty($pgdata['template_object']) ? $pgdata['template_object']->id : 0,
1494             'language' => 'en',
1495             'translation_of_id' => 0,
1496             'is_system_page' => 1,
1497             'is_element' => 0,
1498             'is_static' => 0, // not sure what this is supposed to indicate..
1499             'updated' => $this->sqlValue('NOW()'),
1500             'created' => $this->sqlValue('NOW()'),
1501         ));
1502             //print_r($contentStrings);
1503         
1504         if (!$cmsPage->id) {
1505             $cmsPage->title = $link;
1506         }
1507         
1508         $contentStrings = !empty($pgdata['template_object']) ? $pgdata['template_object']->contentStrings : false;
1509         
1510         if ($contentStrings && 
1511                 (!empty($run_opts['force-content-update']) || !$cmsPage->id)
1512             ) { // only do this for the initila load
1513             foreach( array('title', 'body', 'extended') as $prop) {
1514                 if (isset($contentStrings['{page.'. $prop.'}'])) {
1515                     $cmsPage->{$prop} = $contentStrings['{page.'. $prop.'}'];
1516                 }
1517                 if (isset($contentStrings['{page.'. $prop.':h}'])) {
1518                     $cmsPage->{$prop} = $contentStrings['{page.'. $prop.':h}'];
1519                 }
1520                 if (isset($contentStrings['{page.'. $prop.'ToDisplayHtml():h}'])) {
1521                     $cmsPage->{$prop} = $contentStrings['{page.'. $prop.'ToDisplayHtml():h}'];
1522                 }
1523                 echo "cmsPage->{$prop} = ". $cmsPage->{$prop} ."\n";
1524             }
1525         }   
1526             
1527              
1528             
1529         if(!$cmsPage->id){
1530             $cmsPage->insert();
1531         } else {
1532             $cmsPage->update();
1533         }
1534         return clone($cmsPage);
1535     
1536         
1537     }
1538     
1539     
1540     
1541     function toSitemapAll($xml, $site_base)
1542     {
1543         $this->is_draft = 0;
1544         $x->is_deleted = 0;
1545         $this->page_type_id = DB_DataObject::factory('core_enum')->lookup('cms_page_type', 'page');
1546         
1547         $ar = $this->fetchAll();
1548 //        print_r($ar);
1549         $except = array('Home', 'Site');
1550         foreach($ar as $o) {
1551             $link = explode('/', $o->page_link);
1552             if(in_array($link[0], $except)){
1553                 continue;
1554             }
1555             $url = $site_base."/".str_replace('%2F', '/', rawurlencode($o->page_link));
1556             $tmpXml = $xml->addChild("url");
1557             $tmpXml->addChild("loc", $url);
1558             $tmpXml->addChild("changefreq", "weekly");
1559             $tmpXml->addChild("priority", 1);
1560             $time = $o->updated;
1561             if(!$time || $time == '0000-00-00 00:00:00'){
1562                 $time = '2000-01-01 00:00:00';
1563             }
1564             $tmpXml->addChild("lastmod", date("Y-m-d", strtotime($time)));
1565 //            $a = $xml->addChild("url");
1566 //            $a->addChild("loc", 'http://www.prettybooked.com');
1567 //            $a = $xml->addChild("url");
1568 //            $a->addChild("loc", 'http://www.prettybooked.com2');
1569         }
1570 //        return $xml;
1571     }
1572     
1573     function comments($count = false)
1574     {
1575         $comments = DB_DataObject::factory('cms_comments');
1576         $comments->ontable = 'cms_page';
1577         $comments->entry_id = $this->id;
1578         
1579         if(!empty($count)){
1580             return $comments->count();
1581         }
1582         
1583         $comments->_join .= '
1584             LEFT JOIN
1585                 Person
1586             ON
1587                 Person.email = cms_comments.email
1588         ';
1589         $person = DB_DataObject::Factory('core_person');
1590         
1591         $comments->selectAs($person, 'person_%s');
1592         
1593         $comments->orderBy('posted ASC');
1594         
1595         return $comments->fetchAll();
1596     }
1597     
1598     
1599     function beforeDelete($dependants_array, $roo)
1600     {
1601         $this->beforeDeleteInterests($dependants_array, $roo);
1602     }
1603     
1604     
1605     /**---------- crm related interest - no idea how this snuck in here --*/
1606     
1607     
1608     function beforeDeleteInterests($dependants_array, $roo)
1609     {
1610         // why is this using crm interest???
1611         $ff = HTML_FlexyFramework::get();
1612         if (!in_array('Crm', $ff->enableArray)) {
1613             return;
1614         }
1615         
1616         $interest = DB_DataObject::factory('crm_interest');
1617         $interest->onid = $this->id;
1618         $interest->ontable = $this->tableName();
1619         
1620         foreach($interest->fetchAll() as $i){
1621             $i->delete();
1622         }
1623         
1624     }
1625     
1626     
1627     function updateInterests($interests = array(), $roo = false)
1628     {
1629         $ff = HTML_FlexyFramework::get();
1630         if (!in_array('Crm', $ff->enableArray)) {
1631             return;
1632         }
1633         
1634         
1635         $type = $this->page_type();
1636         
1637         if($type->name != 'blog'){
1638             return;
1639         }
1640         
1641         $exists = $this->interests();
1642         
1643         $interests = array_filter(explode(',', $interests));
1644         
1645         foreach ($interests as $i){
1646             if(array_key_exists($i, $exists)){
1647                 unset($exists[$i]);
1648                 continue;
1649             }
1650             
1651             $ci = DB_DataObject::factory('crm_interest');
1652             $ci->setFrom(array(
1653                 'onid'          => $this->id,
1654                 'ontable'       => $this->tableName(),
1655                 'interest_id'   => $i,
1656                 'created_dt'    => $ci->sqlValue("NOW()")
1657             ));
1658             $ci->insert();
1659         }
1660         
1661         foreach ($exists as $e){
1662             $e->delete();
1663         }
1664         
1665     }
1666     
1667     function updatecategory($category = array(), $roo = false)
1668     {
1669         $exists = $this->categories();
1670         
1671         foreach ($category as $c){
1672             if(array_key_exists($c, $exists)){
1673                 unset($exists[$c]);
1674                 continue;
1675             }
1676             
1677             $cms_page_category = DB_DataObject::factory('cms_page_category');
1678         
1679             $cms_page_category->setFrom(array(
1680                 'page_id' => $this->id,
1681                 'category_id' => $c
1682             ));
1683             
1684             $cms_page_category->insert();
1685         }
1686         
1687         foreach ($exists as $e){
1688             $e->delete();
1689         }
1690         
1691     }
1692     
1693     function categories()
1694     {
1695         $cms_page_category = DB_DataObject::factory('cms_page_category');
1696         
1697         $cms_page_category->setFrom(array(
1698             'page_id' => $this->id
1699         ));
1700         
1701         $cms_page_category->find();
1702         
1703         $ret = array();
1704         
1705         while ($cms_page_category->fetch()){
1706             $o = clone($cms_page_category);
1707             $ret[$o->category_id] = $o;
1708         }
1709         
1710         return $ret;
1711         
1712     }
1713     
1714     function interests()
1715     {
1716         $ff = HTML_FlexyFramework::get();
1717         if (!in_array('Crm', $ff->enableArray)) {
1718             return array();
1719         }
1720         $i = DB_DataObject::factory('crm_interest');
1721         $i->autoJoin();
1722         $i->onid = $this->id;
1723         $i->ontable = $this->tableName();
1724         
1725         $i->find();
1726         
1727         $ret = array();
1728         
1729         while ($i->fetch()){
1730             $ii = clone($i);
1731             $ret[$ii->interest_id] = $ii;
1732         }
1733         
1734         return $ret;
1735     }
1736     
1737     function toRooSingleArrayInterests($ret, $req)
1738     {
1739         
1740         
1741         $ff = HTML_FlexyFramework::get();
1742         if (!in_array('Crm', $ff->enableArray)) {
1743             return $ret;
1744         }
1745         
1746         
1747         if($ret['page_type_id_name'] == 'blog') {
1748             $li = array();
1749             $interest = DB_DataObject::factory('crm_interest');
1750             $interest->autoJoin();
1751             $interest->onid = $this->id;
1752             $interest->ontable = $this->tableName();
1753             
1754             $interest = $interest->fetchAll('interest_id', 'interest_id_display_name');
1755             
1756             foreach($interest as $k => $v) {
1757                 $li[] = array(
1758                     'id' => $k,
1759                     'display_name' => $v
1760                 );
1761             }
1762
1763             $ret["interests"] = json_encode($li);
1764         }
1765         
1766         return $ret;
1767     }
1768     
1769     function extra_css()
1770     {
1771         if (empty($this->extra_css)) {
1772             return '';
1773         }
1774         return "<style>\n{$this->extra_css}\n</style>\n";
1775     }
1776     
1777     function stylesheets($roo)
1778     {
1779         $enum = DB_DataObject::factory('core_enum');
1780         $enum->setFrom(array(
1781             'etype' => 'Cms.Settings',
1782             'active' => 1,
1783             'name' => 'stylesheets'
1784         ));
1785         
1786         $stylesheets = $enum->fetchAll('display_name');
1787         
1788         $stylesheets = implode("\n", $stylesheets);
1789         
1790         $roo->jdata(array(
1791             '_stylesheets' => $stylesheets
1792         ));
1793     }
1794     
1795     function updateStylesheets($stylesheets, $roo)
1796     {
1797         $stylesheets = empty($stylesheets) ? array() : array_unique(array_filter(explode("\n", $stylesheets)));
1798         
1799         $enum = DB_DataObject::factory('core_enum');
1800         $enum->setFrom(array(
1801             'etype' => 'Cms.Settings',
1802             'active' => 1,
1803             'name' => 'stylesheets'
1804         ));
1805         
1806         $enum->find();
1807         
1808         while ($enum->fetch()){
1809             $o = clone ($enum);
1810             
1811             if(in_array($o->display_name, $stylesheets)){
1812                 unset($stylesheets[array_search($o->display_name, $stylesheets)]);
1813                 continue;
1814             }
1815             
1816             $o->delete();
1817             
1818         }
1819         
1820         foreach ($stylesheets as $s){
1821             $enum = DB_DataObject::factory('core_enum');
1822             $enum->setFrom(array(
1823                 'etype' => 'Cms.Settings',
1824                 'active' => 1,
1825                 'name' => 'stylesheets',
1826                 'display_name' => $s
1827             ));
1828             
1829             $enum->insert();
1830         }
1831         
1832         $roo->jok('DONE');
1833     }
1834     
1835     function build_tree_sequence($page_type_id)
1836     {
1837         $pid = DB_DataObject::factory('core_enum')->lookup('cms_page_type', 'page');
1838         $mid = DB_DataObject::factory('core_enum')->lookup('cms_page_type', 'menu');
1839         $cid = DB_DataObject::factory('core_enum')->lookup('cms_page_type', 'category');
1840             
1841         if(empty($page_type_id) || !in_array($page_type_id, array($pid, $mid, $cid))){
1842             return;
1843         }
1844             
1845         $cms_page = DB_DataObject::factory('cms_page');
1846         
1847         $cms_page->setFrom(array(
1848             'page_type_id' => $page_type_id,
1849             'parent_id' => 0
1850         ));
1851         
1852         if($page_type_id == $pid){
1853             $cms_page->orderBy('cms_page.page_link ASC');
1854         } else {
1855             $cms_page->orderBy('cms_page.seq_id ASC');
1856         }
1857         
1858         $data = $cms_page->fetchAll();
1859         
1860         $this->_build_tree_sequence($data, 0, 0);
1861         
1862     }
1863     
1864     function _build_tree_sequence($data, $sequence, $depth)
1865     {
1866         foreach ($data as $d){
1867             
1868             $dd = clone ($d);
1869             
1870             $d->setFrom(array(
1871                 'tree_sequence' => $sequence,
1872                 'tree_depth' => $depth
1873             ));
1874             
1875             $d->update($dd);
1876             
1877             $pid = DB_DataObject::factory('core_enum')->lookup('cms_page_type', 'page');
1878
1879             $cms_page = DB_DataObject::factory('cms_page');
1880
1881             $cms_page->setFrom(array(
1882                 'parent_id' => $d->id,
1883                 'page_type_id' => $d->page_type_id
1884             ));
1885             
1886             if($d->page_type_id == $pid){
1887                 $cms_page->orderBy('cms_page.page_link ASC');
1888             } else {
1889                 $cms_page->orderBy('cms_page.seq_id ASC');
1890             }
1891
1892             $children = $cms_page->fetchAll();
1893             
1894             $seq = $sequence + 1;
1895             $dep = $depth + 1;
1896             
1897             $sequence = $this->_build_tree_sequence($children, $seq, $dep);
1898             
1899         }
1900         
1901         return $sequence;
1902         
1903     }
1904     
1905     function toPublicData($country = false)
1906     {
1907         $ret = array();
1908         
1909         if(empty($this->id)){
1910             return $ret;
1911         }
1912         
1913         $children = DB_DataObject::factory('cms_page');
1914         $children->autoJoin();
1915         $children->setFrom(array(
1916             'parent_id' => (!empty($this->translation_of_id)) ? $this->translation_of_id : $this->id,
1917             'is_draft' => 0,
1918             'is_deleted' => 0,
1919             'is_element' => 1,
1920             'translation_of_id' => 0
1921         ));
1922         
1923         $children->whereAdd('cms_page.element_id != 0');
1924         
1925         $children->orderBy('cms_page.seq_id ASC');
1926         
1927         $ff = HTML_FlexyFramework::get();
1928         
1929         foreach ($children->fetchAll() as $c){
1930             
1931             $cc = $c->inLanguage($ff->locale);
1932             
1933             if(!isset($ret[$c->element_id_name])){
1934                 $ret[$c->element_id_name] = array();
1935             }
1936             
1937             $image = DB_DataObject::factory('Images');
1938             $image->setFrom(array(
1939                 'ontable' => 'cms_page',
1940                 'onid' => $c->id
1941             ));
1942             
1943             $image->orderBy('Images.displayorder ASC');
1944             
1945             $bgimage = $image->fetchAll(false, false, 'toArray');
1946             
1947             $video = false;
1948             $player = (empty($country) || $country != 'CN') ? 'youtu.be' : 'youku.com';
1949             
1950             foreach ($bgimage as $k => $v) {
1951                 
1952                 if(empty($v['linkurl'])){
1953                     continue;
1954                 }
1955                 
1956                 if(!preg_match('/(youtu.be|youku.com)/i', $v['linkurl'])){
1957                     continue;
1958                 }
1959                 
1960                 if(strpos($v['linkurl'], $player) === false){
1961                     
1962                     if(empty($video)){
1963                         $video = $v;
1964                     }
1965                     
1966                     unset($bgimage[$k]);
1967                     continue;
1968                 }
1969                 
1970                 $video = $v;
1971                 unset($bgimage[$k]);
1972             }
1973             
1974             if(!empty($video)){
1975                 array_unshift($bgimage, $video);
1976             }
1977             
1978             $ret[$c->element_id_name][] = array(
1979                 'size' => (empty($c->template_id_template)) ? '' : $c->template_id_template,
1980                 'title' => $cc->title,
1981                 'html' => $cc->body,
1982                 'extended' => $cc->extended,
1983                 'href' => $c->page_link,
1984                 'cls' => implode(' ', explode(',', $c->page_cls)),
1985                 'bgimage' => $bgimage
1986             );
1987         }
1988         
1989         $ret['page'] = array(
1990             'target' => (!empty($this->translation_of_id)) ? $this->translation_of_id : $this->id,
1991             'title' => $this->title,
1992             'body' => $this->body
1993         );
1994         
1995         return $ret;
1996     }
1997     
1998     function gatherMenu($name)
1999     {
2000         $ret = array();
2001         
2002         $cms_page = DB_DataObject::factory('cms_page');
2003         
2004         $cms_page->setFrom(array(
2005             'is_draft' => 0,
2006             'is_deleted' => 0,
2007             'page_link' => $name,
2008             'is_menuitem' => 1
2009         ));
2010         
2011         $cms_page->orderBy('cms_page.seq_id ASC');
2012         
2013         if(empty($name) || !$cms_page->find(true)){
2014             return $ret;
2015         }
2016         
2017         return $cms_page->gatherSubMenu();
2018         
2019     }
2020     
2021     function gatherSubMenu()
2022     {
2023         $ret = array();
2024         
2025         if(empty($this->id)){
2026             return $ret;
2027         }
2028         
2029         $ff = HTML_FlexyFramework::get();
2030         
2031         $cfg = array(
2032             'type' => 'menu', 
2033             'language' => 'en'
2034         );
2035         
2036         $sub = $this->children($cfg);
2037         
2038         foreach ($sub as $k => $v){
2039             
2040             $vv = $v->inLanguage($ff->locale);
2041             
2042             $item = array(
2043                 'target' => (empty($v->menu_page_id)) ? 0 : $v->menu_page_id,
2044                 'html' => $vv->title,
2045                 'href' => empty($v->menu_page_id_page_link) ? '' : $v->menu_page_id_page_link
2046             );
2047             
2048             $item['children'] = $v->gatherSubMenu();
2049             
2050             $ret[] = $item;
2051         }
2052         
2053         return $ret;
2054         
2055     }
2056     
2057     function dump_pages($q, $au, $roo)
2058     {
2059         if (!extension_loaded('zip')) { // sudo apt-get install php5.6-zip??
2060             die('Please install php zip extension');
2061         }
2062         
2063         $pages = array();
2064         
2065         $cms_page = DB_DataObject::factory('cms_page');
2066         
2067         foreach ($cms_page->fetchAll() as $cp){
2068             $pages[$cp->id] = $cp->toArray();
2069         }
2070         
2071         $types = array();
2072         
2073         $core_enum = DB_DataObject::factory('core_enum');
2074         
2075         $core_enum->setFrom(array(
2076             'etype' => 'cms_page_type',
2077             'active' => 1
2078         ));
2079         
2080         foreach ($core_enum->fetchAll() as $ce){
2081             $types[$ce->id] = $ce->toArray();
2082         }
2083         
2084         $categories = array();
2085         
2086         $cms_page_category = DB_DataObject::factory('cms_page_category');
2087         
2088         foreach ($cms_page_category->fetchAll() as $cpc){
2089             $categories[$cpc->id] = $cpc->toArray();
2090         }
2091         
2092         $templates = array();
2093         
2094         $cms_template = DB_DataObject::factory('cms_template');
2095         
2096         foreach ($cms_template->fetchAll() as $ct){
2097             $templates[$ct->id] = $ct->toArray();
2098         }
2099         
2100         $elements = array();
2101         
2102         $cms_template_element = DB_DataObject::factory('cms_template_element');
2103         
2104         foreach ($cms_template_element->fetchAll() as $cte){
2105             $elements[$cte->id] = $cte->toArray();
2106         }
2107         
2108         $images = array();
2109         $photos = array();
2110         
2111         $img = DB_DataObject::factory('Images');
2112         $img->setFrom(array(
2113             'ontable' => 'cms_page'
2114         ));
2115         
2116         foreach ($img->fetchAll() as $i){
2117             $images[$i->id] = $i->toArray();
2118             
2119             if(!array_key_exists($i->filename, $photos)){
2120                 $photos[$i->filename] = $i->getStoreName();
2121             }
2122             
2123         }
2124         
2125         $json = json_encode(array(
2126             'pages' => $pages,
2127             'types' => $types,
2128             'categories' => $categories,
2129             'templates' => $templates,
2130             'elements' => $elements,
2131             'images' => $images,
2132             'photos' => array_keys($photos)
2133         ));
2134         
2135         $zipFile = $roo->tempName('zip');
2136         
2137         $zip = new ZipArchive();
2138         
2139         if ($zip->open($zipFile, ZipArchive::CREATE) !== TRUE) {
2140             die('Can not create zip file');
2141         }
2142         
2143         $zip->addFromString('data.json', $json);
2144         
2145         foreach ($photos as $name => $path){
2146             $zip->addFile($path, $name);
2147         }
2148         
2149         $zip->close();
2150         
2151         require_once 'File/Convert.php';
2152         
2153         $fc=  new File_Convert($zipFile, 'pplication/zip');
2154         $fn = $fc->convert('pplication/zip'); 
2155         $fc->serve('attachment', 'cms-page-dummy-page.zip', true);
2156         
2157         exit;
2158         
2159     }
2160     
2161     function applyFilterTemplateElements($q, $au, $roo)
2162     {
2163         $cms_page = DB_DataObject::factory('cms_page');
2164         
2165         if(!$cms_page->get($q['_list_elements'])){
2166             $roo->jerr('Invalid id');
2167         }
2168         
2169         $pid = DB_DataObject::factory('core_enum')->lookup('cms_page_type', 'page');
2170         
2171         if($cms_page->page_type_id != $pid || empty($cms_page->template_id)){
2172             $roo->jdata(array());
2173         }
2174         
2175         $eid = DB_DataObject::factory('core_enum')->lookup('cms_page_type', 'element');
2176         
2177         $items = DB_DataObject::factory('cms_page');
2178         $items->autoJoin();
2179         $items->setFrom(array(
2180             'parent_id' => $cms_page->id,
2181             'is_element' => 1,
2182             'page_type_id' => $eid
2183         ));
2184         
2185         $items->whereAdd('cms_page.element_id != 0 AND cms_page.translation_of_id = 0');
2186         
2187         if (empty($q['_show_deleted'])) {
2188             $items->is_deleted =  0 ;
2189         }
2190         
2191         $items->selectAdd();
2192         
2193         $items->selectAdd("
2194             cms_page.id AS id,
2195             cms_page.title AS title,
2196             join_element_id_id.name AS element_id_name,
2197             cms_page.seq_id AS seq_id,
2198             cms_page.is_draft AS is_draft,
2199             cms_page.is_deleted AS is_deleted,
2200             cms_page.language AS language,
2201             join_template_id_id.template AS template_id_template,
2202             (
2203                 SELECT
2204                         GROUP_CONCAT(cp.language SEPARATOR ',')
2205                 FROM
2206                         cms_page AS cp
2207                 WHERE
2208                         cp.translation_of_id = cms_page.id
2209             ) AS translation_type,
2210             (
2211                 SELECT
2212                         id
2213                 FROM
2214                         Images
2215                 WHERE
2216                         Images.ontable = 'cms_page'
2217                     AND
2218                         Images.onid = cms_page.id
2219                 ORDER BY 
2220                         Images.displayorder ASC
2221                 LIMIT 1
2222             ) AS primary_image_id
2223         ");
2224         
2225         $items->orderBy("join_element_id_id.name ASC, cms_page.seq_id ASC");
2226         
2227         $total = $items->count();
2228         
2229         $start = (empty($q['start'])) ? 0 : $q['start'];
2230         $limit = (empty($q['limit'])) ? 25 : $q['limit'];
2231         
2232         $items->limit($start, $limit);
2233         
2234         $ret = $items->fetchAll(false, false, 'toArray');
2235         
2236         $roo->jdata($ret, $total);
2237         
2238     }
2239     
2240     function updatePageSeq($type, $roo)
2241     {
2242         $this->reOrderSeq($roo);
2243         
2244         $target = DB_DataObject::factory('cms_page');
2245         $target->get($this->id);
2246         
2247         $cms_page = DB_DataObject::factory('cms_page');
2248         
2249         $cms_page->setFrom(array(
2250             'is_draft' => 0,
2251             'is_deleted' => 0,
2252             'parent_id' => $target->parent_id,
2253             'element_id' => $target->element_id,
2254             'page_type_id' => $target->page_type_id,
2255             'is_element' => 1
2256         ));
2257         
2258         switch ($type) {
2259             case 'down' :
2260                 
2261                 $cms_page->whereAdd("cms_page.seq_id > {$target->seq_id}");
2262                 
2263                 $cms_page->orderBy('cms_page.seq_id ASC');
2264                 
2265                 break;
2266             case 'up' :
2267                 
2268                 $cms_page->whereAdd("cms_page.seq_id < {$target->seq_id}");
2269                 
2270                 $cms_page->orderBy('cms_page.seq_id DESC');
2271                 
2272                 break;
2273         }
2274         
2275         
2276         
2277         if(!$cms_page->find(true)){
2278             $roo->jok('OK');
2279         }
2280         
2281         $ot = clone($target);
2282         $oc = clone($cms_page);
2283         
2284         $target->seq_id = $oc->seq_id;
2285         $cms_page->seq_id = $ot->seq_id;
2286         
2287         $target->update($ot);
2288         $cms_page->update($oc);
2289         
2290         $roo->jok('OK');
2291         
2292     }
2293     
2294     function reOrderSeq($roo)
2295     {
2296         $cms_page = DB_DataObject::factory('cms_page');
2297         
2298         $cms_page->setFrom(array(
2299             'is_draft' => 0,
2300             'is_deleted' => 0,
2301             'parent_id' => $this->parent_id,
2302             'element_id' => $this->element_id,
2303             'page_type_id' => $this->page_type_id,
2304             'is_element' => 1
2305         ));
2306         
2307         $validate = clone($cms_page);
2308         
2309         $validate->selectAdd();
2310         $validate->selectAdd("
2311             DISTINCT(cms_page.seq_id) AS seq_id,
2312             COUNT(cms_page.id) AS total
2313         ");
2314         
2315         $validate->groupBy('cms_page.seq_id');
2316         
2317         $validate->having('total > 1');
2318         
2319         $validate->limit(1);
2320         
2321         $res = $validate->fetchAll();
2322         if(empty($res)){ // looks good...
2323             return;
2324         }
2325         
2326         $cms_page->orderBy('cms_page.seq_id ASC, cms_page.id ASC');
2327         
2328         foreach ($cms_page->fetchAll() as $k => $v){
2329             
2330             $o = clone($v);
2331             
2332             $v->seq_id = $k + 1;
2333             
2334             $v->update($o);
2335         }
2336         
2337         return;
2338         
2339     }
2340     
2341     function copy($id, $roo)
2342     {
2343         $cms_page = DB_DataObject::factory('cms_page');
2344         
2345         if(empty($id) || !$cms_page->get($id)){
2346             $roo->jerr('Invalid id');
2347         }
2348         
2349         $n = DB_DataObject::factory('cms_page');
2350         $n->setFrom($cms_page->toArray());
2351         
2352         $n->setFrom(array(
2353             'title' => (!empty($cms_page->title)) ? "Copy of {$cms_page->title}" : '',
2354             'page_link' => (!empty($cms_page->page_link)) ? "{$cms_page->page_link}-copy" : '',
2355             'updated' => date('Y-m-d H:i:s'),
2356             'created' => date('Y-m-d H:i:s')
2357         ));
2358             
2359         $n->insert();
2360         
2361         $images = DB_DataObject::factory('Images');
2362         $images->setFrom(array(
2363             'ontable' => 'cms_page',
2364             'onid' => $cms_page->id
2365         ));
2366         
2367         foreach ($images->fetchAll() as $i){
2368             
2369             $ni = DB_DataObject::factory('Images');
2370             $ni->setFrom(array(
2371                 'ontable' => 'cms_page',
2372                 'onid' => $n->id
2373             ));
2374             
2375             $ni->createFrom($i->getStoreName(), $i->filename);
2376             
2377             if(!empty($ni->err)){
2378                 $roo->jerr($ni->err);
2379             }
2380         }
2381         
2382         $eid = DB_DataObject::factory('core_enum')->lookup('cms_page_type', 'element');
2383         
2384         $elements = DB_DataObject::factory('cms_page');
2385         $elements->setFrom(array(
2386             'parent_id' => $cms_page->id,
2387             'is_element' => 1,
2388             'page_type_id' => $eid
2389         ));
2390         
2391         $elements->whereAdd('cms_page.element_id != 0 AND cms_page.translation_of_id = 0');
2392         
2393         foreach ($elements->fetchAll() as $element) {
2394             
2395             $ne = DB_DataObject::factory('cms_page');
2396             $ne->setFrom($element->toArray());
2397
2398             $ne->setFrom(array(
2399                 'parent_id' => $n->id,
2400                 'title' => (!empty($element->title)) ? "Copy of {$element->title}" : '',
2401                 'page_link' => (!empty($element->page_link)) ? "{$element->page_link}-copy" : '',
2402                 'updated' => date('Y-m-d H:i:s'),
2403                 'created' => date('Y-m-d H:i:s')
2404             ));
2405
2406             $ne->insert();
2407             
2408             $images = DB_DataObject::factory('Images');
2409             $images->setFrom(array(
2410                 'ontable' => 'cms_page',
2411                 'onid' => $element->id
2412             ));
2413
2414             foreach ($images->fetchAll() as $i){
2415
2416                 $nei = DB_DataObject::factory('Images');
2417                 $nei->setFrom(array(
2418                     'ontable' => 'cms_page',
2419                     'onid' => $ne->id
2420                 ));
2421
2422                 $nei->createFrom($i->getStoreName(), $i->filename);
2423                 
2424                 if(!empty($nei->err)){
2425                     $roo->jerr($nei->err);
2426                 }
2427             }
2428             
2429         }
2430         
2431         $roo->jok($n->id);
2432         
2433     }
2434     
2435 }
2436