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