/** * Install the module */ public function install() { // load install.sql $this->importSQL(dirname(__FILE__) . '/data/install.sql'); // add 'search' as a module $this->addModule('search'); // import locale $this->importLocale(dirname(__FILE__) . '/data/locale.xml'); // general settings $this->setSetting('search', 'overview_num_items', 10); $this->setSetting('search', 'validate_search', true); // module rights $this->setModuleRights(1, 'search'); // action rights $this->setActionRights(1, 'search', 'add_synonym'); $this->setActionRights(1, 'search', 'edit_synonym'); $this->setActionRights(1, 'search', 'delete_synonym'); $this->setActionRights(1, 'search', 'settings'); $this->setActionRights(1, 'search', 'statistics'); $this->setActionRights(1, 'search', 'synonyms'); // set navigation $navigationModulesId = $this->setNavigation(null, 'Modules'); $navigationSearchId = $this->setNavigation($navigationModulesId, 'Search'); $this->setNavigation($navigationSearchId, 'Statistics', 'search/statistics'); $this->setNavigation($navigationSearchId, 'Synonyms', 'search/synonyms', array('search/add_synonym', 'search/edit_synonym')); // settings navigation $navigationSettingsId = $this->setNavigation(null, 'Settings'); $navigationModulesId = $this->setNavigation($navigationSettingsId, 'Modules'); $this->setNavigation($navigationModulesId, 'Search', 'search/settings'); // add extra's $searchId = $this->insertExtra('search', 'block', 'Search', null, 'a:1:{s:3:"url";s:40:"/private/nl/search/statistics?token=true";}', 'N', 2000); $this->insertExtra('search', 'widget', 'SearchForm', 'form', null, 'N', 2001); // loop languages foreach ($this->getLanguages() as $language) { // check if a page for search already exists in this language // @todo refactor this nasty if statement... if (!(bool) $this->getDB()->getVar('SELECT 1 FROM pages AS p INNER JOIN pages_blocks AS b ON b.revision_id = p.revision_id WHERE b.extra_id = ? AND p.language = ? LIMIT 1', array($searchId, $language))) { // insert search $this->insertPage(array('title' => SpoonFilter::ucfirst($this->getLocale('Search', 'core', $language, 'lbl', 'frontend')), 'type' => 'root', 'language' => $language), null, array('extra_id' => $searchId, 'position' => 'main')); } } // activate search on 'pages' $this->searchPages(); // create module cache path if (!SpoonDirectory::exists(PATH_WWW . '/frontend/cache/search')) { SpoonDirectory::create(PATH_WWW . '/frontend/cache/search'); } }
public function testMove() { // setup SpoonDirectory::create($this->path . '/move_org'); // copy SpoonDirectory::move($this->path . '/move_org', $this->path . '/move_dest'); // check if both folders exists $var = (bool) (!SpoonDirectory::exists($this->path . '/move_org') && SpoonDirectory::exists($this->path . '/move_dest')); // assert $this->assertTrue($var); // cleanup SpoonDirectory::delete($this->path . '/move_dest'); }
/** * Scans the directory structure for modules and adds them to the list of optional modules */ private function loadModules() { // fetch modules $tmpModules = SpoonDirectory::getList(PATH_WWW . '/backend/modules', false, null, '/^[a-z0-9_]+$/i'); // loop modules foreach ($tmpModules as $module) { // not required nor hidden if (!in_array($module, $this->modules['required']) && !in_array($module, $this->modules['hidden'])) { // add to the list of optional installs $this->modules['optional'][] = $module; } } }
/** * Write an error/custom message to the log. * * @return void * @param string $message The messages that should be logged. * @param string[optional] $type The type of message you want to log, possible values are: error, custom. */ public static function write($message, $type = 'error') { // milliseconds list($milliseconds) = explode(' ', microtime()); $milliseconds = round($milliseconds * 1000, 0); // redefine var $message = date('Y-m-d H:i:s') . ' ' . $milliseconds . 'ms | ' . $message . "\n"; $type = SpoonFilter::getValue($type, array('error', 'custom'), 'error'); // file $file = self::getPath() . '/' . $type . '.log'; // rename if needed if ((int) @filesize($file) >= self::MAX_FILE_SIZE * 1024) { // start new log file SpoonDirectory::move($file, $file . '.' . date('Ymdhis')); } // write content SpoonFile::setContent($file, $message, true, true); }
/** * Generates the desired image formats based on the source image * * @param string $path The path we write the images to. * @param string $filename The name of the source file. * @param array[optional] $formats The formats of the images to generate based on the source. * @return bool Returns true if every file succeeded */ public static function generateImages($path, $filename, array $formats = null) { // check input if (empty($filename)) { return false; } // create the path up to the source dir if (!\SpoonDirectory::exists($path . '/source')) { \SpoonDirectory::create($path . '/source'); } // source path $pathSource = $path . '/source'; // formats found if (!empty($formats)) { // loop the formats foreach ($formats as $format) { // create the path for this product if (!\SpoonDirectory::exists($path . '/' . $format['size'])) { \SpoonDirectory::create($path . '/' . $format['size']); } // exploded format $explodedFormat = explode('x', $format['size']); // set enlargement/aspect ratio $allowEnlargement = isset($format['allow_enlargement']) ? $format['allow_enlargement'] : true; $forceAspectRatio = isset($format['force_aspect_ratio']) ? $format['force_aspect_ratio'] : true; // get measurements of the source file $sourceDimensions = getimagesize($pathSource . '/' . $filename); // source width is bigger than what it should be $width = $sourceDimensions[0] > $explodedFormat[0] ? $explodedFormat[0] : $sourceDimensions[0]; $height = isset($explodedFormat[1]) && $sourceDimensions[1] > $explodedFormat[1] ? $explodedFormat[1] : $sourceDimensions[1]; // check if height is empty or not if (empty($height)) { $height = null; } // make a thumbnail for the provided format $thumbnail = new \SpoonThumbnail($pathSource . '/' . $filename, $width, $forceAspectRatio ? null : $height); $thumbnail->setAllowEnlargement($allowEnlargement); $thumbnail->setForceOriginalAspectRatio($forceAspectRatio); $success[] = $thumbnail->parseToFile($path . '/' . $format['size'] . '/' . $filename); unset($thumbnail); } } }
/** * Writes a string to a file. * * @return bool True if the content was written, false if not. * @param string $filename The path of the file. * @param string $content The content that should be written. * @param bool[optional] $createFile Should the file be created if it doesn't exists? * @param bool[optional] $append Should the content be appended if the file already exists? * @param int[optional] $chmod Mode that should be applied on the file. */ public static function setContent($filename, $content, $createFile = true, $append = false, $chmod = 0777) { // redefine vars $filename = (string) $filename; $content = (string) $content; $createFile = (bool) $createFile; $append = (bool) $append; // file may not be created, but it doesn't exist either if (!$createFile && self::exists($filename)) { throw new SpoonFileSystemException('The file "' . $filename . '" doesn\'t exist'); } // create directory recursively if needed SpoonDirectory::create(dirname($filename), $chmod, true); // create file & open for writing $handler = $append ? @fopen($filename, 'a') : @fopen($filename, 'w'); // something went wrong if ($handler === false) { throw new SpoonFileSystemException('The file "' . $filename . '" could not be created. Check if PHP has enough permissions.'); } // write to file & close it @fwrite($handler, $content); @fclose($handler); // chmod file @chmod($filename, $chmod); // status return true; }
/** * Get the filetree * * @param string $path The path to get the filetree for. * @param array[optional] $tree An array to hold the results. * @return array */ private static function getTree($path, array $tree = array()) { // paths that should be ignored $ignore = array(BACKEND_CACHE_PATH, BACKEND_CORE_PATH . '/js/ckeditor', BACKEND_CACHE_PATH, BACKEND_CORE_PATH . '/js/ckfinder', FRONTEND_CACHE_PATH); // get modules $modules = BackendModel::getModules(); // get the folder listing $items = SpoonDirectory::getList($path, true, array('.svn', '.git')); // already in the modules? if (substr_count($path, '/modules/') > 0) { // get last chunk $start = strpos($path, '/modules') + 9; $end = strpos($path, '/', $start + 1); if ($end === false) { $moduleName = substr($path, $start); } else { $moduleName = substr($path, $start, $end - $start); } // don't go any deeper if (!in_array($moduleName, $modules)) { return $tree; } } foreach ($items as $item) { // if the path should be ignored, skip it if (in_array($path . '/' . $item, $ignore)) { continue; } // if the item is a directory we should index it also (recursive) if (is_dir($path . '/' . $item)) { $tree = self::getTree($path . '/' . $item, $tree); } else { // if the file has an extension that has to be processed add it into the tree if (in_array(SpoonFile::getExtension($item), array('js', 'php', 'tpl'))) { $tree[] = $path . '/' . $item; } } } return $tree; }
/** * Validate the form */ protected function validateForm() { if ($this->frm->isSubmitted()) { $this->frm->cleanupFields(); // validation $fields = $this->frm->getFields(); // validate the image if ($this->frm->getField('image')->isFilled()) { // image extension and mime type $this->frm->getField('image')->isAllowedExtension(array('jpg', 'png', 'gif', 'jpeg'), BL::err('JPGGIFAndPNGOnly')); $this->frm->getField('image')->isAllowedMimeType(array('image/jpg', 'image/png', 'image/gif', 'image/jpeg'), BL::err('JPGGIFAndPNGOnly')); } $this->meta->validate(); if ($this->frm->isCorrect()) { $item['meta_id'] = $this->meta->save(); $item['company'] = $fields['company']->getValue(); $item['name'] = $fields['name']->getValue(); $item['firstname'] = $fields['firstname']->getValue(); $item['email'] = $fields['email']->getValue(); $item['address'] = $fields['address']->getValue(); $item['zipcode'] = $fields['zipcode']->getValue(); $item['city'] = $fields['city']->getValue(); $item['country'] = $fields['country']->getValue(); $item['phone'] = $fields['phone']->getValue(); $item['fax'] = $fields['fax']->getValue(); $item['website'] = str_replace("http://", "", $fields['website']->getValue()); $item['text'] = $fields['text']->getValue(); $item['zipcodes'] = $fields['zipcodes']->getValue(); $item['remark'] = $fields['remark']->getValue(); //$item['assort'] = $fields['assort']->getValue(); //$item['open'] = $fields['open']->getValue(); //$item['closed'] = $fields['closed']->getValue(); //$item['visit'] = $fields['visit']->getValue(); //$item['size'] = $fields['size']->getValue(); $item['language'] = BL::getWorkingLanguage(); $item['hidden'] = $fields['hidden']->getValue(); if ($item['country'] == '') { $item['country'] = 'BE'; } //--Create url $url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($item['address'] . ', ' . $item['zipcode'] . ' ' . $item['city'] . ', ' . \SpoonLocale::getCountry($item['country'], BL::getWorkingLanguage())) . '&sensor=false'; //--Get lat $geocode = json_decode(\SpoonHTTP::getContent($url)); //--Sleep between the requests sleep(0.05); //--Check result $item['lat'] = isset($geocode->results[0]->geometry->location->lat) ? $geocode->results[0]->geometry->location->lat : null; $item['lng'] = isset($geocode->results[0]->geometry->location->lng) ? $geocode->results[0]->geometry->location->lng : null; // the image path $imagePath = FRONTEND_FILES_PATH . '/Addresses/Images'; // create folders if needed if (!\SpoonDirectory::exists($imagePath . '/Source')) { \SpoonDirectory::create($imagePath . '/Source'); } if (!\SpoonDirectory::exists($imagePath . '/128x128')) { \SpoonDirectory::create($imagePath . '/128x128'); } if (!\SpoonDirectory::exists($imagePath . '/400x300')) { \SpoonDirectory::create($imagePath . '/400x300'); } if (!\SpoonDirectory::exists($imagePath . '/800x')) { \SpoonDirectory::create($imagePath . '/800x'); } // image provided? if ($this->frm->getField('image')->isFilled()) { // build the image name $item['image'] = $this->meta->getURL() . '.' . $this->frm->getField('image')->getExtension(); // upload the image & generate thumbnails $this->frm->getField('image')->generateThumbnails($imagePath, $item['image']); } $item['id'] = BackendAddressesModel::insert($item); //--Add the languages foreach ((array) BackendModel::get('fork.settings')->get('Core', 'languages') as $key => $language) { $itemLanguage = array(); $itemLanguage['id'] = $item['id']; $itemLanguage['language'] = $language; $itemLanguage['text'] = $this->frm->getField('text_' . $language)->getValue(); $itemLanguage['opening_hours'] = $this->frm->getField('opening_hours_' . $language)->getValue(); BackendAddressesModel::insertLanguage($itemLanguage); } if (isset($fields["groups"])) { //--Get all the groups $groups = $fields["groups"]->getValue(); foreach ($groups as $value) { $groupAddress = array(); $groupAddress["address_id"] = $item['id']; $groupAddress["group_id"] = $value; //--Add user to the group BackendAddressesModel::insertAddressToGroup($groupAddress); } } BackendSearchModel::saveIndex($this->getModule(), $item['id'], array('title' => $item['name'], 'text' => $item['name'])); BackendModel::triggerEvent($this->getModule(), 'after_add', $item); $this->redirect(BackendModel::createURLForAction('index') . '&report=added&highlight=row-' . $item['id']); } } }
/** * Fetch the list of available themes * * @return array */ public static function getThemes() { // fetch themes $records = (array) SpoonDirectory::getList(FRONTEND_PATH . '/themes/', false, array('.svn')); // loop and complete the records foreach ($records as $key => $record) { try { // path to info.xml $pathInfoXml = PATH_WWW . '/frontend/themes/' . $record . '/info.xml'; // load info.xml $infoXml = @new SimpleXMLElement($pathInfoXml, LIBXML_NOCDATA, true); // convert xml to useful array $information = BackendExtensionsModel::processThemeXml($infoXml); if (!$information) { throw new BackendException('Invalid info.xml'); } } catch (Exception $e) { // spoon thumbnail value $information['thumbnail'] = 'thumbnail.png'; } // add additional values $records[$record]['value'] = $record; $records[$record]['label'] = $record; $records[$record]['thumbnail'] = '/frontend/themes/' . $record . '/' . $information['thumbnail']; // doublecheck if templates for this theme are installed already $records[$record]['installed'] = self::isThemeInstalled($record); $records[$record]['installable'] = isset($information['templates']); // unset the key unset($records[$key]); } // add core theme $core = array('core' => array()); $core['core']['value'] = 'core'; $core['core']['label'] = BL::lbl('NoTheme'); $core['core']['thumbnail'] = '/frontend/core/layout/images/thumbnail.png'; $core['core']['installed'] = self::isThemeInstalled('core'); $core['core']['installable'] = false; $records = array_merge($core, $records); return (array) $records; }
/** * Validate the form add image * * @return void */ private function validateFormAddImage() { //--Check if the add-image form is submitted if ($this->frmAddImage->isSubmitted()) { //--Clean up fields in the form $this->frmAddImage->cleanupFields(); //--Get image field $filImage = $this->frmAddImage->getField('images'); //--Check if the field is filled in if ($filImage->isFilled()) { //--Image extension and mime type $filImage->isAllowedExtension(array('jpg', 'png', 'gif', 'jpeg'), BL::err('JPGGIFAndPNGOnly')); $filImage->isAllowedMimeType(array('image/jpg', 'image/png', 'image/gif', 'image/jpeg'), BL::err('JPGGIFAndPNGOnly')); //--Check if there are no errors. $strError = $filImage->getErrors(); if ($strError === null) { //--Get the filename $strFilename = BackendGalleriaModel::checkFilename(substr($filImage->getFilename(), 0, 0 - (strlen($filImage->getExtension()) + 1)), $filImage->getExtension()); //--Fill in the item $item = array(); $item["album_id"] = (int) $this->id; $item["user_id"] = BackendAuthentication::getUser()->getUserId(); $item["language"] = BL::getWorkingLanguage(); $item["filename"] = $strFilename; $item["description"] = ""; $item["publish_on"] = BackendModel::getUTCDate(); $item["hidden"] = "N"; $item["sequence"] = BackendGalleriaModel::getMaximumImageSequence($this->id) + 1; //--the image path $imagePath = FRONTEND_FILES_PATH . '/Galleria/Images'; //--create folders if needed if (!\SpoonDirectory::exists($imagePath . '/Source')) { \SpoonDirectory::create($imagePath . '/Source'); } if (!\SpoonDirectory::exists($imagePath . '/128x128')) { \SpoonDirectory::create($imagePath . '/128x128'); } //--image provided? if ($filImage->isFilled()) { //--upload the image & generate thumbnails $filImage->generateThumbnails($imagePath, $item["filename"]); } //--Add item to the database BackendGalleriaModel::insert($item); //--Redirect $this->redirect(BackendModel::createURLForAction('edit_album') . '&id=' . $item["album_id"] . '&report=added-image&var=' . urlencode($item["filename"]) . '#tabImages'); } } } }
/** * Validate the form */ private function validateForm() { if ($this->frm->isSubmitted()) { // cleanup the submitted fields, ignore fields that were added by hackers $this->frm->cleanupFields(); // validate fields $file = $this->frm->getField('file'); $this->frm->getField('title')->isFilled(BL::err('NameIsRequired')); $file->isFilled(BL::err('FieldIsRequired')); // validate the file if ($this->frm->getField('file')->isFilled()) { // file extension $this->frm->getField('file')->isAllowedExtension($this->allowedExtensions, BL::err('FileExtensionNotAllowed')); } // no errors? if ($this->frm->isCorrect()) { // build file record to insert $item['agenda_id'] = $this->item['id']; $item['title'] = $this->frm->getField('title')->getValue(); // the file path $filePath = FRONTEND_FILES_PATH . '/' . $this->getModule() . '/' . $item['agenda_id'] . '/source'; // create folders if needed if (!\SpoonDirectory::exists($filePath)) { \SpoonDirectory::create($filePath); } // file provided? if ($file->isFilled()) { // build the file name $item['filename'] = time() . '.' . $file->getExtension(); // upload the file $file->moveFile($filePath . '/' . $item['filename']); } $item['sequence'] = BackendAgendaModel::getMaximumFilesSequence($item['agenda_id']) + 1; // insert it $item['id'] = BackendAgendaModel::saveFile($item); // trigger event BackendModel::triggerEvent($this->getModule(), 'after_add_file', array('item' => $item)); // everything is saved, so redirect to the overview $this->redirect(BackendModel::createURLForAction('media') . '&agenda_id=' . $item['agenda_id'] . '&report=added&var=' . urlencode($item['title']) . '&highlight=row-' . $item['id'] . '#tabFiles'); } } }
public function tearDown() { // remove directory $directory = realpath(dirname(__FILE__) . '/..') . '/tmp/logging'; SpoonDirectory::delete($directory); }
private static function uploadFile() { //--Check if the file is an image or file if (self::isImage()) { // the image path $path = FRONTEND_FILES_PATH . '/media/images'; } else { // the file path $path = FRONTEND_FILES_PATH . '/media/files'; } // create folders if needed if (!SpoonDirectory::exists($path . '/source')) { SpoonDirectory::create($path . '/source'); } if (!SpoonDirectory::exists($path . '/128x128')) { SpoonDirectory::create($path . '/128x128'); } // build the filename $filename = self::checkFilename(); $item = array(); $item["filename"] = $filename; $item["extension"] = self::$field->getExtension(); $item["created_on"] = FrontendModel::getUTCDate('Y-m-d H:i:s'); $item["filesize"] = self::$field->getFileSize("b"); $data = array(); //--Check if file is an image to specify data if (self::isImage()) { $item["filetype"] = self::$fieldTypeImage; $data["width"] = self::$field->getWidth(); $data["height"] = self::$field->getHeight(); // upload the image & generate thumbnails self::$field->generateThumbnails($path, $filename); } else { $item["filetype"] = self::$fieldTypeFile; // move the source file self::$field->moveFile($path . "/" . $filename); } //--Serialize data $item["data"] = serialize($data); // get db $db = FrontendModel::getDB(true); //--Insert into media return $db->insert("media", $item); }
/** * Saves the image to a file (quality is only used for jpg images). * * @return bool True if the image was saved, false if not. * @param string $filename The path where the image should be saved. * @param int[optional] $quality The quality to use (only applies on jpg-images). * @param int[optional] $chmod Mode that should be applied on the file. */ public function parseToFile($filename, $quality = 100, $chmod = 0666) { // redefine vars $filename = (string) $filename; $quality = (int) $quality; // if (@is_writable(dirname($filename)) !== true) { // does the folder exist? if not, try to create if (!SpoonDirectory::create(dirname($filename))) { if ($this->strict) { throw new SpoonThumbnailException('The destination-path should be writable.'); } return false; } } // get extension $extension = SpoonFile::getExtension($filename); // invalid quality if (!SpoonFilter::isBetween(1, 100, $quality)) { // strict? if ($this->strict) { throw new SpoonThumbnailException('The quality should be between 1 - 100'); } return false; } // invalid extension if (SpoonFilter::getValue($extension, array('gif', 'jpeg', 'jpg', 'png'), '') == '') { if ($this->strict) { throw new SpoonThumbnailException('Only gif, jpeg, jpg or png are allowed types.'); } return false; } // get current dimensions $imageProperties = @getimagesize($this->filename); // validate imageProperties if ($imageProperties === false) { // strict? if ($this->strict) { throw new SpoonThumbnailException('The sourcefile "' . $this->filename . '" could not be found.'); } return false; } // set current dimensions $currentWidth = (int) $imageProperties[0]; $currentHeight = (int) $imageProperties[1]; $currentType = (int) $imageProperties[2]; $currentMime = (string) $imageProperties['mime']; // file is the same? if ($currentType == IMAGETYPE_GIF && $extension == 'gif' || $currentType == IMAGETYPE_JPEG && in_array($extension, array('jpg', 'jpeg')) || $currentType == IMAGETYPE_PNG && $extension == 'png') { if ($currentWidth == $this->width && $currentHeight == $this->height) { return SpoonDirectory::copy($this->filename, $filename, true, true, $chmod); } } // resize image $this->resizeImage($currentWidth, $currentHeight, $currentType, $currentMime); // output to file switch (strtolower($extension)) { case 'gif': $return = @imagegif($this->image, $filename); break; case 'jpeg': case 'jpg': $return = @imagejpeg($this->image, $filename, $quality); break; case 'png': $return = @imagepng($this->image, $filename); break; } // chmod @chmod($filename, $chmod); // cleanup memory @imagedestroy($this->image); // return success return (bool) $return; }
/** * Get an unique URL for a page * * @param string $URL The URL to base on. * @param int[optional] $id The id to ignore. * @param int[optional] $parentId The parent for the page to create an url for. * @param bool[optional] $isAction Is this page an action. * @return string */ public static function getURL($URL, $id = null, $parentId = 0, $isAction = false) { $URL = (string) $URL; $parentIds = array((int) $parentId); // 0, 1, 2, 3, 4 are all toplevels, so we should place them on the same level if ($parentId == 0 || $parentId == 1 || $parentId == 2 || $parentId == 3 || $parentId == 4) { $parentIds = array(0, 1, 2, 3, 4); } // get db $db = BackendModel::getDB(); // no specific id if ($id === null) { // no items? if ((bool) $db->getVar('SELECT 1 FROM pages AS i INNER JOIN meta AS m ON i.meta_id = m.id WHERE i.parent_id IN(' . implode(',', $parentIds) . ') AND i.status = ? AND m.url = ? AND i.language = ? LIMIT 1', array('active', $URL, BL::getWorkingLanguage()))) { // add a number $URL = BackendModel::addNumber($URL); // recall this method, but with a new URL return self::getURL($URL, null, $parentId, $isAction); } } else { // there are items so, call this method again. if ((bool) $db->getVar('SELECT 1 FROM pages AS i INNER JOIN meta AS m ON i.meta_id = m.id WHERE i.parent_id IN(' . implode(',', $parentIds) . ') AND i.status = ? AND m.url = ? AND i.id != ? AND i.language = ? LIMIT 1', array('active', $URL, $id, BL::getWorkingLanguage()))) { // add a number $URL = BackendModel::addNumber($URL); // recall this method, but with a new URL return self::getURL($URL, $id, $parentId, $isAction); } } // get full URL $fullURL = self::getFullUrl($parentId) . '/' . $URL; // get info about parent page $parentPageInfo = self::get($parentId, null, BL::getWorkingLanguage()); // does the parent have extra's? if ($parentPageInfo['has_extra'] == 'Y' && !$isAction) { // set locale FrontendLanguage::setLocale(BackendLanguage::getWorkingLanguage(), true); // get all onsite action $actions = FrontendLanguage::getActions(); // if the new URL conflicts with an action we should rebuild the URL if (in_array($URL, $actions)) { // add a number $URL = BackendModel::addNumber($URL); // recall this method, but with a new URL return self::getURL($URL, $id, $parentId, $isAction); } } // check if folder exists if (SpoonDirectory::exists(PATH_WWW . '/' . $fullURL)) { // add a number $URL = BackendModel::addNumber($URL); // recall this method, but with a new URL return self::getURL($URL, $id, $parentId, $isAction); } // check if it is an appliation if (in_array(trim($fullURL, '/'), array_keys(ApplicationRouting::getRoutes()))) { // add a number $URL = BackendModel::addNumber($URL); // recall this method, but with a new URL return self::getURL($URL, $id, $parentId, $isAction); } // return the unique URL! return $URL; }
/** * Generates the Backend files (module.js, sequence.php) */ protected function generateBackendFiles() { // generate module.js file if ($this->record['multipleImages']) { $this->variables['multiJs'] = BackendModuleMakerGenerator::generateSnippet('Backend/Js/Snippets/Multifiles.base.js', $this->variables); } else { $this->variables['multiJs'] = ''; } $this->variables['do_meta'] = BackendModuleMakerGenerator::generateSnippet('Backend/Js/Snippets/DoMeta.base.js', $this->record['fields'][$this->record['metaField']]); BackendModuleMakerGenerator::generateFile('Backend/Js/Javascript.base.js', $this->variables, $this->backendPath . 'Js/' . $this->record['camel_case_name'] . '.js'); // classes needed to register module specific services BackendModuleMakerGenerator::generateFile('Backend/DependencyInjection/ModuleExtension.base.php', $this->variables, $this->backendPath . 'DependencyInjection/' . $this->record['camel_case_name'] . 'Extension.php'); BackendModuleMakerGenerator::generateFile('Backend/Resources/config/services.base.yml', $this->variables, $this->backendPath . 'Resources/config/services.yml'); unset($this->variables['multiJs'], $this->variables['do_meta']); // add a sequence Ajax action if necessary if ($this->record['useSequence']) { BackendModuleMakerGenerator::generateFile('Backend/Ajax/Sequence.base.php', $this->variables, $this->backendPath . 'Ajax/Sequence.php'); } // add a sequence categories Ajax action if necessary if ($this->record['useCategories']) { BackendModuleMakerGenerator::generateFile('Backend/Ajax/SequenceCategories.base.php', $this->variables, $this->backendPath . 'Ajax/SequenceCategories.php'); } // add an upload Ajax action if necessary if ($this->record['multipleImages']) { BackendModuleMakerGenerator::generateFile('Backend/Ajax/Upload.base.php', $this->variables, $this->backendPath . 'Ajax/Upload.php'); } // if we use the fineuploader, we should copy the needed js and css files if ($this->record['multipleImages']) { \SpoonDirectory::copy(BACKEND_MODULES_PATH . '/ModuleMaker/Layout/Templates/Backend/Js/fineuploader', $this->backendPath . 'Js/fineuploader'); BackendModuleMakerGenerator::generateFile('Backend/Layout/Css/fineuploader.css', null, $this->backendPath . 'Layout/Css/fineuploader.css'); } }
/** * Fetch the list of available themes * * @return array */ public static function getThemes() { // fetch themes $themes = (array) SpoonDirectory::getList(FRONTEND_PATH . '/themes/', false, array('.svn')); // create array $themes = array_combine($themes, $themes); // add core templates $themes = array_merge(array('core' => BL::lbl('NoTheme')), $themes); return $themes; }
/** * Validate the form add image * * @return void */ private function validateForm() { //--Check if the add-image form is submitted if ($this->frm->isSubmitted()) { //--Clean up fields in the form (NOT ALLOWED: fields from plupload like name are deleted) //$this->frm->cleanupFields(); //--Get image field $filImage = $this->frm->getField('images'); //--Check if the field is filled in if ($filImage->isFilled()) { //--Image extension and mime type $filImage->isAllowedExtension(array('jpg', 'png', 'gif', 'jpeg'), BL::err('JPGGIFAndPNGOnly')); $filImage->isAllowedMimeType(array('image/jpg', 'image/png', 'image/gif', 'image/jpeg'), BL::err('JPGGIFAndPNGOnly')); //--Check if there are no errors. $strError = $filImage->getErrors(); if ($strError === null) { //--Get the filename $strFilename = BackendGalleryModel::checkFilename(substr($_REQUEST["name"], 0, 0 - (strlen($filImage->getExtension()) + 1)), $filImage->getExtension()); //--Fill in the item $item = array(); $item["album_id"] = (int) $this->id; $item["user_id"] = BackendAuthentication::getUser()->getUserId(); $item["language"] = BL::getWorkingLanguage(); $item["filename"] = $strFilename; $item["description"] = ""; $item["publish_on"] = BackendModel::getUTCDate(); $item["hidden"] = "N"; $item["sequence"] = BackendGalleryModel::getMaximumImageSequence($this->id) + 1; //--the image path $imagePath = FRONTEND_FILES_PATH . '/Gallery/Images'; //--create folders if needed $resolutions = $this->get('fork.settings')->get("Gallery", 'resolutions', false); foreach ($resolutions as $res) { if (!\SpoonDirectory::exists($imagePath . '/' . $res)) { \SpoonDirectory::create($imagePath . '/' . $res); // Create filesystem object $filesystem = new Filesystem(); // Create var dir for ease of use $dir = $imagePath; // Check if dir exists if ($filesystem->exists($dir . '/Source/')) { // Create Finder object for the files $finderFiles = new Finder(); // Get all the files in the source-dir $files = $finderFiles->files()->in($dir . '/Source/'); // Check if $files is not empty if (!empty($files)) { // Explode the dir-name $chunks = explode("x", $res, 2); // Create folder array $folder = array(); $folder['width'] = $chunks[0] != '' ? (int) $chunks[0] : null; $folder['height'] = $chunks[1] != '' ? (int) $chunks[1] : null; // Loop all the files foreach ($files as $file) { set_time_limit(150); // Check if the file exists if (!$filesystem->exists($imagePath . '/' . $res . '/' . $file->getBasename())) { // generate the thumbnail $thumbnail = new \SpoonThumbnail($dir . '/Source/' . $file->getBasename(), $folder['width'], $folder['height']); $thumbnail->setAllowEnlargement(true); // if the width & height are specified we should ignore the aspect ratio if ($folder['width'] !== null && $folder['height'] !== null) { $thumbnail->setForceOriginalAspectRatio(false); } $thumbnail->parseToFile($imagePath . '/' . $res . '/' . $file->getBasename()); } } } } } } if (!\SpoonDirectory::exists($imagePath . '/Source')) { \SpoonDirectory::create($imagePath . '/Source'); } if (!\SpoonDirectory::exists($imagePath . '/128x128')) { \SpoonDirectory::create($imagePath . '/128x128'); } if (!\SpoonDirectory::exists($imagePath . '/800x')) { \SpoonDirectory::create($imagePath . '/800x'); } if (!\SpoonDirectory::exists($imagePath . '/200x')) { \SpoonDirectory::create($imagePath . '/200x'); } if (!\SpoonDirectory::exists($imagePath . '/400x300')) { \SpoonDirectory::create($imagePath . '/400x300'); } //--image provided? if ($filImage->isFilled()) { //--upload the image & generate thumbnails $filImage->generateThumbnails($imagePath, $item["filename"]); } //--Add item to the database $idInsert = BackendGalleryModel::insert($item); $item['id'] = $idInsert; //--Create html for ajax $tpl = new Template(); $txtDescription = $this->frm->addTextarea("description_" . $idInsert, $item['description']); $item['field_description'] = $txtDescription->setAttribute('style', 'resize: none;')->parse(); //--Parse filename to get name $path_parts = pathinfo(FRONTEND_FILES_PATH . '/Gallery/Images/Source/' . $item['filename']); $item['name'] = $path_parts['filename']; $folders = BackendModel::getThumbnailFolders(FRONTEND_FILES_PATH . '/Gallery/Images', true); foreach ($folders as $folder) { $item['image_' . $folder['dirname']] = $folder['url'] . '/' . $folder['dirname'] . '/' . $item['filename']; } $tpl->assign('images', array($item)); $html = $tpl->getContent(BACKEND_MODULES_PATH . '/Gallery/Layout/Templates/Ajax/Image.tpl'); //Send html (ajax response) $this->output(self::OK, $html, BL::msg('Success')); } } } }
/** * Process the XML and treat it as a blogpost * * @param SimpleXMLElement $xml The XML to process. * @return bool */ private function processXMLAsPost(SimpleXMLElement $xml) { // init var $postID = substr((string) $xml->id, mb_strpos((string) $xml->id, 'post-') + 5); // validate if ($postID == '') { return false; } if ((string) $xml->title == '') { return false; } // build item $item['id'] = (int) BackendBlogModel::getMaximumId() + 1; $item['user_id'] = BackendAuthentication::getUser()->getUserId(); $item['hidden'] = 'N'; $item['allow_comments'] = 'Y'; $item['num_comments'] = 0; $item['status'] = 'active'; $item['language'] = BL::getWorkingLanguage(); $item['publish_on'] = BackendModel::getUTCDate(null, strtotime((string) $xml->published)); $item['created_on'] = BackendModel::getUTCDate(null, strtotime((string) $xml->published)); $item['edited_on'] = BackendModel::getUTCDate(null, strtotime((string) $xml->updated)); $item['category_id'] = 1; $item['title'] = (string) $xml->title; $item['text'] = (string) $xml->content; // set drafts hidden if (strtotime((string) $xml->published) > time()) { $item['hidden'] = 'Y'; $item['status'] = 'draft'; } // build meta $meta = array(); $meta['keywords'] = $item['title']; $meta['keywords_overwrite'] = 'N'; $meta['description'] = $item['title']; $meta['description_overwrite'] = 'N'; $meta['title'] = $item['title']; $meta['title_overwrite'] = 'N'; $meta['url'] = BackendBlogModel::getURL($item['title']); $meta['url_overwrite'] = 'N'; // replace f****d up links $item['text'] = preg_replace('|<a(.*)onblur="(.*)"(.*)>|Ui', '<a$1$3>', $item['text']); // fix images $item['text'] = preg_replace('|<img(.*)border="(.*)"(.*)>|Ui', '<img$1$3>', $item['text']); // remove inline styles $item['text'] = preg_replace('|<(.*)style="(.*)"(.*)>|Ui', '<$1$3>', $item['text']); // whitespace $item['text'] = preg_replace('|\\s{2,}|', ' ', $item['text']); // cleanup $search = array('<br /><br />', '<div><br /></div>', '<div>', '</div>', '<i>', '</i>', '<b>', '</b>', '<p><object', '</object></p>', '<p><p>', '</p></p>', '...'); $replace = array('</p><p>', '</p><p>', '', '', '<em>', '</em>', '<strong>', '</strong>', '<object', '</object>', '<p>', '</p>', '…'); // cleanup $item['text'] = '<p>' . str_replace($search, $replace, SpoonFilter::htmlentitiesDecode($item['text'])) . '</p>'; // get images $matches = array(); preg_match_all('/<img.*src="(.*)".*\\/>/Ui', $item['text'], $matches); // any images? if (isset($matches[1]) && !empty($matches[1])) { // init var $imagesPath = FRONTEND_FILES_PATH . '/userfiles/images/blog'; $imagesURL = FRONTEND_FILES_URL . '/userfiles/images/blog'; // create dir if needed if (!SpoonDirectory::exists($imagesPath)) { SpoonDirectory::create($imagesPath); } // loop matches foreach ($matches[1] as $key => $file) { // get file info $fileInfo = SpoonFile::getInfo($file); // init var $destinationFile = $item['id'] . '_' . $fileInfo['basename']; try { // download SpoonFile::download($file, $imagesPath . '/' . $destinationFile); // replace the old URL with the new one $item['text'] = str_replace($file, $imagesURL . '/' . $destinationFile, $item['text']); } catch (Exception $e) { // ignore } } } // get links $matches = array(); preg_match_all('/<a.*href="(.*)".*\\/>/Ui', $item['text'], $matches); // any images? if (isset($matches[1]) && !empty($matches[1])) { // loop matches foreach ($matches[1] as $key => $file) { // get new link $replaceWith = self::download($file, $item['id']); // should we replace? if ($replaceWith !== false) { // replace the old URL with the new one $item['text'] = str_replace($file, $replaceWith, $item['text']); } } } // insert meta $item['meta_id'] = BackendModel::getDB(true)->insert('meta', $meta); // insert BackendBlogModel::insert($item); // store the post $this->newIds[$postID] = $item['id']; // get tags $tags = array(); // loop categories foreach ($xml->category as $category) { // is this a tag? if so add it if ((string) $category['scheme'] == 'http://www.blogger.com/atom/ns#') { $tags[] = (string) $category['term']; } } // any tags? if (!empty($tags)) { BackendTagsModel::saveTags($item['id'], implode(',', $tags), $this->getModule()); } // return return true; }
/** * Get the widgets * * @return void */ private function getWidgets() { // get all active modules $modules = BackendModel::getModules(true); // loop all modules foreach ($modules as $module) { // you have sufficient rights? if (BackendAuthentication::isAllowedModule($module)) { // build pathName $pathName = BACKEND_MODULES_PATH . '/' . $module; // check if the folder exists if (SpoonDirectory::exists($pathName . '/widgets')) { // get widgets $widgets = (array) SpoonFile::getList($pathName . '/widgets', '/(.*)\\.php/i'); // loop through widgets foreach ($widgets as $widget) { // require the classes require_once $pathName . '/widgets/' . $widget; // init var $widgetName = str_replace('.php', '', $widget); // build classname $className = 'Backend' . SpoonFilter::toCamelCase($module) . 'Widget' . SpoonFilter::toCamelCase($widgetName); // validate if the class exists if (!class_exists($className)) { // throw exception throw new BackendException('The widgetfile is present, but the classname should be: ' . $className . '.'); } else { // add to array $this->widgetInstances[] = array('module' => $module, 'widget' => $widgetName, 'className' => $className); // create reflection class $reflection = new ReflectionClass('Backend' . SpoonFilter::toCamelCase($module) . 'Widget' . SpoonFilter::toCamelCase($widgetName)); // get the offset $offset = strpos($reflection->getDocComment(), '*', 7); // get the first sentence $description = substr($reflection->getDocComment(), 0, $offset); // replacements $description = str_replace('*', '', $description); $description = trim(str_replace('/', '', $description)); } // check if model file exists if (SpoonFile::exists($pathName . '/engine/model.php')) { // require model require_once $pathName . '/engine/model.php'; } // add to array $this->widgets[] = array('label' => SpoonFilter::toCamelCase($widgetName), 'value' => $widgetName, 'description' => $description); } } } } }
/** * Get all data for templates in a format acceptable for SpoonForm::addRadioButton() and SpoonForm::addMultiCheckbox() * * @param string $language The language. * @return array */ public static function getTemplatesForCheckboxes($language) { // load all templates in the 'templates' folder for this language $records = SpoonDirectory::getList(BACKEND_MODULE_PATH . '/templates/' . $language . '/', false, array('.svn')); // stop here if no directories were found if (empty($records)) { return array(); } // loop and complete the records foreach ($records as $key => $record) { // add additional values $records[$record]['language'] = $language; $records[$record]['value'] = $record; $records[$record]['label'] = BL::lbl('Template' . SpoonFilter::toCamelCase($record, array('-', '_'))); // unset the key unset($records[$key]); } return (array) $records; }
/** * Set the module * * We can't rely on the parent setModule function, because a cronjob requires no login * * @param string $module The module to load. */ public function setModule($module) { // does this module exist? $modules = SpoonDirectory::getList(BACKEND_MODULES_PATH); $modules[] = 'core'; if (!in_array($module, $modules)) { // set correct headers SpoonHTTP::setHeadersByCode(403); // throw exception throw new BackendException('Module not allowed.'); } // set property $this->module = $module; }
private function uploadFile() { //--Check if the file is an image or file if ($this->isImage()) { // the image path $path = FRONTEND_FILES_PATH . '/Media/Images'; if (!\SpoonDirectory::exists($path . '/Source')) { \SpoonDirectory::create($path . '/Source'); } } else { // the file path $path = FRONTEND_FILES_PATH . '/Media/Files'; } // create folders if needed // build the filename $filename = $this->checkFilename(); $item = array(); $item["filename"] = $filename; $item["extension"] = $this->field->getExtension(); $item["created_on"] = BackendModel::getUTCDate('Y-m-d H:i:s'); $item["filesize"] = $this->field->getFileSize("b"); $data = array(); //--Check if file is an image to specify data if ($this->isImage()) { $item["filetype"] = $this->fieldTypeImage; //--Put file on disk $this->field->moveFile($path . "/Source/" . $filename); // create folders if needed if (!\SpoonDirectory::exists($path . '/128x128')) { \SpoonDirectory::create($path . '/128x128'); } //--Create all tumbs/resizes of file $thumbnail = new \SpoonThumbnail($path . "/Source/" . $filename); $thumbnail->setAllowEnlargement(true); \Common\Core\Model::generateThumbnails($path, $path . '/Source/' . $filename); } else { $item["filetype"] = $this->fieldTypeFile; // move the source file $this->field->moveFile($path . "/" . $filename); } //--Serialize data $item["data"] = serialize($data); //--Store item so we can access it $this->item = $item; //--Insert into media return BackendModel::getContainer()->get('database')->insert("media", $item); }
/** * Get the template record * * @param string $language The language. * @param string $name The name of the template. * @return array */ public static function getTemplate($language, $name) { // set the path to the template folders for this language $path = PATH_WWW . '/backend/modules/mailmotor/templates/' . $language; // load all templates in the 'templates' folder for this language $templates = SpoonDirectory::getList($path, false, array('.svn')); // stop here if no directories were found if (empty($templates) || !in_array($name, $templates)) { return array(); } // load all templates in the 'templates' folder for this language if (!SpoonFile::exists($path . '/' . $name . '/template.tpl')) { throw new SpoonException('The template folder "' . $name . '" exists, but no template.tpl file was found. Please create one.'); } if (!SpoonFile::exists($path . '/' . $name . '/css/screen.css')) { throw new SpoonException('The template folder "' . $name . '" exists, but no screen.css file was found. Please create one in a subfolder "css".'); } // set template data $record = array(); $record['name'] = $name; $record['language'] = $language; $record['path_content'] = $path . '/' . $name . '/template.tpl'; $record['path_css'] = $path . '/' . $name . '/css/screen.css'; $record['url_css'] = SITE_URL . '/backend/modules/mailmotor/templates/' . $language . '/' . $name . '/css/screen.css'; // check if the template file actually exists if (SpoonFile::exists($record['path_content'])) { $record['content'] = SpoonFile::getContent($record['path_content']); } if (SpoonFile::exists($record['path_css'])) { $record['css'] = SpoonFile::getContent($record['path_css']); } return $record; }
/** * Attemps to move the uploaded file to the new location. * * @return bool * @param string $path The path whereto the file will be moved. * @param int[optional] $chmod The octal value to use for chmod. */ public function moveFile($path, $chmod = 0755) { // create missing directories if (!file_exists(dirname($path))) { SpoonDirectory::create(dirname($path)); } // move the file $return = @move_uploaded_file($_FILES[$this->attributes['name']]['tmp_name'], (string) $path); // chmod file @chmod($path, $chmod); // return move file status return $return; }
/** * Validate the form */ private function validateForm() { // is the form submitted? if ($this->frm->isSubmitted()) { // get the status $status = SpoonFilter::getPostValue('status', array('active', 'draft'), 'active'); // cleanup the submitted fields, ignore fields that were added by hackers $this->frm->cleanupFields(); // validate fields $this->frm->getField('title')->isFilled(BL::err('TitleIsRequired')); $this->frm->getField('text')->isFilled(BL::err('FieldIsRequired')); $this->frm->getField('publish_on_date')->isValid(BL::err('DateIsInvalid')); $this->frm->getField('publish_on_time')->isValid(BL::err('TimeIsInvalid')); $this->frm->getField('category_id')->isFilled(BL::err('FieldIsRequired')); if ($this->frm->getField('category_id')->getValue() == 'new_category') { $this->frm->getField('category_id')->addError(BL::err('FieldIsRequired')); } if ($this->imageIsAllowed) { // validate the image if ($this->frm->getField('image')->isFilled()) { // image extension and mime type $this->frm->getField('image')->isAllowedExtension(array('jpg', 'png', 'gif', 'jpeg'), BL::err('JPGGIFAndPNGOnly')); $this->frm->getField('image')->isAllowedMimeType(array('image/jpg', 'image/png', 'image/gif', 'image/jpeg'), BL::err('JPGGIFAndPNGOnly')); } } // validate meta $this->meta->validate(); if ($this->frm->isCorrect()) { // build item $item['id'] = (int) BackendBlogModel::getMaximumId() + 1; $item['meta_id'] = $this->meta->save(); $item['category_id'] = (int) $this->frm->getField('category_id')->getValue(); $item['user_id'] = $this->frm->getField('user_id')->getValue(); $item['language'] = BL::getWorkingLanguage(); $item['title'] = $this->frm->getField('title')->getValue(); $item['introduction'] = $this->frm->getField('introduction')->getValue(); $item['text'] = $this->frm->getField('text')->getValue(); $item['publish_on'] = BackendModel::getUTCDate(null, BackendModel::getUTCTimestamp($this->frm->getField('publish_on_date'), $this->frm->getField('publish_on_time'))); $item['created_on'] = BackendModel::getUTCDate(); $item['edited_on'] = $item['created_on']; $item['hidden'] = $this->frm->getField('hidden')->getValue(); $item['allow_comments'] = $this->frm->getField('allow_comments')->getChecked() ? 'Y' : 'N'; $item['num_comments'] = 0; $item['status'] = $status; if ($this->imageIsAllowed) { // the image path $imagePath = FRONTEND_FILES_PATH . '/blog/images'; // create folders if needed if (!SpoonDirectory::exists($imagePath . '/source')) { SpoonDirectory::create($imagePath . '/source'); } if (!SpoonDirectory::exists($imagePath . '/128x128')) { SpoonDirectory::create($imagePath . '/128x128'); } // image provided? if ($this->frm->getField('image')->isFilled()) { // build the image name $item['image'] = $this->meta->getURL() . '.' . $this->frm->getField('image')->getExtension(); // upload the image & generate thumbnails $this->frm->getField('image')->generateThumbnails($imagePath, $item['image']); } } // insert the item $item['revision_id'] = BackendBlogModel::insert($item); // trigger event BackendModel::triggerEvent($this->getModule(), 'after_add', array('item' => $item)); // save the tags BackendTagsModel::saveTags($item['id'], $this->frm->getField('tags')->getValue(), $this->URL->getModule()); // active if ($item['status'] == 'active') { // add search index BackendSearchModel::saveIndex($this->getModule(), $item['id'], array('title' => $item['title'], 'text' => $item['text'])); // ping if (BackendModel::getModuleSetting($this->getModule(), 'ping_services', false)) { BackendModel::ping(SITE_URL . BackendModel::getURLForBlock('blog', 'detail') . '/' . $this->meta->getURL()); } // everything is saved, so redirect to the overview $this->redirect(BackendModel::createURLForAction('index') . '&report=added&var=' . urlencode($item['title']) . '&highlight=row-' . $item['revision_id']); } elseif ($item['status'] == 'draft') { // everything is saved, so redirect to the edit action $this->redirect(BackendModel::createURLForAction('edit') . '&report=saved-as-draft&var=' . urlencode($item['title']) . '&id=' . $item['id'] . '&draft=' . $item['revision_id'] . '&highlight=row-' . $item['revision_id']); } } } }
/** * Delete the cached data */ private function deleteCachedData() { // init some vars $foldersToLoop = array('/backend/cache', '/frontend/cache'); $foldersToIgnore = array('/backend/cache/navigation'); $filesToIgnore = array('.gitignore'); $filesToDelete = array(); // loop folders foreach ($foldersToLoop as $folder) { // get folderlisting $subfolders = (array) SpoonDirectory::getList(PATH_WWW . $folder, false, array('.svn', '.gitignore')); // loop folders foreach ($subfolders as $subfolder) { // not in ignore list? if (!in_array($folder . '/' . $subfolder, $foldersToIgnore)) { // get the filelisting $files = (array) SpoonFile::getList(PATH_WWW . $folder . '/' . $subfolder); // loop the files foreach ($files as $file) { if (!in_array($file, $filesToIgnore)) { $filesToDelete[] = PATH_WWW . $folder . '/' . $subfolder . '/' . $file; } } } } } // delete cached files if (!empty($filesToDelete)) { // loop files and delete them foreach ($filesToDelete as $file) { SpoonFile::delete($file); } } }
/** * Get the thumbnail folders * * @param string $path The path * @param bool[optional] $includeSource Should the source-folder be included in the return-array. * @return array */ public static function getThumbnailFolders($path, $includeSource = false) { $folders = SpoonDirectory::getList((string) $path, false, null, '/^([0-9]*)x([0-9]*)$/'); if ($includeSource && SpoonDirectory::exists($path . '/source')) { $folders[] = 'source'; } $return = array(); foreach ($folders as $folder) { $item = array(); $chunks = explode('x', $folder, 2); // skip invalid items if (count($chunks) != 2 && !$includeSource) { continue; } $item['dirname'] = $folder; $item['path'] = $path . '/' . $folder; if (substr($path, 0, strlen(PATH_WWW)) == PATH_WWW) { $item['url'] = substr($item['path'], strlen(PATH_WWW)); } if ($folder == 'source') { $item['width'] = null; $item['height'] = null; } else { $item['width'] = $chunks[0] != '' ? (int) $chunks[0] : null; $item['height'] = $chunks[1] != '' ? (int) $chunks[1] : null; } $return[] = $item; } return $return; }
/** * Install the module. */ public function install() { // load install.sql $this->importSQL(dirname(__FILE__) . '/Data/install.sql'); // add 'profiles' as a module $this->addModule('Profiles'); // import locale $this->importLocale(dirname(__FILE__) . '/Data/locale.xml'); // general settings $this->setSetting('Profiles', 'allow_gravatar', true); // add folders \SpoonDirectory::create(PATH_WWW . '/src/Frontend/Files/Profiles/avatars/source/'); \SpoonDirectory::create(PATH_WWW . '/src/Frontend/Files/Profiles/avatars/240x240/'); \SpoonDirectory::create(PATH_WWW . '/src/Frontend/Files/Profiles/avatars/64x64/'); \SpoonDirectory::create(PATH_WWW . '/src/Frontend/Files/Profiles/avatars/32x32/'); // module rights $this->setModuleRights(1, 'Profiles'); // action rights $this->setActionRights(1, 'Profiles', 'Add'); $this->setActionRights(1, 'Profiles', 'AddGroup'); $this->setActionRights(1, 'Profiles', 'AddProfileGroup'); $this->setActionRights(1, 'Profiles', 'Block'); $this->setActionRights(1, 'Profiles', 'DeleteGroup'); $this->setActionRights(1, 'Profiles', 'DeleteProfileGroup'); $this->setActionRights(1, 'Profiles', 'Delete'); $this->setActionRights(1, 'Profiles', 'EditGroup'); $this->setActionRights(1, 'Profiles', 'EditProfileGroup'); $this->setActionRights(1, 'Profiles', 'Edit'); $this->setActionRights(1, 'Profiles', 'ExportTemplate'); $this->setActionRights(1, 'Profiles', 'Groups'); $this->setActionRights(1, 'Profiles', 'Import'); $this->setActionRights(1, 'Profiles', 'Index'); $this->setActionRights(1, 'Profiles', 'MassAction'); // set navigation $navigationModulesId = $this->setNavigation(null, 'Modules'); $navigationProfilesId = $this->setNavigation($navigationModulesId, 'Profiles'); $this->setNavigation($navigationProfilesId, 'Overview', 'profiles/index', array('profiles/add', 'profiles/edit', 'profiles/add_profile_group', 'profiles/edit_profile_group', 'profiles/import')); $this->setNavigation($navigationProfilesId, 'Groups', 'profiles/groups', array('profiles/add_group', 'profiles/edit_group')); // add extra $activateId = $this->insertExtra('Profiles', 'block', 'Activate', 'Activate', null, 'N', 5000); $forgotPasswordId = $this->insertExtra('Profiles', 'block', 'ForgotPassword', 'ForgotPassword', null, 'N', 5001); $indexId = $this->insertExtra('Profiles', 'block', 'Dashboard', null, null, 'N', 5002); $loginId = $this->insertExtra('Profiles', 'block', 'Login', 'Login', null, 'N', 5003); $logoutId = $this->insertExtra('Profiles', 'block', 'Logout', 'Logout', null, 'N', 5004); $changeEmailId = $this->insertExtra('Profiles', 'block', 'ChangeEmail', 'ChangeEmail', null, 'N', 5005); $changePasswordId = $this->insertExtra('Profiles', 'block', 'ChangePassword', 'ChangePassword', null, 'N', 5006); $settingsId = $this->insertExtra('Profiles', 'block', 'Settings', 'Settings', null, 'N', 5007); $registerId = $this->insertExtra('Profiles', 'block', 'Register', 'Register', null, 'N', 5008); $resetPasswordId = $this->insertExtra('Profiles', 'block', 'ResetPassword', 'ResetPassword', null, 'N', 5008); $resendActivationId = $this->insertExtra('Profiles', 'block', 'ResendActivation', 'ResendActivation', null, 'N', 5009); $this->insertExtra('Profiles', 'widget', 'LoginBox', 'LoginBox', null, 'N', 5010); $this->insertExtra('Profiles', 'widget', 'LoginLink', 'LoginLink', null, 'N', 5011); // get search widget id $searchId = (int) $this->getDB()->getVar('SELECT id FROM modules_extras WHERE module = ? AND action = ?', array('search', 'form')); // loop languages foreach ($this->getLanguages() as $language) { // only add pages if profiles isn't linked anywhere // @todo refactor me, syntax sucks atm if (!(bool) $this->getDB()->getVar('SELECT 1 FROM pages AS p INNER JOIN pages_blocks AS b ON b.revision_id = p.revision_id INNER JOIN modules_extras AS e ON e.id = b.extra_id WHERE e.module = ? AND p.language = ? LIMIT 1', array('Profiles', $language))) { // activate page $this->insertPage(array('title' => 'Activate', 'type' => 'root', 'language' => $language), null, array('extra_id' => $activateId, 'position' => 'main'), array('extra_id' => $searchId, 'position' => 'top')); // forgot password page $this->insertPage(array('title' => 'Forgot password', 'type' => 'root', 'language' => $language), null, array('extra_id' => $forgotPasswordId, 'position' => 'main'), array('extra_id' => $searchId, 'position' => 'top')); // reset password page $this->insertPage(array('title' => 'Reset password', 'type' => 'root', 'language' => $language), null, array('extra_id' => $resetPasswordId, 'position' => 'main'), array('extra_id' => $searchId, 'position' => 'top')); // resend activation email page $this->insertPage(array('title' => 'Resend activation e-mail', 'type' => 'root', 'language' => $language), null, array('extra_id' => $resendActivationId, 'position' => 'main'), array('extra_id' => $searchId, 'position' => 'top')); // login page $this->insertPage(array('title' => 'Login', 'type' => 'root', 'language' => $language), null, array('extra_id' => $loginId, 'position' => 'main'), array('extra_id' => $searchId, 'position' => 'top')); // register page $this->insertPage(array('title' => 'Register', 'type' => 'root', 'language' => $language), null, array('extra_id' => $registerId, 'position' => 'main'), array('extra_id' => $searchId, 'position' => 'top')); // logout page $this->insertPage(array('title' => 'Logout', 'type' => 'root', 'language' => $language), null, array('extra_id' => $logoutId, 'position' => 'main'), array('extra_id' => $searchId, 'position' => 'top')); // index page $indexPageId = $this->insertPage(array('title' => 'Profile', 'type' => 'root', 'language' => $language), null, array('extra_id' => $indexId, 'position' => 'main'), array('extra_id' => $searchId, 'position' => 'top')); // settings page $this->insertPage(array('title' => 'Profile settings', 'parent_id' => $indexPageId, 'language' => $language), null, array('extra_id' => $settingsId, 'position' => 'main'), array('extra_id' => $searchId, 'position' => 'top')); // change email page $this->insertPage(array('title' => 'Change email', 'parent_id' => $indexPageId, 'language' => $language), null, array('extra_id' => $changeEmailId, 'position' => 'main'), array('extra_id' => $searchId, 'position' => 'top')); // change password page $this->insertPage(array('title' => 'Change password', 'parent_id' => $indexPageId, 'language' => $language), null, array('extra_id' => $changePasswordId, 'position' => 'main'), array('extra_id' => $searchId, 'position' => 'top')); } } }
/** * Generate thumbnails based on the folders in the path * Use * - 128x128 as foldername to generate an image that where the width will be 128px and the height will be 128px * - 128x as foldername to generate an image that where the width will be 128px, the height will be calculated based on the aspect ratio. * - x128 as foldername to generate an image that where the width will be 128px, the height will be calculated based on the aspect ratio. * * @param string $path * @param string $filename */ public function generateThumbnails($path, $filename) { // create folder if needed if (!SpoonDirectory::exists($path . '/source')) { SpoonDirectory::create($path . '/source'); } // move the source file $this->moveFile($path . '/source/' . $filename); // generate the thumbnails FrontendModel::generateThumbnails($path, $path . '/source/' . $filename); }