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