/** * Output a CSV-file as a download * * @param string $filename The name of the file. * @param array $array The array to convert. * @param array $columns The column names you want to use. * @param array $excludeColumns The columns you want to exclude. */ public static function outputCSV($filename, array $array, array $columns = null, array $excludeColumns = null) { // get settings $splitCharacter = Authentication::getUser()->getSetting('csv_split_character'); $lineEnding = Authentication::getUser()->getSetting('csv_line_ending'); // reformat if ($lineEnding == '\\n') { $lineEnding = "\n"; } if ($lineEnding == '\\r\\n') { $lineEnding = "\r\n"; } // convert into CSV $csv = \SpoonFileCSV::arrayToString($array, $columns, $excludeColumns, $splitCharacter, '"', $lineEnding); // set headers for download $charset = BackendModel::getContainer()->getParameter('kernel.charset'); $headers[] = 'Content-type: application/csv; charset=' . $charset; $headers[] = 'Content-Disposition: attachment; filename="' . $filename . '"'; $headers[] = 'Content-Length: ' . strlen($csv); $headers[] = 'Pragma: no-cache'; // overwrite the headers \SpoonHTTP::setHeaders($headers); // output the CSV echo $csv; exit; }
/** * Create the XML based on the locale items. */ public function getContent() { $charset = BackendModel::getContainer()->getParameter('kernel.charset'); // create XML $xmlOutput = BackendLocaleModel::createXMLForExport($this->locale); return new Response($xmlOutput, Response::HTTP_OK, ['Content-Disposition' => 'attachment; filename="locale_' . BackendModel::getUTCDate('d-m-Y') . '.xml"', 'Content-Type' => 'application/octet-stream;charset=' . $charset, 'Content-Length' => '' . mb_strlen($xmlOutput)]); }
/** * Generate an url, using the predefined callback. * * @param string $url The base-url to start from. * @param string $class The Fully Qualified Class Name or service name * @param string $method The method that needs to be called * @param array $parameters The parameters for the callback * * @throws Exception When the function does not exist * * @return string */ public function generateURL($url, $class, $method, array $parameters = []) { // check if the class is a service if (Model::getContainer()->has($class)) { $class = Model::getContainer()->get($class); } // validate (check if the function exists) if (!is_callable([$class, $method])) { throw new Exception('The callback-method doesn\'t exist.'); } // when using ->getValue() in SpoonFormText fields the function is using htmlentities(), // so we must decode it again first! $url = SpoonFilter::htmlentitiesDecode($url); $actualParameters = []; // build parameters for use in the callback $actualParameters[] = Uri::getUrl($url); // add parameters set by user if (!empty($parameters)) { foreach ($parameters as $parameter) { $actualParameters[] = $parameter; } } // get the real url return call_user_func_array([$class, $method], $actualParameters); }
/** * Execute the action */ public function execute() { parent::execute(); $isGod = BackendAuthentication::getUser()->isGod(); // get possible languages if ($isGod) { $possibleLanguages = array_unique(array_merge(BL::getWorkingLanguages(), BL::getInterfaceLanguages())); } else { $possibleLanguages = BL::getWorkingLanguages(); } // get parameters $language = \SpoonFilter::getPostValue('language', array_keys($possibleLanguages), null, 'string'); $module = \SpoonFilter::getPostValue('module', BackendModel::getModules(), null, 'string'); $name = \SpoonFilter::getPostValue('name', null, null, 'string'); $type = \SpoonFilter::getPostValue('type', BackendModel::getContainer()->get('database')->getEnumValues('locale', 'type'), null, 'string'); $application = \SpoonFilter::getPostValue('application', array('Backend', 'Frontend'), null, 'string'); $value = \SpoonFilter::getPostValue('value', null, null, 'string'); // validate values if (trim($value) == '' || $language == '' || $module == '' || $type == '' || $application == '' || $application == 'Frontend' && $module != 'Core') { $error = BL::err('InvalidValue'); } // in case this is a 'act' type, there are special rules concerning possible values if ($type == 'act' && !isset($error)) { if (urlencode($value) != CommonUri::getUrl($value)) { $error = BL::err('InvalidActionValue', $this->getModule()); } } // no error? if (!isset($error)) { // build item $item['language'] = $language; $item['module'] = $module; $item['name'] = $name; $item['type'] = $type; $item['application'] = $application; $item['value'] = $value; $item['edited_on'] = BackendModel::getUTCDate(); $item['user_id'] = BackendAuthentication::getUser()->getUserId(); // does the translation exist? if (BackendLocaleModel::existsByName($name, $type, $module, $language, $application)) { // add the id to the item $item['id'] = (int) BackendLocaleModel::getByName($name, $type, $module, $language, $application); // update in db BackendLocaleModel::update($item); } else { // insert in db BackendLocaleModel::insert($item); } // output OK $this->output(self::OK); } else { $this->output(self::ERROR, null, $error); } }
/** * Get the comments * * @param string $status The type of comments to get. Possible values are: published, moderation, spam. * @param int $limit The maximum number of items to retrieve. * @param int $offset The offset. * * @return array */ public static function commentsGet($status = null, $limit = 30, $offset = 0) { // authorize if (BaseAPI::isAuthorized() && BaseAPI::isValidRequestMethod('GET')) { // redefine $limit = (int) $limit; // validate if ($limit > 10000) { return BaseAPI::output(BaseAPI::ERROR, array('message' => 'Limit can\'t be larger than 10000.')); } // get comments $comments = (array) BackendModel::getContainer()->get('database')->getRecords('SELECT i.id, UNIX_TIMESTAMP(i.created_on) AS created_on, i.author, i.email, i.website, i.text, i.type, i.status, p.id AS post_id, p.title AS post_title, m.url AS post_url, p.language AS post_language FROM blog_comments AS i INNER JOIN blog_posts AS p ON i.post_id = p.id AND i.language = p.language INNER JOIN meta AS m ON p.meta_id = m.id WHERE p.status = ? GROUP BY i.id ORDER BY i.id DESC LIMIT ?, ?', array('active', (int) $offset, $limit)); $totalCount = (int) BackendModel::getContainer()->get('database')->getVar('SELECT COUNT(i.id) FROM blog_comments AS i INNER JOIN blog_posts AS p ON i.post_id = p.id AND i.language = p.language INNER JOIN meta AS m ON p.meta_id = m.id WHERE p.status = ?', array('active')); $return = array('comments' => null, 'total_count' => $totalCount); // build return array foreach ($comments as $row) { // create array $item['comment'] = array(); // article meta data $item['comment']['article']['@attributes']['id'] = $row['post_id']; $item['comment']['article']['@attributes']['lang'] = $row['post_language']; $item['comment']['article']['title'] = $row['post_title']; $item['comment']['article']['url'] = SITE_URL . BackendModel::getURLForBlock('Blog', 'Detail', $row['post_language']) . '/' . $row['post_url']; // set attributes $item['comment']['@attributes']['id'] = $row['id']; $item['comment']['@attributes']['created_on'] = date('c', $row['created_on']); $item['comment']['@attributes']['status'] = $row['status']; // set content $item['comment']['text'] = $row['text']; $item['comment']['url'] = $item['comment']['article']['url'] . '#comment-' . $row['id']; // author data $item['comment']['author']['@attributes']['email'] = $row['email']; $item['comment']['author']['name'] = $row['author']; $item['comment']['author']['website'] = $row['website']; // add $return['comments'][] = $item; } return $return; } }
/** * Create the XML based on the locale items. */ private function createXML() { $charset = BackendModel::getContainer()->getParameter('kernel.charset'); // create XML $xmlOutput = BackendLocaleModel::createXMLForExport($this->locale); // xml headers header('Content-Disposition: attachment; filename="locale_' . BackendModel::getUTCDate('d-m-Y') . '.xml"'); header('Content-Type: application/octet-stream;charset=' . $charset); header('Content-Length: ' . strlen($xmlOutput)); // output XML echo $xmlOutput; exit; }
/** * Output a CSV-file as a download * * @param string $filename The name of the file. * @param array $array The array to convert. * @param array $columns The column names you want to use. * @param array $excludeColumns The columns you want to exclude. */ public static function outputCSV($filename, array $array, array $columns = null, array $excludeColumns = null) { // get settings $splitCharacter = Authentication::getUser()->getSetting('csv_split_character'); $lineEnding = Authentication::getUser()->getSetting('csv_line_ending'); // reformat if ($lineEnding == '\\n') { $lineEnding = "\n"; } if ($lineEnding == '\\r\\n') { $lineEnding = "\r\n"; } // convert into CSV $csv = \SpoonFileCSV::arrayToString($array, $columns, $excludeColumns, $splitCharacter, '"', $lineEnding); // set headers for download $charset = BackendModel::getContainer()->getParameter('kernel.charset'); throw new RedirectException('Return the csv data', new Response($csv, Response::HTTP_OK, ['Content-type' => 'application/csv; charset=' . $charset, 'Content-Disposition' => 'attachment; filename="' . $filename . '"', 'Content-Length' => mb_strlen($csv), 'Pragma' => 'no-cache'])); }
/** * @param string $name Name of the form. * @param string $action The action (URL) whereto the form will be submitted, if not provided it * will be autogenerated. * @param string $method The method to use when submitting the form, default is POST. * @param bool $useToken Should we automagically add a formtoken? * @param bool $useGlobalError Should we automagically show a global error? */ public function __construct($name = null, $action = null, $method = 'post', $useToken = true, $useGlobalError = true) { if (BackendModel::getContainer()->has('url')) { $this->URL = BackendModel::getContainer()->get('url'); } if (BackendModel::getContainer()->has('header')) { $this->header = BackendModel::getContainer()->get('header'); } $this->useGlobalError = (bool) $useGlobalError; // build a name if there wasn't one provided $name = $name === null ? \SpoonFilter::toCamelCase($this->URL->getModule() . '_' . $this->URL->getAction(), '_', true) : (string) $name; // build the action if it wasn't provided $action = $action === null ? '/' . $this->URL->getQueryString() : (string) $action; // call the real form-class parent::__construct($name, $action, $method, $useToken); // add default classes $this->setParameter('id', $name); $this->setParameter('class', 'forkForms submitWithLink'); }
/** * Execute the actions */ public function execute() { parent::execute(); //--Get all the addresses $addresses = BackendAddressesModel::getAllAddresses(1); foreach ($addresses as &$address) { $address = BackendAddressesModel::get($address['id']); foreach ($address as &$row) { $row = $row == "" ? "-" : $row; } } foreach ($addresses as $address) { set_time_limit(10); if (filter_var($address['email'], FILTER_VALIDATE_EMAIL) && $address['send_mail'] == 0) { //--Send mail for the address BackendMailer::addEmail("Nieuwe website Namev.be met uw eigen bedrijfs-pagina", BACKEND_MODULE_PATH . '/layout/templates/mails/send_email.tpl', $address, '*****@*****.**', $address['company']); // BackendMailer::addEmail("Nieuwe website Namev.be met uw eigen bedrijfs-pagina", BACKEND_MODULE_PATH . '/layout/templates/mails/send_email.tpl', $address, '*****@*****.**', $address['company']); // BackendMailer::addEmail("Nieuwe website Namev.be met uw eigen bedrijfs-pagina", BACKEND_MODULE_PATH . '/layout/templates/mails/send_email.tpl', $address, $address['email'], $address['company']); BackendModel::getContainer()->get('database')->update('addresses', array("send_mail" => 1), 'id = ?', (int) $address['id']); die; } } //--Update the address row when e-mail is send }
/** * Get some statistics about the compression, like the Weissman score™ * * @return array Compression statistics */ public static function getStatistics() { $db = BackendModel::getContainer()->get('database'); return $db->getRecord('SELECT COUNT(i.id) AS total_compressed, SUM(i.saved_bytes) AS saved_bytes, concat(round(( 100 - (SUM(compressed_size) / SUM(original_size) * 100)),2),"%") AS saved_percentage FROM compression_history AS i'); }
/** * Handle the category of a post * * We'll check if the category exists in the fork blog module, and create it if it doesn't. * * @param string $category The post category * @return int */ private function handleCategory($category = '') { // Does a category with this name exist? /* @var \SpoonDatabase $db */ $db = BackendModel::getContainer()->get('database'); $id = (int) $db->getVar('SELECT id FROM blog_categories WHERE title=? AND language=?', array($category, BL::getWorkingLanguage())); // We found an id! if ($id > 0) { return $id; } // Return default if we got an empty string if (trim($category) == '') { return 2; } // We should create a new category $cat = array(); $cat['language'] = BL::getWorkingLanguage(); $cat['title'] = $category; $meta = array(); $meta['keywords'] = $category; $meta['description'] = $category; $meta['title'] = $category; $meta['url'] = $category; return Model::insertCategory($cat, $meta); }
/** * Update a page revision without generating a new revision. * Needed to add an image to a page. * * @param $revision_id * @param $item */ public static function updateRevision($revision_id, $item) { BackendModel::getContainer()->get('database')->update('blog_posts', $item, 'revision_id = ?', array($revision_id)); }
/** * Get the url of a navigation item. * If the item doesn't have an id, it will search recursively until it finds one. * * @param int $id The id to search for. * @return string */ private function getNavigationUrl($id) { $id = (int) $id; // get url $item = (array) BackendModel::getContainer()->get('database')->getRecord('SELECT id, url FROM backend_navigation WHERE id = ?', array($id)); if (empty($item)) { return ''; } elseif ($item['url'] != '') { return $item['url']; } else { // get the first child $childId = (int) BackendModel::getContainer()->get('database')->getVar('SELECT id FROM backend_navigation WHERE parent_id = ? ORDER BY sequence ASC LIMIT 1', array($id)); // get its url return $this->getNavigationUrl($childId); } }
/** * Parse some vars */ private function parseVars() { // assign a placeholder var $this->assign('var', ''); // assign current timestamp $this->assign('timestamp', time()); // check on url object if (Model::getContainer()->has('url')) { $url = Model::get('url'); if ($url instanceof Url) { $this->assign('bodyID', \SpoonFilter::toCamelCase($url->getModule(), '_', true)); // build classes $bodyClass = \SpoonFilter::toCamelCase($url->getModule() . '_' . $url->getAction(), '_', true); // special occasions if ($url->getAction() == 'add' || $url->getAction() == 'edit') { $bodyClass = $url->getModule() . 'AddEdit'; } // assign $this->assign('bodyClass', $bodyClass); } } if (Model::has('navigation')) { $navigation = Model::get('navigation'); if ($navigation instanceof Navigation) { $navigation->parse($this); } } foreach ($this->forms as $form) { if ($form->isSubmitted() && !$form->isCorrect()) { $this->assign('form_error', true); break; } } $this->assign('cookies', Model::get('request')->cookies->all()); }
/** * Process the querystring */ private function processQueryString() { // store the querystring local, so we don't alter it. $queryString = $this->getQueryString(); // find the position of ? (which separates real URL and GET-parameters) $positionQuestionMark = mb_strpos($queryString, '?'); // separate the GET-chunk from the parameters $getParameters = ''; if ($positionQuestionMark === false) { $processedQueryString = $queryString; } else { $processedQueryString = mb_substr($queryString, 0, $positionQuestionMark); $getParameters = mb_substr($queryString, $positionQuestionMark); } // split into chunks, a Backend URL will always look like /<lang>/<module>/<action>(?GET) $chunks = (array) explode('/', trim($processedQueryString, '/')); // check if this is a request for a AJAX-file $isAJAX = isset($chunks[1]) && $chunks[1] == 'ajax'; // get the language, this will always be in front $language = ''; if (isset($chunks[1]) && $chunks[1] != '') { $language = \SpoonFilter::getValue($chunks[1], array_keys(BackendLanguage::getWorkingLanguages()), ''); } // no language provided? if ($language == '' && !$isAJAX) { // remove first element array_shift($chunks); // redirect to login $this->redirect('/' . NAMED_APPLICATION . '/' . SITE_DEFAULT_LANGUAGE . (empty($chunks) ? '' : '/') . implode('/', $chunks) . $getParameters); } // get the module, null will be the default $module = isset($chunks[2]) && $chunks[2] != '' ? $chunks[2] : 'Dashboard'; $module = \SpoonFilter::toCamelCase($module); // get the requested action, if it is passed if (isset($chunks[3]) && $chunks[3] != '') { $action = \SpoonFilter::toCamelCase($chunks[3]); } elseif (!$isAJAX) { // Check if we can load the config file $configClass = 'Backend\\Modules\\' . $module . '\\Config'; if ($module == 'Core') { $configClass = 'Backend\\Core\\Config'; } try { // when loading a backend url for a module that doesn't exist, without // providing an action, a FatalErrorException occurs, because the config // class we're trying to load doesn't exist. Let's just throw instead, // and catch it immediately. if (!class_exists($configClass)) { throw new Exception('The config class does not exist'); } /** @var BackendBaseConfig $config */ $config = new $configClass($this->getKernel(), $module); // set action $action = $config->getDefaultAction() !== null ? $config->getDefaultAction() : 'Index'; } catch (Exception $ex) { if (BackendModel::getContainer()->getParameter('kernel.debug')) { throw new Exception('The config file for the module (' . $module . ') can\'t be found.'); } else { // @todo don't use redirects for error, we should have something like an invoke method. // build the url $errorUrl = '/' . NAMED_APPLICATION . '/' . $language . '/error?type=action-not-allowed'; // add the querystring, it will be processed by the error-handler $errorUrl .= '&querystring=' . rawurlencode('/' . $this->getQueryString()); // redirect to the error page $this->redirect($errorUrl, 307); } } } // AJAX parameters are passed via GET or POST if ($isAJAX) { $module = isset($_GET['fork']['module']) ? $_GET['fork']['module'] : ''; $action = isset($_GET['fork']['action']) ? $_GET['fork']['action'] : ''; $language = isset($_GET['fork']['language']) ? $_GET['fork']['language'] : SITE_DEFAULT_LANGUAGE; $module = isset($_POST['fork']['module']) ? $_POST['fork']['module'] : $module; $action = isset($_POST['fork']['action']) ? $_POST['fork']['action'] : $action; $language = isset($_POST['fork']['language']) ? $_POST['fork']['language'] : $language; $this->setModule($module); $this->setAction($action); BackendLanguage::setWorkingLanguage($language); } else { $this->processRegularRequest($module, $action, $language); } }
/** * Truncate a string * syntax: {$var|truncate:max-length[:append-hellip][:closest-word]} * * @param string $var The string passed from the template. * @param int $length The maximum length of the truncated string. * @param bool $useHellip Should a hellip be appended if the length exceeds the requested length? * @param bool $closestWord Truncate on exact length or on closest word? * @return string */ public static function truncate($var = null, $length, $useHellip = true, $closestWord = false) { // init vars $charset = BackendModel::getContainer()->getParameter('kernel.charset'); // remove special chars, all of them, also the ones that shouldn't be there. $var = \SpoonFilter::htmlentitiesDecode($var, null, ENT_QUOTES); // remove HTML $var = strip_tags($var); // less characters if (mb_strlen($var) <= $length) { return \SpoonFilter::htmlspecialchars($var); } else { // more characters // hellip is seen as 1 char, so remove it from length if ($useHellip) { $length = $length - 1; } // truncate if ($closestWord) { $var = mb_substr($var, 0, strrpos(substr($var, 0, $length + 1), ' '), $charset); } else { $var = mb_substr($var, 0, $length, $charset); } // add hellip if ($useHellip) { $var .= '…'; } // return return \SpoonFilter::htmlspecialchars($var, ENT_QUOTES); } }
/** * Update an existing item. * * @param array $item The new data. * @return int */ public static function update(array $item) { $db = BackendModel::getContainer()->get('database'); // update extra BackendModel::updateExtra($item['extra_id'], 'data', array('id' => $item['id'], 'extra_label' => $item['title'], 'language' => $item['language'], 'edit_url' => BackendModel::createURLForAction('Edit') . '&id=' . $item['id'])); // archive all older content_block versions $db->update('content_blocks', array('status' => 'archived'), 'id = ? AND language = ?', array($item['id'], BL::getWorkingLanguage())); // insert new version $item['revision_id'] = $db->insert('content_blocks', $item); // how many revisions should we keep $rowsToKeep = (int) BackendModel::get('fork.settings')->get('ContentBlocks', 'max_num_revisions', 20); // get revision-ids for items to keep $revisionIdsToKeep = (array) $db->getColumn('SELECT i.revision_id FROM content_blocks AS i WHERE i.id = ? AND i.language = ? AND i.status = ? ORDER BY i.edited_on DESC LIMIT ?', array($item['id'], BL::getWorkingLanguage(), 'archived', $rowsToKeep)); // delete other revisions if (!empty($revisionIdsToKeep)) { $db->delete('content_blocks', 'id = ? AND language = ? AND status = ? AND revision_id NOT IN (' . implode(', ', $revisionIdsToKeep) . ')', array($item['id'], BL::getWorkingLanguage(), 'archived')); } // return the new revision_id return $item['revision_id']; }
public static function getAllMediaItems() { $records = BackendModel::getContainer()->get('database')->getRecords("SELECT m.id, filename, m.filetype, m.extension FROM media AS m"); $recordsImages = $recordsFiles = array(); //--Loop records if (!empty($records)) { //--Get the thumbnail-folders $folders = BackendModel::getThumbnailFolders(FRONTEND_FILES_PATH . '/Media/Images', true); //--Create the image-links to the thumbnail folders foreach ($records as &$row) { if ($row['filetype'] == 1) { $path_parts = pathinfo(FRONTEND_FILES_PATH . '/Media/Images/Source/' . $row['filename']); $row['name'] = $path_parts['filename']; foreach ($folders as $folder) { $row['image_' . $folder['dirname']] = $folder['url'] . '/' . $folder['dirname'] . '/' . $row['filename']; } $recordsImages[] = $row; } else { $path_parts = pathinfo(FRONTEND_FILES_PATH . '/Media/Files/' . $row['filename']); $row['url'] = FRONTEND_FILES_URL . '/Media/Files/' . $row['filename']; $row['name'] = $path_parts['filename']; $recordsFiles[] = $row; } } } $all = array(); $all['images'] = $recordsImages; $all['files'] = $recordsFiles; return $all; }
/** * @param array $item * @return int */ public static function updateVideo(array $item) { BackendModel::invalidateFrontendCache('productsCache'); return (int) BackendModel::getContainer()->get('database')->update('catalog_videos', $item, 'id = ?', array($item['id'])); }
/** * Save the link list * * @param array $navigation The full navigation array * @param array $keys The page keys * @param string $language The language to save the file for * @return string The full content for the cache file */ protected function dumpEditorLinkList($navigation, $keys, $language) { // get the order foreach (array_keys($navigation) as $type) { $order[$type] = $this->getOrder($navigation, $type, 0); } // start building the cache file $editorLinkListString = $this->getCacheHeader('the links that can be used by the editor'); // init var $links = array(); // init var $cachedTitles = (array) $this->database->getPairs('SELECT i.id, i.navigation_title FROM pages AS i WHERE i.id IN(' . implode(',', array_keys($keys)) . ') AND i.language = ? AND i.status = ?', array($language, 'active')); // loop the types in the order we want them to appear foreach (array('page', 'meta', 'footer', 'root') as $type) { // any pages? if (isset($order[$type])) { // loop pages foreach ($order[$type] as $pageId => $url) { // skip if we don't have a title if (!isset($cachedTitles[$pageId])) { continue; } // get the title $title = \SpoonFilter::htmlspecialcharsDecode($cachedTitles[$pageId]); // split into chunks $urlChunks = explode('/', $url); // remove the language chunk $hasMultiLanguages = BackendModel::getContainer()->getParameter('site.multilanguage'); $urlChunks = $hasMultiLanguages ? array_slice($urlChunks, 2) : array_slice($urlChunks, 1); // subpage? if (count($urlChunks) > 1) { // loop while we have more then 1 chunk while (count($urlChunks) > 1) { // remove last chunk of the url array_pop($urlChunks); // build the temporary URL, so we can search for an id $tempUrl = implode('/', $urlChunks); // search the pageID $tempPageId = array_search($tempUrl, $keys); // prepend the title if (!isset($cachedTitles[$tempPageId])) { $title = ' > ' . $title; } else { $title = $cachedTitles[$tempPageId] . ' > ' . $title; } } } // add $links[] = array($title, $url); } } } // add JSON-string $editorLinkListString .= 'var linkList = ' . json_encode($links) . ';'; return $editorLinkListString; }
/** * Update a membership of a profile in a group. * * @param int $id Membership id. * @param array $values Membership data. * @return int */ public static function updateProfileGroup($id, array $values) { return (int) BackendModel::getContainer()->get('database')->update('profiles_groups_rights', $values, 'id = ?', (int) $id); }
public function execute() { parent::execute(); $txtText = \SpoonFile::getContent(BACKEND_MODULE_PATH . "/meubelwinkels.txt"); $arrText = explode("\n", $txtText); $strShop = ""; $arrShops = array(); $arrShopsFinal = array(); $arrElements = array("company", "phone", "zipcode", "city", "address", "contact", "email", "website", "fax", "vat", "assort", "m�", "open", "gesloten", "visit"); $arrElementsDash = array("assort", "m�", "open", "gesloten", "visit"); foreach ($arrText as $line) { //--Check if the line is only a zipcode or pagenumbers (1000 or 52 53) if (preg_match("/^\\d+\$/", $line) || preg_match("/^[0-9 ]+\$/", $line)) { continue; } //--Search for T : in the line (this is the first line of the address) if (strpos($line, "T :") !== false) { //--If line is not empty, add it to the array if (!empty($strShop)) { $arrShops[] = $strShop; } $strShop = ""; } //--Add the line + add a marker [LINE] $strShop .= $line . "[LINE]"; } //--Loop all the shops foreach ($arrShops as $shop) { //--Explode the shop with [LINE] $arrShop = explode("[LINE]", $shop); $arrShopFinal = array(); //--Get the phone number and name of the shop $strPosTelephone = strpos($arrShop[0], "T :"); //--Create array $arrShopFinal["company"] = ucwords(mb_strtolower(substr($arrShop[0], 0, $strPosTelephone))); $arrShopFinal["phone"] = trim(str_replace("T :", "", substr($arrShop[0], $strPosTelephone))); //--Get the address $strAddress = ucwords(mb_strtolower($arrShop[1])); //--Get position of the space $strPosSpaceZipcode = strpos($strAddress, " "); //--Add the zipcode $arrShopFinal["zipcode"] = substr($strAddress, 0, $strPosSpaceZipcode); //--Alter the address-string $strAddress = substr($strAddress, $strPosSpaceZipcode); //--Search comma $strPosCommaCity = strpos($strAddress, ","); //--Add the city $arrShopFinal["city"] = substr($strAddress, 0, $strPosCommaCity); //--Add the address $arrShopFinal["address"] = trim(substr($strAddress, $strPosCommaCity + 1)); //--Unset first and second item unset($arrShop[0]); unset($arrShop[1]); //--Loop the shop foreach ($arrShop as $key => $row) { //--Get the contact if (!isset($arrShopFinal["contact"]) && strpos($row, "contact:") !== false) { $arrShopFinal["contact"] = ucwords(mb_strtolower(trim(substr($row, 8)))); } //--Find the e-mailaddress in the string if (!isset($arrShopFinal["email"])) { preg_match("/[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,3})/i", $row, $matches); if (!empty($matches)) { $arrShopFinal["email"] = $matches[0]; } } //--Find the website address if (!isset($arrShopFinal["website"])) { preg_match("/www\\.[a-zA-Z0-9-]+\\.[a-z]{2,7}/i", $row, $matches); if (!empty($matches)) { $arrShopFinal["website"] = $matches[0]; } } //--Find the fax if (!isset($arrShopFinal["fax"])) { preg_match("/F: ([\\s0-9]+)/i", $row, $matches); if (!empty($matches)) { $arrShopFinal["fax"] = $matches[1]; } } //--Find the VAT if (!isset($arrShopFinal["btw"])) { preg_match("/BTW : ([A-Z]{2}[\\s]*[0-9-\\.\\s]+)/i", $row, $matches); if (!empty($matches)) { $arrShopFinal["vat"] = $matches[1]; } } //--Check if the dash is for a numeric value (not - assort:) preg_match("/([0-9]{1}[\\s]-[\\s][0-9]{1})/i", $row, $matches); if (!empty($matches)) { foreach ($matches as $match) { $strMatchReplace = str_replace(" - ", "-", $match); $row = str_replace($match, $strMatchReplace, $row); } } //--Split the text with " - "; $arrDashes = explode(" - ", $row); //--Check if there are elements if (!empty($arrDashes)) { //--Loop the different pieces foreach ($arrDashes as $dash) { //--Loop the elements that are possible for the dash-element foreach ($arrElementsDash as $element) { //--Check if the element is found, if true, add the element to the array if (strpos($dash, $element . ":") !== false) { $arrShopFinal[$element] = str_replace($element . ":", "", $dash); } } } } } //--Check if all elements are filled in foreach ($arrElements as $element) { //--If key not exists, add an empty value to it if (!isset($arrShopFinal[$element])) { //--Fill in empty value $arrShopFinal[$element] = ""; } else { //--Replace to utf8 $arrShopFinal[$element] = trim($arrShopFinal[$element]); //--Replace ? to ' $arrShopFinal[$element] = str_replace("?", "'", $arrShopFinal[$element]); } } //--Replace m� by size (for the database) $arrShopFinal["size"] = $arrShopFinal["m�"]; unset($arrShopFinal["m�"]); //--Replace gesloten by closed (for the database) $arrShopFinal["closed"] = $arrShopFinal["gesloten"]; unset($arrShopFinal["gesloten"]); $arrShopFinal["country"] = substr($arrShopFinal["vat"], 0, 2); $arrShopFinal["country"] = $arrShopFinal["country"] == "" ? "BE" : $arrShopFinal["country"]; //--Add final shop to all shops $arrShopsFinal[] = $arrShopFinal; } print "<pre>"; //--Loop all the shops foreach ($arrShopsFinal as $row) { $arrId = (array) BackendModel::getContainer()->get('database')->getVar('SELECT i.id FROM addresses AS i WHERE i.email = ? AND i.address = ? ', array($row['email'], $row['address'])); $id = (int) $arrId[0]; if ($id > 0) { $arrUpdate = array("contact" => $row['contact']); BackendModel::getContainer()->get('database')->update('addresses', $arrUpdate, 'id = ?', (int) $id); } else { echo $id; print_r($row); } } die; }
/** * "Updates" a mailing draft; it deletes and re-creates a draft mailing. * Campaignmonitor does not have an updateDraft method, so we have to do it this way in order * to be able to use their sendCampaignPreview method. * * @param array $item The mailing record to update a campaign draft. * @return string|null Returns the newly made campaign ID, or false if the method failed. */ public static function updateMailingDraft(array $item) { $db = BackendModel::getContainer()->get('database'); $campaignID = self::getCampaignMonitorID('campaign', $item['id']); if (is_string($campaignID)) { // first we insert the new campaign draft and store the CM ID $newCampaignID = self::insertMailingDraft($item); // delete the old CM campaign self::getCM()->deleteCampaign($campaignID); // remove the old CM ID from the database $db->delete('mailmotor_campaignmonitor_ids', 'cm_id = ?', $campaignID); // return the CM ID for the newly created draft campaign return $newCampaignID; } }
/** * Login the user with the given credentials. * Will return a boolean that indicates if the user is logged in. * * @param string $login The users login. * @param string $password The password provided by the user. * * @return bool */ public static function loginUser($login, $password) { $login = (string) $login; $password = (string) $password; $db = BackendModel::get('database'); // fetch the encrypted password $passwordEncrypted = static::getEncryptedPassword($login, $password); // check in database (is the user active and not deleted, are the email and password correct?) $userId = (int) $db->getVar('SELECT u.id FROM users AS u WHERE u.email = ? AND u.password = ? AND u.active = ? AND u.deleted = ? LIMIT 1', array($login, $passwordEncrypted, 'Y', 'N')); // not 0 = valid user! if ($userId !== 0) { // cleanup old sessions self::cleanupOldSessions(); // build the session array (will be stored in the database) $session = array(); $session['user_id'] = $userId; $session['secret_key'] = static::getEncryptedString(\SpoonSession::getSessionId(), $userId); $session['session_id'] = \SpoonSession::getSessionId(); $session['date'] = BackendModel::getUTCDate(); // insert a new row in the session-table $db->insert('users_sessions', $session); // store some values in the session \SpoonSession::set('backend_logged_in', true); \SpoonSession::set('backend_secret_key', $session['secret_key']); // update/instantiate the value for the logged_in container. BackendModel::getContainer()->set('logged_in', true); self::$user = new User($userId); // return result return true; } else { // userId 0 will not exist, so it means that this isn't a valid combination // reset values for invalid users. We can't destroy the session // because session-data can be used on the site. \SpoonSession::set('backend_logged_in', false); \SpoonSession::set('backend_secret_key', ''); // update/instantiate the value for the logged_in container. BackendModel::getContainer()->set('logged_in', false); // return result return false; } }
/** * Load the form */ private function loadForm() { // list of default domains $defaultDomains = array(str_replace(array('http://', 'www.', 'https://'), '', SITE_URL)); // create form $this->frm = new BackendForm('settingsIndex'); // general settings $this->frm->addText('site_title', $this->get('fork.settings')->get('Core', 'site_title_' . BL::getWorkingLanguage(), SITE_DEFAULT_TITLE)); $this->frm->addTextarea('site_html_header', $this->get('fork.settings')->get('Core', 'site_html_header', null), 'textarea code', 'textareaError code', true); $this->frm->addTextarea('site_start_of_body_scripts', $this->get('fork.settings')->get('Core', 'site_start_of_body_scripts', null), 'textarea code', 'textareaError code', true); $this->frm->addTextarea('site_html_footer', $this->get('fork.settings')->get('Core', 'site_html_footer', null), 'textarea code', 'textareaError code', true); $this->frm->addTextarea('site_domains', implode("\n", (array) $this->get('fork.settings')->get('Core', 'site_domains', $defaultDomains)), 'textarea code', 'textareaError code'); // facebook settings $this->frm->addText('facebook_admin_ids', $this->get('fork.settings')->get('Core', 'facebook_admin_ids', null)); $this->frm->addText('facebook_application_id', $this->get('fork.settings')->get('Core', 'facebook_app_id', null)); $this->frm->addText('facebook_application_secret', $this->get('fork.settings')->get('Core', 'facebook_app_secret', null)); // twitter settings $this->frm->addText('twitter_site_name', ltrim($this->get('fork.settings')->get('Core', 'twitter_site_name', null), '@')); // ckfinder $this->frm->addText('ckfinder_license_name', $this->get('fork.settings')->get('Core', 'ckfinder_license_name', null)); $this->frm->addText('ckfinder_license_key', $this->get('fork.settings')->get('Core', 'ckfinder_license_key', null)); $this->frm->addText('ckfinder_image_max_width', $this->get('fork.settings')->get('Core', 'ckfinder_image_max_width', 1600)); $this->frm->addText('ckfinder_image_max_height', $this->get('fork.settings')->get('Core', 'ckfinder_image_max_height', 1200)); // api keys $this->frm->addText('fork_api_public_key', $this->get('fork.settings')->get('Core', 'fork_api_public_key', null)); $this->frm->addText('fork_api_private_key', $this->get('fork.settings')->get('Core', 'fork_api_private_key', null)); // date & time formats $this->frm->addDropdown('time_format', BackendModel::getTimeFormats(), $this->get('fork.settings')->get('Core', 'time_format')); $this->frm->addDropdown('date_format_short', BackendModel::getDateFormatsShort(), $this->get('fork.settings')->get('Core', 'date_format_short')); $this->frm->addDropdown('date_format_long', BackendModel::getDateFormatsLong(), $this->get('fork.settings')->get('Core', 'date_format_long')); // number formats $this->frm->addDropdown('number_format', BackendModel::getNumberFormats(), $this->get('fork.settings')->get('Core', 'number_format')); // create a list of the languages foreach ($this->get('fork.settings')->get('Core', 'languages', array('en')) as $abbreviation) { // is this the default language $defaultLanguage = $abbreviation == SITE_DEFAULT_LANGUAGE ? true : false; // attributes $activeAttributes = array(); $activeAttributes['id'] = 'active_language_' . $abbreviation; $redirectAttributes = array(); $redirectAttributes['id'] = 'redirect_language_' . $abbreviation; // fetch label $label = BL::lbl(mb_strtoupper($abbreviation), 'Core'); // default may not be unselected if ($defaultLanguage) { // add to attributes $activeAttributes['disabled'] = 'disabled'; $redirectAttributes['disabled'] = 'disabled'; // overrule in $_POST if (!isset($_POST['active_languages']) || !is_array($_POST['active_languages'])) { $_POST['active_languages'] = array(SITE_DEFAULT_LANGUAGE); } elseif (!in_array($abbreviation, $_POST['active_languages'])) { $_POST['active_languages'][] = $abbreviation; } if (!isset($_POST['redirect_languages']) || !is_array($_POST['redirect_languages'])) { $_POST['redirect_languages'] = array(SITE_DEFAULT_LANGUAGE); } elseif (!in_array($abbreviation, $_POST['redirect_languages'])) { $_POST['redirect_languages'][] = $abbreviation; } } // add to the list $activeLanguages[] = array('label' => $label, 'value' => $abbreviation, 'attributes' => $activeAttributes, 'variables' => array('default' => $defaultLanguage)); $redirectLanguages[] = array('label' => $label, 'value' => $abbreviation, 'attributes' => $redirectAttributes, 'variables' => array('default' => $defaultLanguage)); } $hasMultipleLanguages = BackendModel::getContainer()->getParameter('site.multilanguage'); // create multilanguage checkbox $this->frm->addMultiCheckbox('active_languages', $activeLanguages, $this->get('fork.settings')->get('Core', 'active_languages', array($hasMultipleLanguages))); $this->frm->addMultiCheckbox('redirect_languages', $redirectLanguages, $this->get('fork.settings')->get('Core', 'redirect_languages', array($hasMultipleLanguages))); // api keys are not required for every module if ($this->needsAkismet) { $this->frm->addText('akismet_key', $this->get('fork.settings')->get('Core', 'akismet_key', null)); } if ($this->needsGoogleMaps) { $this->frm->addText('google_maps_key', $this->get('fork.settings')->get('Core', 'google_maps_key', null)); } // cookies $this->frm->addCheckbox('show_cookie_bar', $this->get('fork.settings')->get('Core', 'show_cookie_bar', false)); }
protected function loadLanguages() { $settings = BackendModel::getContainer()->get('fork.settings'); $this->languages = $settings->get('Core', 'languages', array('en')); }
/** * Parse a field and return the HTML. * * @param array $field Field data. * @return string */ public static function parseField(array $field) { if (!empty($field)) { // init $frm = new BackendForm('tmp', ''); $tpl = BackendModel::getContainer()->has('template') ? BackendModel::getContainer()->get('template') : new BackendTemplate(); $fieldHTML = ''; $fieldName = 'field' . $field['id']; $values = isset($field['settings']['values']) ? $field['settings']['values'] : null; $defaultValues = isset($field['settings']['default_values']) ? $field['settings']['default_values'] : null; $placeholder = isset($field['settings']['placeholder']) ? $field['settings']['placeholder'] : null; /** * Create form and parse to HTML */ // dropdown if ($field['type'] == 'dropdown') { // values and labels are the same $values = array_combine($values, $values); // get index of selected item $defaultIndex = array_search($defaultValues, $values, true); if ($defaultIndex === false) { $defaultIndex = null; } // create element $ddm = $frm->addDropdown($fieldName, $values, $defaultIndex); // empty default element $ddm->setDefaultElement(''); // get content $fieldHTML = $ddm->parse(); } elseif ($field['type'] == 'datetime') { // create element if ($field['settings']['input_type'] == 'date') { // calculate default value $amount = $field['settings']['value_amount']; $type = $field['settings']['value_type']; if ($type != '') { switch ($type) { case 'today': $defaultValues = date('d/m/Y'); break; case 'day': case 'week': case 'month': case 'year': if ($amount != '') { $defaultValues = date('d/m/Y', strtotime('+' . $amount . ' ' . $type)); } break; } } $datetime = $frm->addText($fieldName, $defaultValues); } else { $datetime = $frm->addTime($fieldName, $defaultValues); } $datetime->setAttribute('disabled', 'disabled'); // get content $fieldHTML = $datetime->parse(); } elseif ($field['type'] == 'radiobutton') { // create element $rbt = $frm->addRadiobutton($fieldName, $values, $defaultValues); // get content $fieldHTML = $rbt->parse(); } elseif ($field['type'] == 'checkbox') { // rebuild values foreach ($values as $value) { $newValues[] = array('label' => $value, 'value' => $value); } // create element $chk = $frm->addMultiCheckbox($fieldName, $newValues, $defaultValues); // get content $fieldHTML = $chk->parse(); } elseif ($field['type'] == 'textbox') { // create element $txt = $frm->addText($fieldName, $defaultValues); $txt->setAttribute('disabled', 'disabled'); $txt->setAttribute('placeholder', $placeholder); // get content $fieldHTML = $txt->parse(); } elseif ($field['type'] == 'textarea') { // create element $txt = $frm->addTextarea($fieldName, $defaultValues); $txt->setAttribute('cols', 30); $txt->setAttribute('disabled', 'disabled'); $txt->setAttribute('placeholder', $placeholder); // get content $fieldHTML = $txt->parse(); } elseif ($field['type'] == 'heading') { $fieldHTML = '<h3>' . $values . '</h3>'; } elseif ($field['type'] == 'paragraph') { $fieldHTML = $values; } /** * Parse the field into the template */ // init $tpl->assign('plaintext', false); $tpl->assign('simple', false); $tpl->assign('multiple', false); $tpl->assign('id', $field['id']); $tpl->assign('required', isset($field['validations']['required'])); // plaintext items if ($field['type'] == 'heading' || $field['type'] == 'paragraph') { // assign $tpl->assign('content', $fieldHTML); $tpl->assign('plaintext', true); } elseif ($field['type'] == 'checkbox' || $field['type'] == 'radiobutton') { // name (prefixed by type) $name = $field['type'] == 'checkbox' ? 'chk' . \SpoonFilter::ucfirst($fieldName) : 'rbt' . \SpoonFilter::ucfirst($fieldName); // rebuild so the html is stored in a general name (and not rbtName) foreach ($fieldHTML as &$item) { $item['field'] = $item[$name]; } // show multiple $tpl->assign('label', $field['settings']['label']); $tpl->assign('items', $fieldHTML); $tpl->assign('multiple', true); } else { // assign $tpl->assign('label', $field['settings']['label']); $tpl->assign('field', $fieldHTML); $tpl->assign('simple', true); } return $tpl->getContent(BACKEND_MODULES_PATH . '/FormBuilder/Layout/Templates/Field.tpl'); } else { // empty field so return empty string return ''; } }
public function AddVideo($type, $id) { //--Check if the file is an image or file $item = array(); $item["filename"] = $id; $item["extension"] = $type; $item["created_on"] = BackendModel::getUTCDate('Y-m-d H:i:s'); $item["filesize"] = 0; $item["filetype"] = 3; //--Serialize data //$item["data"] = serialize($data); //--Store item so we can access it $this->item = $item; //--Insert into media $media_id = BackendModel::getContainer()->get('database')->insert("media", $item); $this->item['media_id'] = $media_id; $this->item["text"] = ""; //--Link the $this->item['id'] = $this->linkMediaToModule($media_id); return $media_id; }
/** * Set a setting * * @param string $key The key of the setting. * @param mixed $value The value to store. */ public function setSetting($key, $value) { $key = (string) $key; $valueToStore = serialize($value); // get db $db = BackendModel::getContainer()->get('database'); // store $db->execute('INSERT INTO users_settings(user_id, name, value) VALUES(?, ?, ?) ON DUPLICATE KEY UPDATE value = ?', array($this->getUserId(), $key, $valueToStore, $valueToStore)); // cache setting $this->settings[(string) $key] = $value; }
/** * Update a synonym * * @param array $item The data to update in the db. */ public static function updateSynonym($item) { // update BackendModel::getContainer()->get('database')->update('search_synonyms', $item, 'id = ?', array($item['id'])); // invalidate the cache for search self::invalidateCache(); }