<?php

class Page extends SiteTree implements PermissionProvider {

    public static $db = array(
    );
    
    public static $has_one = array(
      //  'SidebarWidget' => 'WidgetArea',
	);
    
    public static $itemsPerPage = 15;
    
    /*
     * Fixing sitetree_link shortcode
     */
    public function Content() {
        return DBField::create('HTMLText', $this->Content); 
    }

    public function ChildrenWithLimit($limit, $offset = 0) {
        $children = $this->Children();
        return empty($children) ? null : $children->getRange($offset, $limit);
    }

    public function ChildrenCountMoreThan($count) {
        $children = $this->Children();
        return empty($children) ? false : ($children->Count() > $count);
    }

    public function getCMSFields() {
        $fields = parent::getCMSFields();
//        $fields->addFieldToTab(
//			'Root.Content.Widgets', new WidgetAreaEditor('SidebarWidget')
//		);
        $fields->removeByName('ProvideComments');
        return $fields;
    }
    
   
    public function isFrontpage() {
        return ( $this->ClassName=='Frontpage' );
    }
    
    
    protected function _localizeDate($value, $format = 'long') {
		if (empty($value)) {
			return null;
		}
		// lt_LT nes datetime = YYYY-mm-dd
		$date = new Zend_Date($value, null, 'lt_LT');
		
		switch ($format) {
			case 'short':
				$format = Zend_Date::DATE_SHORT;
				break;
			case 'medium':
				$format = Zend_Date::DATE_MEDIUM;
				break;
			case 'full':
				$format = Zend_Date::DATE_FULL;
				break;
			case 'long':
			default:
				$format = Zend_Date::DATE_LONG;
		}
		
		return $date->toString($format, null, Translatable::get_current_locale());
	}
	
	public function Locale() {
		return Translatable::get_current_locale();
	}
	
	protected function _localizedMonth($dateValue) {
		$date = new Zend_Date($dateValue);
		
		return $date->toString(Zend_Date::MONTH_NAME, null, Translatable::get_current_locale());
	}
	
	protected function _stringForJavascript($value) {
		return str_replace(array("\n", "\t", "\r"), ' ', strip_tags(trim($value)));
	}
	
	public function Breadcrumbs($maxDepth = 20, $unlinked = false, $stopAtPageType = false, $showHidden = false) {
		parent::$breadcrumbs_delimiter = " / ";
		return parent::Breadcrumbs($maxDepth, $unlinked, $stopAtPageType, $showHidden);
	}

    public function CustomBaseHref() {
        return substr(Director::absoluteBaseURL(), 0, -1);
    }

    public function PosGreaterThanNine() {
        return ($this->Pos() > 9);
    }
    
    
    /*
     * current position of results
     * @param boolean $search - search result pagination is different then other pages.
     * @return current position of all results
     */
    public function currentPosition($search=false)  {
        
        $page = isset($_REQUEST['start']) ? (int) $_REQUEST['start'] : 0;
        if((int)$page==0) $page = 1;
        
        $currentPos = $this->Pos();
        if($search && $page > 1) $currentPos += 1;
       
        $itemsPerPage = ((int)$this->itemsPerPage > 0) ? $this->itemsPerPage : 1;
        $pos = ($page - 1) * $itemsPerPage + $currentPos;

        if((int)$pos < 10) {
            $pos = '0'.$pos;
        }
        return $pos;
        
    }
    

    function EntriesMoreThan($value) {
        $num_entries = $this->DirectoryEntries()->Count();

        return ($num_entries > $value);
    }
    
    public function ParentLink() {
		$myparent = $this->ParentID;

		$parent = DataObject::get_one('Page', "ParentID = '" . $this->ParentID . "'");
		if ($parent) {
			return $parent->Link();
		}
		return false;
	}

    public function LinkHomepageCurrLang() {
        //return Translatable::get_homepage_link_by_locale(Translatable::get_current_locale());
        $homepage = Translatable::get_one_by_locale('Frontpage', Translatable::get_current_locale(), "Status='Published'");
        return $homepage->URLSegment;
    }
    
    public function IsHomepage() {
		return $this->LinkHomepageCurrLang() == $this->URLSegment;
	}
	
	public function AbsoluteHomeURL() {
		return Director::absoluteURL("/", true);
	}
 
    public function getOtherLanguages() {

        $where = "Status='Published' AND ClassName='Frontpage'";
        $baseTable = ClassInfo::baseDataClass('SiteTree');
        $query = new SQLQuery("Distinct \"Locale\", URLSegment", "\"$baseTable\"", $where, '', "\"Locale\"");

        $dbLangs = $query->execute()->column();

        $langlist = (array) $dbLangs;
        $langs = new DataObjectSet();
        $allCodes = array_merge(i18n::$all_locales, i18n::$common_locales);
        $originalLocale = Translatable::get_current_locale();
        foreach ($langlist as $langCode) {
            if ($langCode && isset($allCodes[$langCode]) && strtolower($langCode) != strtolower($originalLocale)) {

                $lang = new DataObjectSet();
                $lang->Code = $langCode;
                Translatable::set_current_locale($langCode);
                $lang->Locale = Translatable::get_current_locale();
                $lang->ShortCode = strtoupper(substr($langCode, 0, 2));
               
                $lang->Title = (is_array($allCodes[$langCode])) ? $allCodes[$langCode][0] : $allCodes[$langCode];
                $homepage = Translatable::get_one_by_locale('Frontpage', $langCode, "Status='Published'");
                $lang->Link = $homepage->URLSegment;
                $langs->push($lang);
                Translatable::set_current_locale($originalLocale);
            }
        }
        return $langs;
    }
    
    
    public function getLanguages() {

        $where = "Status='Published' AND ClassName='Frontpage'";
        $baseTable = ClassInfo::baseDataClass('SiteTree');
        $query = new SQLQuery("Distinct \"Locale\", URLSegment", "\"$baseTable\"", $where, '', "\"Locale\"");

        $dbLangs = $query->execute()->column();

        $langlist = (array) $dbLangs;
        
	//	print "<!--";
	//	print_r($langlist);
	//	print "-->";
		$langs = new DataObjectSet();
        $allCodes = array_merge(i18n::$all_locales, i18n::$common_locales);
        $originalLocale = Translatable::get_current_locale();
        $cntTmp = 0;
        foreach ($langlist as $langCode) {
            if ($langCode && isset($allCodes[$langCode])) {

                $lang = new DataObjectSet();
                $lang->Code = $langCode;
                Translatable::set_current_locale($langCode);
                $lang->Locale = Translatable::get_current_locale();
                $lang->ShortCode = strtoupper(substr($langCode, 0, 2));
                if ($langCode == $originalLocale) {
                    $lang->Current = true;
                } else {
                    $lang->Current = false;
                }
                $lang->Title = (is_array($allCodes[$langCode])) ? $allCodes[$langCode][0] : $allCodes[$langCode];
                $homepage = Translatable::get_one_by_locale('Frontpage', $langCode, "Status='Published'");
                $lang->Link = $homepage->URLSegment;
                $cntTmp++;
                $langs->push($lang);
            }

            Translatable::set_current_locale($originalLocale);
        }
        
        return ($cntTmp > 1) ? $langs : false;
    }

    /**
     * Extended SiteTree function for manage foreign symbols
     * 
     * @param string $title Page title.
     * @return string Generated url segment
     */
    public function generateURLSegment($title) {
        
        $title = $this->ForeignToLatin($title);
        
        $t = (function_exists('mb_strtolower')) ? mb_strtolower($title) : strtolower($title);
        $t = Object::create('Transliterator')->toASCII($t);
        $t = str_replace('&amp;', '-and-', $t);
        $t = str_replace('&', '-and-', $t);
        $t = ereg_replace('[^A-Za-z0-9]+', '-', $t);

        $t = ereg_replace('-+', '-', $t);
        if (!$t || $t == '-' || $t == '-1') {
            $t = "pageg-$this->ID";
        }
        $t = trim($t, '-');

        // Hook for decorators
        $this->extend('updateURLSegment', $t, $title);

        return $t;
    }
    
    
    /**
     * Convert Foreign symbols to Latin
     * 
     * @param string $str.
     * @return string with only Latin Symbols
     */
    public function ForeignToLatin($str) {
        $tr = array(
            "А" => "a", "Б" => "b", "В" => "v", "Г" => "g", "Д" => "d",
            "Е" => "e", "Ё" => "yo", "Ж" => "zh", "З" => "z", "И" => "i",
            "Й" => "j", "К" => "k", "Л" => "l", "М" => "m", "Н" => "n",
            "О" => "o", "П" => "p", "Р" => "r", "С" => "s", "Т" => "t",
            "У" => "u", "Ф" => "f", "Х" => "kh", "Ц" => "ts", "Ч" => "ch",
            "Ш" => "sh", "Щ" => "sch", "Ъ" => "", "Ы" => "y", "Ь" => "",
            "Э" => "e", "Ю" => "yu", "Я" => "ya", "а" => "a", "б" => "b",
            "в" => "v", "г" => "g", "д" => "d", "е" => "e", "ё" => "yo",
            "ж" => "zh", "з" => "z", "и" => "i", "й" => "j", "к" => "k",
            "л" => "l", "м" => "m", "н" => "n", "о" => "o", "п" => "p",
            "р" => "r", "с" => "s", "т" => "t", "у" => "u", "ф" => "f",
            "х" => "kh", "ц" => "ts", "ч" => "ch", "ш" => "sh", "щ" => "sch",
            "ъ" => "", "ы" => "y", "ь" => "", "э" => "e", "ю" => "yu",
            "я" => "ya", "ą" => "a", "č" => "c", "ę" => "e", "ė" => "e",
            "į" => "i", "š" => "s", "ų" => "u", "ū" => "u", "ž" => "z"
        );
        return strtr($str, $tr);
    }
    
    /* Check for live version
     * @return boolean
     */ 
    public function isLiveVersion() {
        return Director::isLive(); 
    }
    
    public function IsTest() {
		return Director::isTest();
	}
    
    
    /*
     * Last but one element
     */
    public function Penultimate() {
		return $this->iteratorPos == $this->iteratorTotalItems - 2;
	}
    
    /**
	 * Change paragraph to break only
	 */
	public function ChangeParagraphTags(){    
        return str_replace(array('<p>', '</p>'),array('',' '),$this->Content);
	}
    
	public function getCustomLink($class="JobOffersHolder") {
        $item = DataObject::get_one($class);
        if($item) {
            return $item->Link();
        }
        return false;
    }

    /**
     * Banner in left from SiteConfig
     * @return \ArrayData|boolean
     */
    public function getBanner() {
        $siteConfig = SiteConfig::current_site_config();
        if($siteConfig && $siteConfig->exists() && $siteConfig->BannerImage() && $siteConfig->BannerActive) {
            if($siteConfig->BannerInnerPageID) {
                $bannerLink = $siteConfig->BannerInnerPage()->Link();
                $newWindow = false;
            } else {
                $bannerLink = $siteConfig->BannerLink;
                $newWindow = true;
            }
            return new ArrayData(
                array(
                    'BannerImage' => $siteConfig->BannerImage(), 
                    'BannerLink' => $bannerLink,
                    'NewWindow' => $newWindow
                ));
        }
        return false;
    }

    
}


class Page_Controller extends ContentController  { //implements PermissionProvider

    /**
     * An array of actions that can be accessed via a request. Each array element should be an action name, and the
     * permissions or conditions required to allow the user to access it.
     *
     * <code>
     * array (
     *     'action', // anyone can access this action
     *     'action' => true, // same as above
     *     'action' => 'ADMIN', // you must have ADMIN permissions to access this action
     *     'action' => '->checkAction' // you can only access this action if $this->checkAction() returns true
     * );
     * </code>
     *
     * @var array
     */

    public static $allowed_actions = array(
    );
    
    function results($data, $form) {
        
        $form->pageLength = Page::$itemsPerPage;
        
        $data = array(
            'Results' => $form->getResults(),
            'Query' => $form->getSearchQuery(),
            'Title' => _t('LangEditor.SEARCH_RESULTS_TITLE', 'Your search results')
        );
        $this->Query = $form->getSearchQuery();
        return $this->customise($data)->renderWith(array('Page_results', 'Page'));
    }

    public function init() {
        parent::init();
        
        if ($this->dataRecord->hasExtension('Translatable')) {
            i18n::set_locale($this->dataRecord->Locale);
        }

        if (!$this->dbObject('Content')->hasValue() && ($this->ClassName == 'Page')) {
            if ($this->Children()->Count()) {
                Director::redirect($this->Children()->First()->AbsoluteLink());
                //Director::redirect($this->Children()->First()->AbsoluteLink(), 301);
            }
        }
    }

    public function StatusMessage() {
        if ($message = Session::get('ActionMessage')) {
            $status = Session::get('ActionStatus');
            Session::clear('ActionStatus');
            Session::clear('ActionMessage');
            return new ArrayData(array('Message' => $message, 'Status' => $status));
        }
        return false;
    }
	

	/**
	 * Remove generator=silverstripe tag
	 * Return the title, description, keywords and language metatags.
	 * @return string The XHTML metatags
	 */
	public function MetaTags($includeTitle = true) {
		$tags = "";
		if($includeTitle === true || $includeTitle == 'true') {
			$tags .= "<title>" . Convert::raw2xml(($this->MetaTitle)
				? $this->MetaTitle
				: $this->Title) . "</title>\n";
		}

		$charset = ContentNegotiator::get_encoding();
		//$tags .= "<meta http-equiv=\"Content-type\" content=\"text/html; charset=$charset\" />\n";
		if($this->MetaKeywords) {
			$tags .= "<meta name=\"keywords\" content=\"" . Convert::raw2att($this->MetaKeywords) . "\" />\n";
		}
		if($this->MetaDescription()) {
			$tags .= "<meta name=\"description\" content=\"" . Convert::raw2att($this->MetaDescription()) . "\" />\n";
		}
		if($this->ExtraMeta) { 
			$tags .= $this->ExtraMeta . "\n";
		} 
		$tags .= $this->FacebookMetaTags();

		$this->extend('MetaTags', $tags);

		return $tags;
	}
	
	public function MetaDescription(){
		return $this->MetaDescription;
	}
	
	public function FacebookMetaTags() {
		//return true;
	}
	
    /*
     * Import job offers from remote xml
     * before import must delete all data - requirement
     */
    public function ImportXMLCronTask(){

        $cronMailContent = "<p>ImportXMLCronTask START ".date('Y-m-d H:i:s')."</p>\r\n";
        $siteconfig =  SiteConfig::current_site_config();
        if($siteconfig && $siteconfig->XmlURL) {
            $url = $siteconfig->XmlURL;
        } else {
            $url = "http://export.biuro.lt/www.php";
        }
       
        $xml = new RestfulService($url, 50); 
        $connect = $xml->request(); 
        $cronMailContent .= "Connect...".date('H:i:s')."<br />\r\n";    

		//print $url;
		//print "<pre>";
		//print_r($connect);
        $result = $connect->simpleXML($connect->getBody()); 
		
		/*try {
				$result->simpleXML = new SimpleXMLElement($this->body);
			}
			catch(Exception $e) {
				user_error("String could not be parsed as XML. " . $e, E_USER_WARNING);
			}*/
		
		//$file = file_get_contents($url, false, $context);
		//print_r($file);
        

		if($result) {
        $cronMailContent .= "Got result ".date('H:i:s')."<br />\r\n"; 
        foreach($result as $key => $value) { 
            
            $XmlID = (int)$value['ID'];
            // if already exist in our DB
            $item = DataObject::get_one('JobOffersData', "Xmlidn = '".$XmlID."'");
            
            //if ($XmlID==773) print html_entity_decode($value->APRASYMAS);
            // just update all info except URLSegment
            if($item) {
                
                $item->Type = (int)$value['TIPAS'];
                $item->Xmlidn = (int)$value['ID'];
                $item->Title = html_entity_decode($value->PAREIGOS);
                $item->Company = html_entity_decode($value->IMONE);
                $item->OfferType = (string)$value->RUSIS;
                $item->Sector = (string)$value->SRITIS;
                $item->Description = html_entity_decode($value->APRASYMAS);
                $item->AdditionalInfo = html_entity_decode($value->KITA);
                $item->City = (string)$value->VIETA;
                $item->Email = (string)$value->EPASTAS;
                $item->OfferLang = (string)$value['KALBA'];
                $item->Department = (string)$value->PADALINYS;
                $item->ContactPerson = (string)$value->KONTAKTASMUO;
                $item->WorkHours = (string)$value->DARBOLAIKAS;
                $item->PublishDate = date('Y-m-d', strtotime((string)$value['PASKELBTA']));
                $item->ValidToDate = date('Y-m-d', strtotime((string)$value['GALIOJA']));
                $item->TsUpdated = date('Y-m-d H:i:s');
                $item->UpdatedDate = $item->CreatedDate;

                if($value->RODYTI && $value->RODYTI->LANG) {
                    foreach($value->RODYTI->LANG as $lang) {
                        if($lang['ID']=='ru') {
                            $item->ShowRU = true;
                        } elseif($lang['ID']=='en') {
                            $item->ShowEN = true;
                        } else {
                            $item->ShowLT = true;
                        }
                    }
                }


/* neimportuojam logo - nebereikia
                // echo (int)$value['ID'].' '.$value->LOGO;
                                
                $LogoURL = (string)$value->LOGO;
                if(!empty($LogoURL)) {

                    $path = ASSETS_PATH.'/Uploads/joboffers/';
                    $ext = pathinfo($LogoURL, PATHINFO_EXTENSION);
                    $name = pathinfo($LogoURL, PATHINFO_FILENAME).date('YmdHis');
                    $tmp = pathinfo($LogoURL, PATHINFO_FILENAME).'.'.$ext;

                    $LogoInfo= get_headers($LogoURL, 1);

                    file_put_contents($path.$tmp, file_get_contents($LogoURL));
                    $_FILES = array(
                        'Logo' => array(
                            'name' => basename($name.'.'.$ext),
                            'type' => 'image/'.$ext,
                            'tmp_name' => $path.$tmp,
                            'error' => 0,
                        'size' => $LogoInfo['Content-Length'],
                        ),
                    );

                    $file = new Image();
                    $upload = new Upload();
                    $upload->setValidator(new Upload_Validator_Void());
                    $uploaded = $upload->loadIntoFile($_FILES['Logo'], $file, 'Uploads/joboffers');
                    if ($uploaded) {
                        // pasalinam pries tai buvusi img
                        if($item->LogoID) {
                            $image = DataObject::get_by_id('Image', $item->LogoID);
                            if($image) {
                                $image->deleteFormattedImages();
                                $image->delete();
                            }
                        }
                        $file->write();
                        $item->LogoID = $file->ID;
                    } 
                    unlink($path.$tmp);

                }
logo atjungiam */ 
                
                $item->write();
                $cronMailContent .= "UPDATED ID: ".$item->ID." - XMLID: ".$XmlID." ".date('H:i:s')."<br />\r\n";
               
            } else { 
              
                // insert new job offer

                $item = new JobOffersData();

                $item->Type = (int)$value['TIPAS'];
                $item->Xmlidn = (int)$value['ID'];
                $item->Title = html_entity_decode($value->PAREIGOS);
                $item->URLSegment = $this->generateURLSegment((string)$value->PAREIGOS.'-'.$value['ID']);
                $item->Company = html_entity_decode($value->IMONE);
                $item->OfferType = (string)$value->RUSIS;
                $item->Sector = (string)$value->SRITIS;
                $item->Description = html_entity_decode($value->APRASYMAS);
                $item->AdditionalInfo = html_entity_decode($value->KITA);
                $item->City = (string)$value->VIETA;
                $item->Email = (string)$value->EPASTAS;
                $item->OfferLang = (string)$value['KALBA'];
                $item->Department = (string)$value->PADALINYS;
                $item->ContactPerson = (string)$value->KONTAKTASMUO;
                $item->WorkHours = (string)$value->DARBOLAIKAS;
                $item->PublishDate = date('Y-m-d', strtotime((string)$value['PASKELBTA']));
                $item->ValidToDate = date('Y-m-d', strtotime((string)$value['GALIOJA']));
                $item->TsCreated = date('Y-m-d H:i:s');
				$item->TsUpdated = date('Y-m-d H:i:s');
                $item->CreatedDate = date('Y-m-d H:i:s', strtotime((string)$value['ATNAUJINTA']));
                $item->UpdatedDate = $item->CreatedDate;

                if($value->RODYTI && $value->RODYTI->LANG) {
                    foreach($value->RODYTI->LANG as $lang) {
                        if($lang['ID']=='ru') {
                            $item->ShowRU = true;
                        } elseif($lang['ID']=='en') {
                            $item->ShowEN = true;
                        } else {
                            $item->ShowLT = true;
                        }
                    }
                }
                
/* nebeimam logo
                // echo (int)$value['ID'].' '.$value->LOGO;

                $LogoURL = (string)$value->LOGO;
                if(!empty($LogoURL)) {

                    $path = ASSETS_PATH.'/Uploads/joboffers/';
                    $ext = pathinfo($LogoURL, PATHINFO_EXTENSION);
                    $name = pathinfo($LogoURL, PATHINFO_FILENAME).date('YmdHis');
                    $tmp = pathinfo($LogoURL, PATHINFO_FILENAME).'.'.$ext;

                    $LogoInfo= get_headers($LogoURL, 1);

                    file_put_contents($path.$tmp, file_get_contents($LogoURL));
                    $_FILES = array(
                        'Logo' => array(
                            'name' => basename($name.'.'.$ext),
                            'type' => 'image/'.$ext,
                            'tmp_name' => $path.$tmp,
                            'error' => 0,
                        'size' => $LogoInfo['Content-Length'],
                        ),
                    );
                    
                    $file = new Image();
                    $upload = new Upload();
                    $upload->setValidator(new Upload_Validator_Void());
                    $uploaded = $upload->loadIntoFile($_FILES['Logo'], $file, 'Uploads/joboffers');
                    if ($uploaded) {
                        $file->write();
                        $item->LogoID = $file->ID;
                    } 
                    unlink($path.$tmp);

                }
nebeimam logo */                
                $item_id = $item->write();
                $cronMailContent .= "NEW ID: ".$item_id." - XMLID: ".$item->Xmlidn." ".date('H:i:s')."<br />\r\n";
            }
        } 
		
        $this->CleanOldOffers();
		} else {
			$cronMailContent .= "<p>Nenuskaite xmlo</p>\r\n";
		}
        $cronMailContent .= "<p>ImportXMLCronTask END ".date('Y-m-d H:i:s')."</p>\r\n";
		//@mail('neringa@idea.lt', 'BIURO LT: ImportXMLCrontTask', $cronMailContent, 
		//	'From: nerrige@gmail.com' . "\r\n" .'Reply-To: nerrige@gmail..com' . "\r\n" .'X-Mailer: PHP/' . phpversion());

        echo $cronMailContent;
        exit;
     }
     
     
     /*
      * salinam neatnaujintus irasus
      */
     public function CleanOldOffers() {
         
        //$date = date('Y-m-d H:i:s', strtotime('-1 hour'));
		$date = date('Y-m-d H:i:s', strtotime('-30 minutes'));
		
        //$objects = DataObject::get('JobOffersData', "TsUpdated<='".$date."' OR TsUpdated='NULL'");
		$objects = DataObject::get('JobOffersData', "TsUpdated<='".$date."'");
		if (empty($objects)) {
			return;
		}
        
	$deleted = '';
        foreach ($objects as $row) {
            if ($row->ClassName != 'JobOffersData') {
				continue;
			}
			echo '<p>Trinam ID: '.$row->ID.' - XMLID: '.$row->Xmlidn.'</p>';
            $image = DataObject::get_by_id('Image', $row->LogoID);
            if($image) {
                $image->deleteFormattedImages();
                $image->delete();
            }     	
			$deleted .= "<p>Trinam ID: ".$row->ID." - XMLID: ".$row->Xmlidn."</p>\r\n";
            $row->delete();
		}
		
		//@mail('neringa@idea.lt', 'BIURO LT: CleanOldOffers', $deleted, 
		//	'From: nerrige@gmail.com' . "\r\n" .'Reply-To: nerrige@gmail..com' . "\r\n" .'X-Mailer: PHP/' . phpversion());
		return;
    }

    
     

}

class Upload_Validator_Void extends Upload_Validator {
	public function isValidSize() {
		return true;
	}
	
	public function isValidExtension() {
		return true;
	}	
	
	public function validate() {
		return true;
	}
}