/**
  * Update function
  */
 public function update()
 {
     // Support for the multilanguage extension by Giel Berkers:
     // http://github.com/kanduvisla/multilanguage
     //
     // See if the multilingual extension is installed:
     require_once TOOLKIT . '/class.extensionmanager.php';
     $extensionManager = new ExtensionManager($this);
     $status = $extensionManager->fetchStatus('multilanguage');
     if ($status == EXTENSION_ENABLED) {
         // Append some extra rows to the search-index table:
         $languages = explode(',', file_get_contents(MANIFEST . '/multilanguage-languages'));
         // Check which fields exist:
         $columns = Symphony::Database()->fetch("SHOW COLUMNS FROM `tbl_search_index`");
         $fields = array();
         foreach ($columns as $column) {
             $fields[] = $column['Field'];
         }
         foreach ($languages as $language) {
             $field = 'data_' . $language;
             if (!in_array($field, $fields)) {
                 Administration::instance()->Database->query("ALTER TABLE `tbl_search_index` ADD `" . $field . "` TEXT, ADD FULLTEXT (`" . $field . "`)");
             }
         }
     }
     // End Support
 }
 /**
  * Upgrade Mediathek fields to make use of this extension
  */
 public function __upgradeMediathek()
 {
     // Do not use Administration::instance() in this context, see:
     // http://github.com/nilshoerrmann/subsectionmanager/issues#issue/27
     $callback = $this->_Parent->getPageCallback();
     // Append upgrade notice
     if ($callback['driver'] == 'systemextensions') {
         require_once TOOLKIT . '/class.extensionmanager.php';
         $ExtensionManager = new ExtensionManager(Administration::instance());
         // Check if Mediathek field is installed
         $mediathek = $ExtensionManager->fetchStatus('mediathek');
         if ($mediathek == EXTENSION_ENABLED) {
             // Append upgrade notice to page
             Administration::instance()->Page->Alert = new Alert(__('You are using Mediathek and Subsection Manager simultaneously.') . ' <a href="http://' . DOMAIN . '/symphony/extension/subsectionmanager/">' . __('Upgrade') . '?</a> <a href="http://' . DOMAIN . '/symphony/extension/subsectionmanager/deactivate/mediathek">' . __('Disable Mediathek') . '</a> <a href="http://' . DOMAIN . '/symphony/extension/subsectionmanager/deactivate/subsectionmanager">' . __('Disable Subsection Manager') . '</a>', Alert::ERROR);
         }
     }
 }
 /**
  * Resizes an Image to a given maximum width and height.
  *
  * @param string  $file     - absolute image path
  * @param integer $width    - desired width of the image
  * @param integer $height   - desired height of the image
  * @param string  $mimetype - image type
  *
  * @return boolean - true if success, false otherwise
  */
 public static function resize($file, $width, $height, $mimetype)
 {
     $jit_status = ExtensionManager::fetchStatus(array('handle' => 'jit_image_manipulation'));
     // process image using JIT mode 1
     if ($jit_status[0] === EXTENSION_ENABLED) {
         require_once EXTENSIONS . '/jit_image_manipulation/lib/class.image.php';
         try {
             $image = Image::load($file);
             // if not and Image, stick with original version
             if (!$image instanceof Image) {
                 return false;
             }
         } catch (Exception $e) {
             return false;
         }
         $image->applyFilter('resize', array($width, $height));
         $image->save($file, 85, null, $mimetype);
     }
     return true;
 }
 /**
  * Parse the indexable content for an entry
  *
  * @param int $entry
  * @param int $section
  */
 public function indexEntry($entry, $section, $check_filters = TRUE)
 {
     self::assert();
     if (is_object($entry)) {
         $entry = $entry->get('id');
     }
     if (is_object($section)) {
         $section = $section->get('id');
     }
     // get a list of sections that have indexing enabled
     $indexed_sections = self::getIndexes();
     // go no further if this section isn't being indexed
     if (!isset($indexed_sections[$section])) {
         return;
     }
     // delete existing index for this entry
     self::deleteIndexByEntry($entry);
     // get the current section index config
     $section_index = $indexed_sections[$section];
     // only pass entries through filters if we need to. If entry is being sent
     // from the Re-Index AJAX it has already gone through filtering, so no need here
     if ($check_filters === TRUE) {
         if (self::$_where == NULL || self::$_joins == NULL) {
             // modified from class.datasource.php
             // create filters and build SQL required for each
             if (is_array($section_index['filters']) && !empty($section_index['filters'])) {
                 foreach ($section_index['filters'] as $field_id => $filter) {
                     if (is_array($filter) && empty($filter) || trim($filter) == '') {
                         continue;
                     }
                     if (!is_array($filter)) {
                         $filter_type = DataSource::__determineFilterType($filter);
                         $value = preg_split('/' . ($filter_type == DS_FILTER_AND ? '\\+' : ',') . '\\s*/', $filter, -1, PREG_SPLIT_NO_EMPTY);
                         $value = array_map('trim', $value);
                     } else {
                         $value = $filter;
                     }
                     $field = self::$_entry_manager->fieldManager->fetch($field_id);
                     $field->buildDSRetrivalSQL($value, $joins, $where, $filter_type == DS_FILTER_AND ? TRUE : FALSE);
                 }
             }
             self::$_where = $where;
             self::$_joins = $joins;
         }
         // run entry though filters
         $entry_prefilter = self::$_entry_manager->fetch($entry, $section, 1, 0, self::$_where, self::$_joins, FALSE, FALSE);
         // if no entry found, it didn't pass the pre-filtering
         if (empty($entry_prefilter)) {
             return;
         }
         // if entry passes filtering, pass entry_id as a DS filter to the EntryXMLDataSource DS
         $entry = reset($entry_prefilter);
         $entry = $entry['id'];
     }
     if (!is_array($entry)) {
         $entry = array($entry);
     }
     // create a DS and filter on System ID of the current entry to build the entry's XML
     #$ds = new EntryXMLDataSource(Administration::instance(), NULL, FALSE);
     self::$_entry_xml_datasource->dsParamINCLUDEDELEMENTS = $indexed_sections[$section]['fields'];
     self::$_entry_xml_datasource->dsParamFILTERS['id'] = implode(',', $entry);
     self::$_entry_xml_datasource->dsSource = (string) $section;
     $param_pool = array();
     $entry_xml = self::$_entry_xml_datasource->grab($param_pool);
     require_once TOOLKIT . '/class.xsltprocess.php';
     $xml = simplexml_load_string($entry_xml->generate());
     /* MULTILANGUAGE SUPPORT: */
     require_once TOOLKIT . '/class.extensionmanager.php';
     require_once TOOLKIT . '/class.fieldmanager.php';
     $fieldManager = new FieldManager($this);
     $extensionManager = new ExtensionManager($this);
     $status = $extensionManager->fetchStatus('multilanguage');
     $multilingualFields = array();
     $languages = array();
     if ($status == EXTENSION_ENABLED) {
         // Check if this section has multilingual fields:
         $results = Symphony::Database()->fetch('SELECT `element_name` FROM `tbl_fields` WHERE `parent_section` = ' . $section . ' AND `multilanguage` = 1;');
         foreach ($results as $result) {
             $multilingualFields[] = $result['element_name'];
         }
         $languages = explode(',', file_get_contents(MANIFEST . '/multilanguage-languages'));
     }
     foreach ($xml->xpath("//entry") as $entry_xml) {
         // get text value of the entry (default behaviour)
         $proc = new XsltProcess();
         $data = $proc->process($entry_xml->asXML(), file_get_contents(EXTENSIONS . '/search_index/lib/parse-entry.xsl'));
         $dataLanguages = array();
         foreach ($languages as $language) {
             foreach ($entry_xml->children() as $child) {
                 $name = $child->getName();
                 if (in_array($name, $multilingualFields)) {
                     // Bingo!
                     // Get the correct value for this item:
                     $field_id = $fieldManager->fetchFieldIDFromElementName($name);
                     $entry_id = $entry_xml->attributes()->id;
                     $values = Symphony::Database()->fetch('SELECT * FROM `tbl_multilanguage_values` WHERE `id_entry` = ' . $entry_id . ' AND `id_field` = ' . $field_id . ' AND `language` = \'' . $language . '\';');
                     if (count($values) >= 1) {
                         // Value found:
                         foreach ($values as $value) {
                             switch ($value['field_name']) {
                                 case 'value':
                                     $entry_xml->{$name} = $value['value'];
                                     break;
                             }
                         }
                     }
                 }
             }
             // Store it:
             $proc = new XsltProcess();
             $dataLanguages[$language] = $proc->process($entry_xml->asXML(), file_get_contents(EXTENSIONS . '/search_index/lib/parse-entry.xsl'));
         }
         self::saveEntryIndex((int) $entry_xml->attributes()->id, $section, $data, $dataLanguages);
         /* END MULTILANGUAGE SUPPORT */
     }
 }
 /**
  * Returns true or false if dependencies are met.
  *
  * @param bool $return_status - if this is set, it will return true or false if dependencies are met. if it is not set, error is thrown
  *
  * @throws Exception
  *
  * @return bool
  */
 public function meetDependencies($return_status = false)
 {
     // depends on "Languages"
     $languages_status = ExtensionManager::fetchStatus(array('handle' => 'languages'));
     $languages_status = current($languages_status);
     if ($languages_status != EXTENSION_ENABLED) {
         if ($return_status) {
             return false;
         } else {
             throw new Exception('Frontend Localisation depends on Languages extension.');
         }
     }
     return true;
 }
 private function __construct()
 {
     $s = Symphony::Configuration()->get();
     $this->_settings = $s[ABF::SETTING_GROUP];
     unset($s);
     // now an array
     $validStatuses = EXTENSION_ENABLED;
     $about = ExtensionManager::about('anti_brute_force');
     $status = ExtensionManager::fetchStatus($about);
     $this->_isInstalled = in_array($validStatuses, $status);
     // only if already installed
     if ($this->_isInstalled) {
         // assure access to settings
         // fail is not settings, since this is a security software
         if (count($this->_settings) < 1) {
             throw new Exception('Can not load settings. Can not continue.');
         }
     }
 }
 private function validateDependencies()
 {
     $result = true;
     // members installed
     $members = ExtensionManager::fetchStatus(array('handle' => 'members'));
     $result = $result && $members[0] === EXTENSION_ENABLED;
     // exsl function manager installed
     $efm = ExtensionManager::fetchStatus(array('handle' => 'exsl_function_manager'));
     $result = $result && $efm[0] === EXTENSION_ENABLED;
     $this->setValidDependencies($result);
 }
 function build($context)
 {
     $this->setTitle('Symphony - File Browser for CKEditor');
     if (!Administration::instance()->isLoggedIn()) {
         $this->_Parent->customError(E_USER_ERROR, __('Access Denied'), __('You are not authorised to access this page.'));
         exit;
     }
     $this->addElementToHead(new XMLElement('meta', NULL, array('http-equiv' => 'Content-Type', 'content' => 'text/html; charset=UTF-8')), 0);
     $this->addHeaderToPage('Content-Type', 'text/html; charset=UTF-8');
     ## Build the form
     $form = Widget::Form(Administration::instance()->getCurrentPageURL(), 'post');
     // Check for the subdirectory:
     $symphonyDomain = parse_url(URL, PHP_URL_SCHEME) . '://' . parse_url(URL, PHP_URL_HOST);
     $symphonySubdir = str_replace($symphonyDomain, '', URL);
     // Get the section:
     if (isset($_GET['id'])) {
         $sectionID = intval($_GET['id']);
         $section = SectionManager::fetch($sectionID);
         if ($section != false) {
             $div = new XMLElement('div', null, array('class' => 'items'));
             // Check if JIT is installed:
             $status = ExtensionManager::fetchStatus(array('handle' => 'jit_image_manipulation'));
             $jitEnabled = in_array(EXTENSION_ENABLED, $status);
             // Get the field id's:
             $fields = $section->fetchFields();
             $fieldIDs = array();
             foreach ($fields as $field) {
                 $fieldIDs[] = $field->get('id');
             }
             // Add rows:
             $entries = EntryManager::fetch(null, $sectionID);
             foreach ($entries as $entry) {
                 $data = $entry->getData();
                 $name = false;
                 foreach ($fieldIDs as $id) {
                     $info = $data[$id];
                     if (isset($info['value'])) {
                         if ($name == false) {
                             $name = $info['value'];
                         }
                     } elseif (isset($info['handle'])) {
                         if ($name == false) {
                             $name = $info['handle'];
                         }
                     } elseif (isset($info['file'])) {
                         if ($name == false) {
                             $name = basename($info['file']);
                         }
                         $value = '<a href="' . $symphonySubdir . '/workspace' . $info['file'] . '">';
                         $value = '<a href="/workspace' . $info['file'] . '">';
                         $a = explode('.', $info['file']);
                         $ext = trim(strtolower($a[count($a) - 1]));
                         // Check if JIT is enabled:
                         if ($jitEnabled && ($ext == 'jpeg' || $ext == 'jpg' || $ext == 'png' || $ext == 'gif')) {
                             $value .= '<img src="' . $symphonySubdir . '/image/2/100/100/5' . $info['file'] . '" alt="thumb" width="100" height="100" />';
                         } else {
                             // Show an icon according to it's extension:
                             $a = explode('.', basename($info['file']));
                             $ext = strtolower($a[count($a) - 1]);
                             $value .= '<img src="' . $this->getImage($ext) . '" alt="thumb" width="64" heigh="64" class="icon" />';
                         }
                         $value .= '<br />' . $name . '</a>';
                         $item = new XMLElement('div', $value);
                         $div->appendChild($item);
                     }
                 }
             }
             $form->appendChild(new XMLElement('a', __('create new'), array('href' => $symphonySubdir . '/symphony/publish/' . $section->get('handle') . '/new/', 'class' => 'create button')));
             $form->appendChild(new XMLElement('h3', $section->get('name')));
             $form->appendChild($div);
             $form->appendChild(new XMLElement('div', '', array('id' => 'thumb')));
         }
     }
     $this->Body->appendChild($form);
 }
 /**
  * Validate extension dependencies.
  *
  * @return boolean - true if dependencies are met, false otherwise
  */
 private function _validateDependencies()
 {
     $fl_status = ExtensionManager::fetchStatus(array('handle' => 'frontend_localisation'));
     return (bool) ($fl_status[0] === EXTENSION_ENABLED);
 }
 public function grab(&$param_pool)
 {
     $result = new XMLElement($this->dsParamROOTELEMENT);
     $param_output = array();
     $get = $_GET;
     // look for key in GET array if it's specified
     if (Symphony::Configuration()->get('get-param-prefix', 'search_index') != '') {
         if (Symphony::Configuration()->get('get-param-prefix', 'search_index') == 'param_pool') {
             $get = $this->_env['param'];
         } else {
             $get = $get[Symphony::Configuration()->get('get-param-prefix', 'search_index')];
         }
     }
     $param_keywords = Symphony::Configuration()->get('get-param-keywords', 'search_index');
     $param_per_page = Symphony::Configuration()->get('get-param-per-page', 'search_index');
     $param_sort = Symphony::Configuration()->get('get-param-sort', 'search_index');
     $param_direction = Symphony::Configuration()->get('get-param-direction', 'search_index');
     $param_sections = Symphony::Configuration()->get('get-param-sections', 'search_index');
     $param_page = Symphony::Configuration()->get('get-param-page', 'search_index');
     $keywords = $get[$param_keywords];
     $this->dsParamLIMIT = isset($get[$param_per_page]) && (int) $get[$param_per_page] > 0 ? (int) $get[$param_per_page] : $this->dsParamLIMIT;
     $sort = isset($get[$param_sort]) ? $get[$param_sort] : 'score';
     $direction = isset($get[$param_direction]) ? strtolower($get[$param_direction]) : 'desc';
     $sections = isset($get[$param_sections]) ? $get[$param_sections] : NULL;
     if ($sections == NULL && Symphony::Configuration()->get('default-sections', 'search_index') != '') {
         $sections = Symphony::Configuration()->get('default-sections', 'search_index');
     }
     $this->dsParamSTARTPAGE = isset($get[$param_page]) ? (int) $get[$param_page] : $this->dsParamSTARTPAGE;
     if (is_null($sections)) {
         return $this->errorXML('Invalid search sections');
     } else {
         $section_handles = explode(',', $sections);
         $sections = array();
         foreach ($section_handles as $handle) {
             $section = Symphony::Database()->fetchRow(0, sprintf("SELECT `id`, `name` FROM `tbl_sections` WHERE handle = '%s' LIMIT 1", Symphony::Database()->cleanValue($handle)));
             if ($section) {
                 $sections[$section['id']] = array('handle' => $handle, 'name' => $section['name']);
             }
         }
         if (count($sections) == 0) {
             return $this->errorXML('Invalid search sections');
         }
     }
     if ($sort == 'date') {
         $order_by = "e.creation_date {$direction}";
     } else {
         if ($sort == 'id') {
             $order_by = "e.id {$direction}";
         } else {
             $order_by = "score {$direction}";
         }
     }
     $weighting = '';
     $indexed_sections = SearchIndex::getIndexes();
     foreach ($indexed_sections as $section_id => $index) {
         $weight = is_null($index['weighting']) ? 2 : $index['weighting'];
         switch ($weight) {
             case 0:
                 $weight = 4;
                 break;
                 // highest
             // highest
             case 1:
                 $weight = 2;
                 break;
                 // high
             // high
             case 2:
                 $weight = 1;
                 break;
                 // none
             // none
             case 3:
                 $weight = 0.5;
                 break;
                 // low
             // low
             case 4:
                 $weight = 0.25;
                 break;
                 // lowest
         }
         $weighting .= sprintf("WHEN e.section_id = %d THEN %d \n", $section_id, $weight);
     }
     /* MULTILANGUAGE SUPPORT: */
     require_once TOOLKIT . '/class.extensionmanager.php';
     $extensionManager = new ExtensionManager($this);
     $status = $extensionManager->fetchStatus('multilanguage');
     $languageSuffix = '';
     if ($status == EXTENSION_ENABLED) {
         $languages = explode(',', file_get_contents(MANIFEST . '/multilanguage-languages'));
         if (count($languages) > 0) {
             $code = isset($_GET['language-code']) ? strtolower($_GET['language-code']) : $languages[0];
             // Override: if the parameter &lang is also in the URL, search that language instead:
             $code = isset($_GET['lang']) ? strtolower($_GET['lang']) : $code;
             $languageSuffix = '_' . $code;
             // SQL injection prevention:
             if (in_array($code, $languages)) {
                 $languageSuffix = '_' . $code;
             }
         }
     }
     $sql = sprintf("SELECT \n\t\t\t\t\tSQL_CALC_FOUND_ROWS \n\t\t\t\t\te.id as `entry_id`,\n\t\t\t\t\tdata" . $languageSuffix . ",\n\t\t\t\t\te.section_id as `section_id`,\n\t\t\t\t\tUNIX_TIMESTAMP(e.creation_date) AS `creation_date`,\n\t\t\t\t\t(\n\t\t\t\t\t\tMATCH(index.data" . $languageSuffix . ") AGAINST ('%1\$s') * \n\t\t\t\t\t\tCASE\n\t\t\t\t\t\t\t%2\$s\n\t\t\t\t\t\t\tELSE 1\n\t\t\t\t\t\tEND\n\t\t\t\t\t\t%3\$s\t\t\t\t\t\t\n\t\t\t\t\t) AS `score`\n\t\t\t\tFROM\n\t\t\t\t\ttbl_search_index as `index`\n\t\t\t\t\tJOIN tbl_entries as `e` ON (index.entry_id = e.id)\n\t\t\t\tWHERE\n\t\t\t\t\tMATCH(index.data" . $languageSuffix . ") AGAINST ('%4\$s' IN BOOLEAN MODE)\n\t\t\t\t\tAND e.section_id IN ('%5\$s')\n\t\t\t\tORDER BY\n\t\t\t\t\t%6\$s\n\t\t\t\tLIMIT %7\$d, %8\$d", Symphony::Database()->cleanValue($keywords), $weighting, $sort == 'score-recency' ? '/ SQRT(GREATEST(1, DATEDIFF(NOW(), creation_date)))' : '', Symphony::Database()->cleanValue(SearchIndex::manipulateKeywords($keywords)), implode("','", array_keys($sections)), Symphony::Database()->cleanValue($order_by), max(0, ($this->dsParamSTARTPAGE - 1) * $this->dsParamLIMIT), (int) $this->dsParamLIMIT);
     /* END MULTILANGUAGE SUPPORT */
     //echo $sql;die;
     $result->setAttributeArray(array('keywords' => General::sanitize($keywords), 'sort' => $sort, 'direction' => $direction));
     // get our entries!
     $entries = Symphony::Database()->fetch($sql);
     $total_entries = Symphony::Database()->fetchVar('total', 0, 'SELECT FOUND_ROWS() AS `total`');
     $result->appendChild(General::buildPaginationElement($total_entries, ceil($total_entries * (1 / $this->dsParamLIMIT)), $this->dsParamLIMIT, $this->dsParamSTARTPAGE));
     $sections_xml = new XMLElement('sections');
     foreach ($sections as $id => $section) {
         $sections_xml->appendChild(new XMLElement('section', General::sanitize($section['name']), array('id' => $id, 'handle' => $section['handle'])));
     }
     $result->appendChild($sections_xml);
     foreach ($entries as $entry) {
         $param_output[] = $entry['entry_id'];
         $result->appendChild(new XMLElement('entry', General::sanitize(SearchIndex::parseExcerpt($keywords, $entry['data'])), array('id' => $entry['entry_id'], 'section' => $sections[$entry['section_id']]['handle'], 'score' => round($entry['score'], 3))));
     }
     // send entry IDs as Output Parameterss
     $param_pool['ds-' . $this->dsParamROOTELEMENT] = $param_output;
     $log_sql = sprintf("INSERT INTO `tbl_search_index_logs`\n\t\t\t\t(date, keywords, sections, page, results, session_id)\n\t\t\t\tVALUES('%s', '%s', '%s', %d, %d, '%s')", date('Y-m-d H:i:s', time()), Symphony::Database()->cleanValue($keywords), Symphony::Database()->cleanValue(implode(',', $section_handles)), $this->dsParamSTARTPAGE, $total_entries, session_id());
     if ($this->log === TRUE) {
         Symphony::Database()->query($log_sql);
     }
     return $result;
 }