private function findPictureByURLSegment($URLSegment, $cached = true)
 {
     if ($cached && $this->CurrentPicture) {
         return $this->CurrentPicture;
     }
     if (!$URLSegment) {
         $this->CurrentPicture = $this->dataRecord->FirstPicture();
     } else {
         $this->CurrentPicture = GalleryPicture::get()->filter(["URLSegment" => $URLSegment, "PageID" => $this->dataRecord->ID])->first();
     }
     return $this->CurrentPicture;
 }
 function onBeforeWrite()
 {
     parent::onBeforeWrite();
     if ($this->ParmanentURLSegment) {
         $this->URLSegment = $this->ParmanentURLSegment;
         return;
     }
     if (!$this->URLSegment || preg_match("/^\\d+\$/", $this->URLSegment) || $this->isChanged('Title') || $this->forceUpdateURLSegment) {
         $filter = URLSegmentFilter::create();
         $t = $filter->filter($this->Title());
         if (strlen(trim($t)) > 0) {
             $this->URLSegment = $t;
         } else {
             $this->URLSegment = $this->Sort;
         }
         if (!$this->URLSegment) {
             $this->URLSegment = $this->ID;
         }
     }
     // check for duplicate URLSegment
     $i = 1;
     // $this->URLSegment = preg_replace("/(^.*?)(\-\d+)+$/","$1", $this->URLSegment);
     while (GalleryPicture::get()->filter(['URLSegment' => $this->URLSegment, 'PageID' => $this->PageID])->exclude(['ID' => $this->ID])->Count() > 0) {
         $this->URLSegment = preg_replace("/(^.*?)(\\-\\d+)+\$/", "\$1", $this->URLSegment);
         $number = preg_match("/\\-*0*(\\d)+\$/", $this->URLSegment, $matches) ? intval($matches[1]) + 1 : $i;
         $this->URLSegment = $this->URLSegment . "-" . sprintf('%02d', $number);
         $i++;
     }
 }