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