*/ class Gallery extends GalleryBase implements iSearchable { /** * defines that its stored data should be removed from the system, too */ const REMOVE_INST_DEL_DATA = 'inst_rem_del_dir'; protected function getMyId() { return 'mcms.gallery'; } public function createInstance($siteId, $instanceName, array $param = array()) { parent::createInstance($siteId, $instanceName, $param); System::getInstance()->createFileStoreDir($instanceName, $siteId, false); } public function removeInstance($siteId, $instanceName, array $param = array()) { parent::removeInstance($siteId, $instanceName, $param); $system = System::getInstance(); $system->purgeFileCacheDir($instanceName, $siteId); if(in_array(self::REMOVE_INST_DEL_DATA, $param)) { // remove the file storage $system->deleteFileStoreDir($instanceName, $siteId, false); } } protected function getStorageType() { $system = System::getInstance(); $val = $system->getSiteParam(NULL, self::clazz(), 'storage', iStoreSvc::T_FILE); return $val; } /** * @return iStoreSvc */ protected function getStorageService() { switch ($this->getStorageType()) { case iStoreSvc::T_FILE: return new FileStoreSvc(); case iStoreSvc::T_FILE: return new DbStoreSvc(); } throw new \InvalidArgumentException('unknown storage type: '.$this->getStorageType()); } protected function updateGalleryPicCount($id) { $db = System::getInstance()->getDB(); // fetches the number of pictures $subselect = $db->select()->columns(['c' => SQLFunction::count()])->from('m_mcms#gallery_picinfos')->where(['gallery_id' => new Parameter()]); // updates the picture count $sql = $db->update()->from('m_mcms#gallery_gallerys')->set(['pic_count'=>$subselect])->where(['id' => new Parameter()]); $db->executeP($sql, [$id, $id]); } public function runIndex(Request $request, Response $response, $activeInstance) { $system = System::getInstance(); $db = $system->getDB(); $param = $system->getRequest()->getParam(); $usr = $system->getUserSvc()->getUser(); $isAdmin = empty($usr) ? false : $this->userHasPriv($usr, $system->getSiteId(), $activeInstance, 'manage'); try { $locale = $system->getActiveLocale(); $strings = $this->loadLocaleStrings($locale, __DIR__); $galleries = ReposSvc::getGalleryPageEntries($system->getSiteId(), $activeInstance, 1, 500); $layout = $this->findLayout($system->getSiteId(), $activeInstance); $template = $this->loadTemplate('mcms.gallery', $system->getTarget('action'), $layout, true); foreach ([ 'title' => 'title', 't_add' => 'create_gal', ] as $param => $langKey) $template->setParam($param, $strings[$langKey]); $template->setParam('admin', $isAdmin); $template->setParam('addlink', _SELF_ . '?mod=' . $activeInstance . '&view=newGallery'); $template->setParam('galleries', $galleries); $template->setParam('gallerylink', function ($ctx) use($activeInstance) { return _SELF_ . '?mod=' . $activeInstance . '&view=gallery&id=' . $ctx['gallery']->id; }); $response->setFragment('CONTENT', $template->getDocument()); } catch(FileNotFoundException $ex) { $response->setFragment('CONTENT', $ex->getMessage() . ' :' . $ex->getContext()); } } public function runNewGallery(Request $request, Response $response, $activeInstance) { $system = System::getInstance(); $db = $system->getDB(); $param = $system->getRequest()->getParam(); $usr = $system->getUserSvc()->getUser(); $isAdmin = empty($usr) ? false : $this->userHasPriv($usr, $system->getSiteId(), $activeInstance, 'manage'); if(!$isAdmin) throw new AccessDeniedException("not privileged"); try { $locale = $system->getActiveLocale(); $strings = $this->loadLocaleStrings($locale, __DIR__); $layout = $this->findLayout($system->getSiteId(), $activeInstance); $template = $this->loadTemplate('mcms.gallery', 'editGallery', $layout, true); $form = $system->createFormBuilder(GalleryModel::clazz()); $form->setTargetLink(_SELF_); $form->setTargetParams(array('mod' => $activeInstance,'view' => 'createGallery')); $template->setParam('title', $strings['title_create']); $template->setParam('t_gal_name', $strings['t_gal_name']); $template->setParam('t_gal_desc', $strings['t_gal_desc']); $template->setParam('t_gal_tags', $strings['t_gal_tags']); $template->setParam('formstart', $form->genStart()); $fields = array( // 'form_parent_id' => 'parent_id', 'form_category' => 'category', 'form_name' => 'name', 'form_info' => 'info', 'form_date' => 'gallerydate', 'form_visible' => 'visible', ); foreach($fields as $formid=>$fieldname) { $this->param2template($formid, $template, $fieldname, $form); $template->setParam($formid, $form->genElement($fieldname)); } // $template->setParam('text_parent_id', 'Parent_id'); $template->setParam('text_category', 'Category'); $template->setParam('text_name', 'Name'); $template->setParam('text_info', 'Info'); $template->setParam('text_date', 'Date'); $template->setParam('text_visible', 'Visible'); $p = $template->getParamParams('submit'); // if(isset($fp['css'])) // $param[Builder::EP_INLINE_CSS] = $fp['css']; $cssClass = false; if(isset($p['cssClass'])) $cssClass = $p['cssClass']; $template->setParam('submit', $form->genSubmit('Create', $cssClass)); $template->setParam('formend', $form->genEnd()); $response->setFragment('CONTENT', $template->getDocument()); } catch(FileNotFoundException $ex) { $response->setFragment('CONTENT', $ex->getMessage() . ' :' . $ex->getContext()); } } public function runCreateGallery(Request $request, Response $response, $activeInstance) { $system = System::getInstance(); $db = $system->getDB(); $param = $system->getRequest()->getParam(); $usr = $system->getUserSvc()->getUser(); $isAdmin = empty($usr) ? false : $this->userHasPriv($usr, $system->getSiteId(), $activeInstance, 'manage'); if(!$isAdmin) throw new AccessDeniedException("not privileged"); $locale = $system->getActiveLocale(); $strings = $this->loadLocaleStrings($locale, __DIR__); $fetcher = $system->createFormFetcher(GalleryModel::clazz()); $object = $fetcher->fetch(); $object->id = NULL; $object->parent_id = NULL; $object->category = 0; $object->pic_count = 0; $object->site_id = $system->getSiteId(); $object->instance = $activeInstance; $object->_created_at = new \DateTime(); $object->_created_by_id = $usr->id; ReposSvc::storeGallery($object); $response->setRedirect($activeInstance, 'index'); // redirect the request } public function runEditGallery(Request $request, Response $response, $activeInstance) { $system = System::getInstance(); $db = $system->getDB(); $param = $system->getRequest()->getParam(); $usr = $system->getUserSvc()->getUser(); $isAdmin = empty($usr) ? false : $this->userHasPriv($usr, $system->getSiteId(), $activeInstance, 'manage'); if(!$isAdmin) throw new AccessDeniedException("not privileged"); try { $locale = $system->getActiveLocale(); $strings = $this->loadLocaleStrings($locale, __DIR__); $layout = $this->findLayout($system->getSiteId(), $activeInstance); $template = $this->loadTemplate('mcms.gallery', $system->getTarget('action'), $layout); $gallery = new GalleryModel(); // TODO: Delete and replace $form = $system->createFormBuilder($gallery); $form->setTargetLink(_SELF_); $form->setTargetParams(array('mod' => $activeInstance,'view' => 'updateGallery')); $template->setParam('formstart', $form->genStart()); $template->setParam('text_parent_id', 'Parent_id'); $template->setParam('form_parent_id', $form->genElement('parent_id')); $template->setParam('text_category', 'Category'); $template->setParam('form_category', $form->genElement('category')); $template->setParam('text_name', 'Name'); $template->setParam('form_name', $form->genElement('name')); $template->setParam('text_info', 'Info'); $template->setParam('form_info', $form->genElement('info')); $template->setParam('text_date', 'Date'); $template->setParam('form_date', $form->genElement('date')); $template->setParam('text_visible', 'Visible'); $template->setParam('form_visible', $form->genElement('visible')); $template->setParam('text_createdById', 'CreatedById'); $template->setParam('form_createdById', $form->genElement('createdById')); $template->setParam('text_picCount', 'PicCount'); $template->setParam('form_picCount', $form->genElement('picCount')); $template->setParam('submit', $form->genSubmit()); $template->setParam('formend', $form->genEnd()); $response->setFragment('CONTENT', $template->getDocument()); } catch(FileNotFoundException $ex) { $response->setFragment('CONTENT', $ex->getMessage() . ' :' . $ex->getContext()); } } public function runSetGalleryIndex(Request $request, Response $response, $activeInstance) { $system = System::getInstance(); $db = $system->getDB(); $param = $system->getRequest()->getParam(); $usr = $system->getUserSvc()->getUser(); $isAdmin = empty($usr) ? false : $this->userHasPriv($usr, $system->getSiteId(), $activeInstance, 'manage'); if(!$isAdmin) throw new AccessDeniedException("not privileged"); $locale = $system->getActiveLocale(); $strings = $this->loadLocaleStrings($locale, __DIR__); /* if ($users->get_admin_level($mod) >= 2) { $gid = (int) $_REQUEST['gid']; $pic = $db->escape_string("{$module['cfg']['datapathw']}/{$gid}/thumb/{$_REQUEST['pic']}"); $db->query("UPDATE `{$mod}_info` SET `pic`='$pic' WHERE `id`='$gid'"); } $pic = urlencode($_REQUEST['pic']); if ($db->lasterror() == '') header("Location: {$_SERVER['PHP_SELF']}?module={$mod}&action=pic&gid={$gid}&pic={$pic}"); else echo $db->lasterror(); $system['dorender'] = false; */ } public function runUpdateGallery(Request $request, Response $response, $activeInstance) { $system = System::getInstance(); $db = $system->getDB(); $param = $system->getRequest()->getParam(); $usr = $system->getUserSvc()->getUser(); $isAdmin = empty($usr) ? false : $this->userHasPriv($usr, $system->getSiteId(), $activeInstance, 'manage'); if(!$isAdmin) throw new AccessDeniedException("not privileged"); $locale = $system->getActiveLocale(); $strings = $this->loadLocaleStrings($locale, __DIR__); $response->setRedirect($activeInstance, 'index'); // redirect the request } public function runDelaskGallery(Request $request, Response $response, $activeInstance) { $system = System::getInstance(); $db = $system->getDB(); $param = $system->getRequest()->getParam(); $usr = $system->getUserSvc()->getUser(); $isAdmin = empty($usr) ? false : $this->userHasPriv($usr, $system->getSiteId(), $activeInstance, 'manage'); if(!$isAdmin) throw new AccessDeniedException("not privileged"); $locale = $system->getActiveLocale(); $strings = $this->loadLocaleStrings($locale, __DIR__); try { $layout = $this->findLayout($system->getSiteId(), $activeInstance); $template = $this->loadTemplate('mcms.gallery', $system->getTarget('action'), $layout); $response->setFragment('CONTENT', $template->getDocument()); } catch(FileNotFoundException $ex) { $response->setFragment('CONTENT', $ex->getMessage() . ' :' . $ex->getContext()); } } public function runRemoveGallery(Request $request, Response $response, $activeInstance) { $system = System::getInstance(); $db = $system->getDB(); $param = $system->getRequest()->getParam(); $usr = $system->getUserSvc()->getUser(); $isAdmin = empty($usr) ? false : $this->userHasPriv($usr, $system->getSiteId(), $activeInstance, 'manage'); if(!$isAdmin) throw new AccessDeniedException("not privileged"); $locale = $system->getActiveLocale(); $strings = $this->loadLocaleStrings($locale, __DIR__); /* if ($users->get_admin_level($mod) >= 2) { $gid = (int) $_REQUEST['gid']; if ($d = scandir("{$module['cfg']['datapath']}/$gid/original")) { unset ($d[0], $d[1]); foreach ($d as $entry) unlink("{$module['cfg']['datapath']}/$gid/original/$entry"); rmdir("{$module['cfg']['datapath']}/$gid/original"); } if ($d = scandir("{$module['cfg']['datapath']}/$gid/thumb")) { unset ($d[0], $d[1]); foreach ($d as $entry) unlink("{$module['cfg']['datapath']}/$gid/thumb/$entry"); rmdir("{$module['cfg']['datapath']}/$gid/thumb"); } if ($d = scandir("{$module['cfg']['datapath']}/$gid/pic")) { unset ($d[0], $d[1]); foreach ($d as $entry) unlink("{$module['cfg']['datapath']}/$gid/pic/$entry"); rmdir("{$module['cfg']['datapath']}/$gid/pic"); } rmdir("{$module['cfg']['datapath']}/$gid"); $db->query("DELETE FROM `{$mod}_info` WHERE `id`='$gid' LIMIT 1"); $error = $db->lasterror(); } if ($error == '') header("Location: {$_SERVER['PHP_SELF']}?module={$mod}"); else echo $error; $system['dorender'] = false; */ $response->setRedirect($activeInstance, 'index'); // redirect the request } public function runGallery(Request $request, Response $response, $activeInstance) { $system = System::getInstance(); $db = $system->getDB(); $param = $system->getRequest()->getParam(); $usr = $system->getUserSvc()->getUser(); $isAdmin = empty($usr) ? false : $this->userHasPriv($usr, $system->getSiteId(), $activeInstance, 'manage'); $locale = $system->getActiveLocale(); $strings = $this->loadLocaleStrings($locale, __DIR__); $id = (int) $param['id']; $this->updateGalleryPicCount($id); $infoTable = $db->escapeTableName('m_mcms#gallery_picinfos'); $siteId = $system->getSiteId(); $gallery = ReposSvc::getGallery($siteId, $activeInstance, $id); if(empty($gallery)) throw new InvalidArgumentException("gallery not found"); $start = 0; $count = 25; $pics = $db->getObjectListP("SELECT * FROM {$infoTable} WHERE gallery_id=?", array( $gallery->id), PicInfo::clazz(), array(), $start, $count); $cachedir = $system->getFileCacheDir($system->getTarget(iSystem::TARGET_INSTANCE), $siteId); $cacheurl = $system->getFileCacheURL($system->getTarget(iSystem::TARGET_INSTANCE), $siteId); $picDatas = array(); $thumbs = array_slice($picDatas,0,5); foreach ($thumbs as $id => $thumb) { // TODO: add caching $fileurl = self::genThumbnail($siteId, $system->getTarget(iSystem::TARGET_INSTANCE), $thumb->id, $thumb->type); $thumb[$id] = $fileurl . '_thumb.jpg'; } $meta = new GalleryMeta(); $meta->setTitle($gallery->name); $meta->setDescription($gallery->info); $meta->setURL(_SELF_ . '?mod=' . $activeInstance . '&view=gallery&id=' . $gallery->id); $meta->setThumbs($thumbs); $meta->setShareable(true); $response->setMetainfo($meta); unset($thumbs, $thumb); foreach($pics as $num=>$pic) { try { $fileurl = self::genThumbnail($siteId, $system->getTarget(iSystem::TARGET_INSTANCE), $pic->id, $pic->type); $picData = new \stdClass(); $picData->url = $fileurl . '_thumb.jpg'; $picData->showlink = _SELF_ . '?mod=' . $activeInstance . '&view=picture&id=' . $pic->id; $picData->dellink = _SELF_ . '?mod=' . $activeInstance . '&view=picDelask&id=' . $pic->id; } catch(FileNotFoundException $e) { $picData = new \stdClass(); $picData->url = './layout/_system_/images/status/16x16/error.png'; $picData->showlink = 'javascript:return false;'; $picData->dellink = _SELF_ . '?mod=' . $activeInstance . '&view=picDelask&id=' . $pic->id; } $picDatas[$num] = $picData; } try { $layout = $this->findLayout($siteId, $activeInstance); $template = $this->loadTemplate('mcms.gallery', $system->getTarget('action'), $layout, true); $template->setParam('title', 'Gallery - ' . $gallery->name); $template->setParam('admin', $isAdmin); //$system->getUserSvc()->userHasPriv($usr,$system->getSiteId(),$activeInstance,'admin')); $template->setParam('pics', $picDatas); $template->setParam('uploadlink', _SELF_ . '?mod=' . $activeInstance . '&view=pictureUpload&id=' . $id); $template->setParam('backlink', _SELF_ . '?mod=' . $activeInstance); foreach ([ 'delete_pic' => 'delete_pic', 'edit_gallery' => 'edit_gallery', 'upload_pic' => 'upload_pic', 'back_gallist' => 'back_gallist', ] as $param => $langKey) $template->setParam($param, $strings[$langKey]); $response->setFragment('CONTENT', $template->getDocument()); } catch(FileNotFoundException $ex) { $response->setFragment('CONTENT', $ex->getMessage() . ' :' . $ex->getContext()); } } public function runPicture(Request $request, Response $response, $activeInstance) { $system = System::getInstance(); $db = $system->getDB(); $param = $system->getRequest()->getParam(); $usr = $system->getUserSvc()->getUser(); $isAdmin = empty($usr) ? false : $this->userHasPriv($usr, $system->getSiteId(), $activeInstance, 'manage'); $locale = $system->getActiveLocale(); $strings = $this->loadLocaleStrings($locale, __DIR__); try { $id = (int) $param['id']; $info = $db->getObjectP('SELECT * FROM "m_mcms#gallery_picinfos" WHERE id=?', array($id), PicInfo::clazz()); $gallery = ReposSvc::getGallery($system->getSiteId(), $activeInstance, $info->gallery_id); if(empty($info) || empty($gallery)) throw new InvalidArgumentException("picture not found"); $meta = new PictureMeta(); $meta->setTitle($gallery->name); $meta->setDescription($gallery->info); $meta->setURL(_SELF_ . '?mod=' . $activeInstance . '&view=picture&id=' . $param['id']); $meta->setImage(_SELF_SERVICE_ . '?mod=' . $activeInstance . '&view=pictureDisplay&id=' . $param['id']); $meta->setShareable(true); $response->setMetainfo($meta); $layout = $this->findLayout($system->getSiteId(), $activeInstance); $template = $this->loadTemplate('mcms.gallery', $system->getTarget('action'), $layout, true); $template->setParam('galleryname', $gallery->name); $template->setParam('admin', $isAdmin); $template->setParam('picurl', _SELF_SERVICE_ . '?mod=' . $activeInstance . '&view=pictureDisplay&id=' . $param['id']); $template->setParam('editurl', _SELF_ . '?mod=' . $activeInstance . '&view=gallery&id=' . $gallery->id); $template->setParam('backurl', _SELF_ . '?mod=' . $activeInstance . '&view=gallery&id=' . $gallery->id); $response->setFragment('CONTENT', $template->getDocument()); } catch(FileNotFoundException $ex) { $response->setFragment('CONTENT', $ex->getMessage() . ' :' . $ex->getContext()); } } public function runPictureDisplay(Request $request, Response $response, $activeInstance) { $system = System::getInstance(); $db = $system->getDB(); $param = $system->getRequest()->getParam(); $usr = $system->getUserSvc()->getUser(); $isAdmin = empty($usr) ? false : $this->userHasPriv($usr, $system->getSiteId(), $activeInstance, 'manage'); $locale = $system->getActiveLocale(); $strings = $this->loadLocaleStrings($locale, __DIR__); $siteId = $system->getSiteId(); try { $id = $param['id']; $info = $db->getObjectP('SELECT * FROM "m_mcms#gallery_picinfos" WHERE id=?', array( $id), PicInfo::clazz()); switch($info->store) { case 'file': $dir = self::verifyFileDirExists($siteId, $activeInstance, $info->gallery_id); $tgtname = $dir . base64_encode($info->filename); $data = file_get_contents($tgtname); break; default: // db $buffer = new Buffer(); $buffer->create(); $db->readBlob('m_mcms#gallery_picdatas', array('pic_id' => $id), 'data', $buffer); $data = $buffer->getBuffer(); $buffer->close(); break; } // header('Content-Description: File Transfer'); // header('Content-Disposition: attachment; filename='.$info->filename); header('Content-Disposition: filename=' . $info->filename); // header('Content-Transfer-Encoding: binary'); // header('Expires: 0'); // header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); // header('Pragma: public'); //header('Content-Length: ' . filesize($data->data)); $picdata = new Image(); $picdata->setImageResource(imagecreatefromstring($data)); $picdata->resize(640, 640, true); switch($info->type) { case IMAGETYPE_JPEG: $response->setType(image_type_to_mime_type($info->type)); $data = $picdata->getAsJPEG(); break; case IMAGETYPE_PNG: $response->setType(image_type_to_mime_type($info->type)); $data = $picdata->getAsPNG(); break; case IMAGETYPE_GIF: $response->setType(image_type_to_mime_type($info->type)); $data = $picdata->getAsGIF(); break; } // $response->setContent($data->data); $response->setContent($data); } catch(FileNotFoundException $ex) { $response->setType('text/plain'); $response->setFragment('CONTENT', $ex->getMessage() . ' :' . $ex->getContext()); } } public static function genThumbnail($siteId, $activeInstance, $picid) { $system = System::getInstance(); $db = $system->getDB(); $info = $db->getObjectP('SELECT * FROM "m_mcms#gallery_picinfos" WHERE id=?', array($picid), PicInfo::clazz()); $cachedir = $system->getFileCacheDir($system->getTarget(iSystem::TARGET_INSTANCE)); $cacheurl = $system->getFileCacheURL($system->getTarget(iSystem::TARGET_INSTANCE)); $filename = $cachedir . $picid; $fileurl = $cacheurl . $picid; $dir = self::verifyFileDirExists($siteId, $activeInstance, $info->gallery_id); $tgtname = $dir . base64_encode($info->filename); echo $info->store; switch($info->store) { case 'file': if(!file_exists($filename)) { $picdata = new Image($tgtname); $picdata->resize(150, 150, true); $picdata->saveAsJPEG($filename . '_thumb.jpg', 75); } break; default: // db if(!file_exists($filename)) { try { $tblName = $db->escapeTableName('m_mcms#gallery_picdatas'); $data = $db->getObjectP("SELECT * FROM {$tblName} WHERE pic_id=?", array( $picid)); $picdata = new Image(); $picdata->setImageResource(imagecreatefromstring($data->data)); $picdata->resize(150, 150, true); $picdata->saveAsJPEG($filename . '_thumb.jpg', 75); } catch(IOException $ex) { var_dump($ex); } } break; } return $fileurl; } public function runCommentAdd(Request $request, Response $response, $activeInstance) { $system = System::getInstance(); $db = $system->getDB(); $param = $system->getRequest()->getParam(); $usr = $system->getUserSvc()->getUser(); $isAdmin = empty($usr) ? false : $this->userHasPriv($usr, $system->getSiteId(), $activeInstance, 'manage'); $locale = $system->getActiveLocale(); $strings = $this->loadLocaleStrings($locale, __DIR__); $response->setRedirect($activeInstance, 'gallery'); // redirect the request } public function runPictureUpload(Request $request, Response $response, $activeInstance) { $system = System::getInstance(); $db = $system->getDB(); $param = $system->getRequest()->getParam(); $usr = $system->getUserSvc()->getUser(); $siteId = $system->getSiteId(); $isAdmin = empty($usr) ? false : $this->userHasPriv($usr, $system->getSiteId(), $activeInstance, 'manage'); if(!$isAdmin) throw new AccessDeniedException("not privileged"); $locale = $system->getActiveLocale(); $strings = $this->loadLocaleStrings($locale, __DIR__); $id = (int) $param['id']; $gallery = ReposSvc::getGallery($siteId, $activeInstance, $id); try { if($this->getStorageType($activeInstance) == 'file') { self::verifyFileDirExists($siteId, $activeInstance, $gallery->id); } $layout = $this->findLayout($system->getSiteId(), $activeInstance); $template = $this->loadTemplate('mcms.gallery', $system->getTarget('action'), $layout, true); $template->setParam('title', 'Upload pictures'); $template->setParam('instance', $activeInstance); $template->setParam('gallery', $gallery); $template->setParam('uploadurl', _SELF_ . '?mod=' . $activeInstance . '&view=picAdd&id=' . $id); $response->setFragment('CONTENT', $template->getDocument()); } catch(FileNotFoundException $ex) { $response->setFragment('CONTENT', $ex->getMessage() . ' :' . $ex->getContext()); } } protected static function verifyFileDirExists($siteId, $activeInstance, $gid) { $dir = System::getInstance()->getFileStoreDir($activeInstance, $siteId, false); $tgtname = $dir->getPath() . $gid . __DS__; if(!is_dir($tgtname)) { ob_start(); $created = mkdir($tgtname, 0777, true); chmod($tgtname, 0777); $st = ob_get_clean(); if(!$created) throw new IllegalStateException($tgtname."\n".$st); } return $tgtname; } /** * Verifies that the file entry exists in the database * * @param string $gid * gallery id * @param string $name * file name * @param string $type * file type * @param string $storage * the storage type of the file * @return PicInfo the picture info object */ protected static function verifyFileInfo($gid, $name, $type, $storage) { $db = System::getInstance()->getDB(); $tblName = $db->escapeTableName('m_mcms#gallery_picinfos'); $fileinfo = $db->getObjectP("SELECT * FROM {$tblName} WHERE gallery_id=? AND filename=?", array( $gid,$name), PicInfo::clazz()); if(!is_object($fileinfo)) { $fileinfo = new PicInfo(); $fileinfo->gallery_id = $gid; $fileinfo->filename = $name; $fileinfo->type = $type; $fileinfo->store = $storage; $fileinfo->views = 0; $db->table('m_mcms#gallery_picinfos')->insert($fileinfo, array('id')); $pid = $db->getInsertId(); $fileinfo = $db->getObjectP("SELECT * FROM {$tblName} WHERE id=?", array($pid), PicInfo::clazz()); } return $fileinfo; } protected function writePicMetaData($pid, $file, $type) { $db = System::getInstance()->getDB(); $metarow = new PicMeta(); $metarow->pic_id = $pid; if($type == IMAGETYPE_JPEG) { $meta = exif_read_data($file); if(is_array($meta)) { foreach($meta as $key=>$section) { if(is_array($section)) { foreach($section as $name=>$val) { $metarow->key = $key . '.' . $name; $metarow->value = $val; $db->table('m_mcms#gallery_picmetas')->insert($metarow); } } else { $metarow->key = $key; $metarow->value = $section; $db->table('m_mcms#gallery_picmetas')->insert($metarow); } } } } } /** * Single file form upload * * @throws Exception on upload errors */ public function runPicAdd(Request $request, Response $response, $activeInstance) { $system = System::getInstance(); $db = $system->getDB(); $param = $system->getRequest()->getParam(); $usr = $system->getUserSvc()->getUser(); $isAdmin = empty($usr) ? false : $this->userHasPriv($usr, $system->getSiteId(), $activeInstance, 'manage'); if(!$isAdmin) throw new AccessDeniedException("not privileged"); $locale = $system->getActiveLocale(); $strings = $this->loadLocaleStrings($locale, __DIR__); $gid = (int) $param['gid']; $siteId = $system->getSiteId(); $file = $_FILES['img']; // get the name of the temporarily saved file (e.g. /tmp/php34634.tmp) $name = $file['name']; $tempPath = $file['tmp_name']; $type = exif_imagetype($tempPath); switch($this->getStorageType($activeInstance)) { case 'file': // file system storage $db->isTransactionSupported() and $db->startTransaction(); $fileinfo = self::verifyFileInfo($gid, $name, $type, 'file'); $tgtname = self::verifyFileDirExists($siteId, $activeInstance, $gid); $tgtfile = $tgtname . __DS__ . base64_encode($fileinfo->filename); if(!move_uploaded_file($tempPath, $tgtfile)) throw new Exception("could not move {$tempPath} to {$tgtfile}"); // update metadata $tblName = $db->escapeTableName('m_mcms#gallery_picmetas'); $db->executeP("DELETE FROM {$tblName} WHERE pic_id=?", array($fileinfo->id)); $this->writePicMetaData($fileinfo->id, $tgtfile, $type); $db->isTransactionSupported() and $db->commit(); break; default: // db $db->isTransactionSupported() and $db->startTransaction(); $fileinfo = self::verifyFileInfo($gid, $name, $type, ''); $db->table('m_mcms#gallery_picdatas')->delete(array('pic_id' => $fileinfo->id)); $db->table('m_mcms#gallery_picdatas')->insert(array( 'pic_id' => $fileinfo->id,'data' => '')); $tblName = $db->escapeTableName('m_mcms#gallery_picdatas'); $blobSrc = new File($tempPath, true); $db->writeBlob('m_mcms#gallery_picdatas', array('pic_id' => $fileinfo->id), 'data', $blobSrc); /*$res = fopen($tempPath,'rb'); while (($data = fread($res,1024*1024))) { $db->executeP("UPDATE {$tblName} SET data=CONCAT(data,?) WHERE pic_id=?",array($data,$fileinfo->id)); } fclose($res);*/ // update metadata (using tempfile, cause "moved" file is in database $tblName = $db->escapeTableName('m_mcms#gallery_picmetas'); $db->executeP("DELETE FROM {$tblName} WHERE pic_id=?", array($fileinfo->id)); $this->writePicMetaData($fileinfo->id, $tempPath, $type); $db->isTransactionSupported() and $db->commit(); break; } $this->updateGalleryPicCount($gid); $response->setRedirectURL(_SELF_DEFAULT_ . '?mod=' . $activeInstance . '&view=gallery&id=' . $gid); } public function runPicAddRPC(Request $request, Response $response, $activeInstance) { $system = System::getInstance(); $db = $system->getDB(); $param = $system->getRequest()->getParam(); $usr = $system->getUserSvc()->getUser(); $isAdmin = empty($usr) ? false : $this->userHasPriv($usr, $system->getSiteId(), $activeInstance, 'manage'); if(!$isAdmin) throw new AccessDeniedException("not privileged"); $locale = $system->getActiveLocale(); $strings = $this->loadLocaleStrings($locale, __DIR__); $siteId = $system->getSiteId(); $gid = (int) $param['gid']; $response->setContent('UNKNOWN'); // on file storage, verify that storage dir exists $tgtname = false; if($this->getStorageType($activeInstance) == 'file') $tgtname = self::verifyFileDirExists($siteId, $activeInstance, $gid); switch($param['uploader']) { case 'jupload': switch($this->getStorageType($activeInstance)) { case 'file': // file system storage break; default: // db if(isset($param['jupart']) || isset($param['jufinal'])) { foreach($_FILES as $tagname=>$fileinfo) { // chunk mode if($param['jupart'] == 1) { $db->isTransactionSupported() and $db->startTransaction(); $name = $fileinfo['name'][0]; $tempPath = $fileinfo['tmp_name'][0]; $fileinfo = new PicInfo(); $fileinfo->gallery_id = $param['id']; $fileinfo->filename = $name; $fileinfo->type = ''; $fileinfo->views = 0; $db->table('m_mcms#gallery_picinfos')->insert($fileinfo, array( 'id')); $pid = $db->getInsertId(); $_SESSION['UPLOAD_ID'] = $pid; $data = new \stdClass(); $data->pic_id = $pid; $data->data = new File($tempPath); $db->table('m_mcms#gallery_picdatas')->insert($data); $db->isTransactionSupported() and $db->commit(); } else { $db->isTransactionSupported() and $db->startTransaction(); $name = $fileinfo['name'][0]; $tempPath = $fileinfo['tmp_name'][0]; // $_SESSION['UPLOAD_ID'] = $pid; // $data = new stdClass(); // $data->pic_id = $pid; // $data->data = new MFFile($tempPath); $content = file_get_contents($tempPath); // $db->table('m_mcms#gallery_picdatas')->insert($data); $db->query("UPDATE `m_mcms#gallery_picdatas` SET data=CONCAT(data," . $db->escapeValue($content) . ") WHERE pic_id=" . $_SESSION['UPLOAD_ID']); $db->isTransactionSupported() and $db->commit(); } } $response->setContent('SUCCESS'); return; } break; } break; case 'html5': switch($this->getStorageType($activeInstance)) { case 'file': // file system storage foreach($_FILES as $tagname=>$fileinfo) { $pic = $fileinfo; $uploaded[$tagname] = $fileinfo['name'][0]; $db->isTransactionSupported() and $db->startTransaction(); // get the name of the temporarily saved file (e.g. /tmp/php34634.tmp) $name = $fileinfo['name']; $tempPath = $fileinfo['tmp_name']; $type = exif_imagetype($tempPath); $fileObj = self::verifyFileInfo($gid, $name, $type, 'file'); // remove the old metadata $tblName = $db->escapeTableName('m_mcms#gallery_picmetas'); $db->executeP("DELETE FROM {$tblName} WHERE pic_id=?", array($fileObj->id)); $this->writePicMetaData($fileObj->id, $tempPath, 'file'); $tgtfile = $tgtname . __DS__ . base64_encode($fileObj->filename); if(!move_uploaded_file($tempPath, $tgtfile)) throw new Exception("could not move {$tempPath} to {$tgtfile}"); $db->isTransactionSupported() and $db->commit(); // The filename and relative path within the Upload-Tree (eg. "/my documents/important/Laura.jpg") // $relativePath = $_POST[$tagname . '_relativePath']; $response->setContent(json_encode(array( 'state' => 'SUCCESS','files' => $uploaded))); } break; default: // db break; } break; default: throw new InvalidArgumentException('no rpc type given'); } $this->updateGalleryPicCount($gid); // $response->setRedirect($activeInstance,'gallery'); // redirect the request } public function runPicDelask(Request $request, Response $response, $activeInstance) { $system = System::getInstance(); $db = $system->getDB(); $param = $system->getRequest()->getParam(); $usr = $system->getUserSvc()->getUser(); $isAdmin = empty($usr) ? false : $this->userHasPriv($usr, $system->getSiteId(), $activeInstance, 'manage'); if(!$isAdmin) throw new AccessDeniedException("not privileged"); $locale = $system->getActiveLocale(); $strings = $this->loadLocaleStrings($locale, __DIR__); try { $layout = $this->findLayout($system->getSiteId(), $activeInstance); $template = $this->loadTemplate($this->getMyId(), $system->getTarget('action'), $layout, true); $template->setParam('title', 'DelPic'); $response->setFragment('CONTENT', $template->getDocument()); } catch(FileNotFoundException $ex) { $response->setFragment('CONTENT', $ex->getMessage() . ' :' . $ex->getContext()); } } public function runPicRemove(Request $request, Response $response, $activeInstance) { $system = System::getInstance(); $db = $system->getDB(); $param = $system->getRequest()->getParam(); $usr = $system->getUserSvc()->getUser(); $isAdmin = empty($usr) ? false : $this->userHasPriv($usr, $system->getSiteId(), $activeInstance, 'manage'); if(!$isAdmin) throw new AccessDeniedException("not privileged"); $locale = $system->getActiveLocale(); $strings = $this->loadLocaleStrings($locale, __DIR__); $site_id = $system->getSiteId(); $cachedir = $system->getFileCacheDir($system->getTarget(iSystem::TARGET_INSTANCE)); $id = $param['id']; $picResult = $db->table('m_mcms#gallery_picinfos')->select(array('id' => $id)); $picInfo = $picResult->fetchObject(); $picResult->close(); $filename = $cachedir . $picInfo->id; if(file_exists($filename . '_thumb.jpg')) unlink($filename . '_thumb.jpg'); $info = $db->getObjectP('SELECT * FROM "m_mcms#gallery_picinfos" WHERE id=?', array($id), PicInfo::clazz()); $tgtname = _DATAPATH_ . __DS__ . 'files' . __DS__ . 'private' . __DS__ . $site_id . __DS__ . $activeInstance . __DS__ . $info->gallery_id . __DS__ . base64_encode($info->filename); if(file_exists($tgtname)) unlink($tgtname); $db->isTransactionSupported() and $db->startTransaction(); $db->table('m_mcms#gallery_piccomments')->delete(array('pic_id' => $id)); $db->table('m_mcms#gallery_picmetas')->delete(array('pic_id' => $id)); $db->table('m_mcms#gallery_picvotes')->delete(array('pic_id' => $id)); $db->table('m_mcms#gallery_picdatas')->delete(array('pic_id' => $id)); $db->table('m_mcms#gallery_picinfos')->delete(array('id' => $id)); $this->updateGalleryPicCount($picInfo->gallery_id); $db->isTransactionSupported() and $db->commit(); $response->setRedirect($activeInstance, 'gallery', array('id' => $picInfo->gallery_id)); // redirect the request } public static function getSearchAreas($siteId, $instanceName) { return NULL; } public static function isSeachAllowedIn($siteId, $instanceName, $area = NULL) { return true; } public static function getSearchAreaName($siteId, $instanceName, $area, $locale = NULL) { return NULL; } public static function search($siteId, $instanceName, $area, $condition) { $db = System::getInstance()->getDB(); $select = $db->select()->from('m_mcms#gallery_gallerys')->where( Condition::newAndSet() ->equalTo('site_id', $siteId) ->equalTo('instance', $instanceName) ->like('name', new Parameter()) ); $result = $db->prepareStatement($select); $result->execute(['%'.$condition.'%']); $data = array(); while ($row = $result->fetchObject()) { $info = new SearchResult(); $info->title = $row->name; $info->info = $row->info; $info->link = _SELF_.'?mod='.$instanceName.'&view=gallery&id='.$row->id; $data[] = $info; } return $data; } }