Пример #1
0
    /**
     * Method responsible for drawing links to settings and login panels
     *
     * @param array $data makes use of the CSRF_TOKEN for anti CSRF attacks
     */
    function render($data)
    {
        $logged_in = isset($data["ADMIN"]) && $data["ADMIN"];
        ?>
        <div class="user-nav" >
        <ul>
        <?php 
        if ($logged_in) {
            ?>
<li><b>[<a href="./?c=admin&amp;<?php 
            e(CSRF_TOKEN . "=" . $data[CSRF_TOKEN]);
            ?>
"><?php 
            e($data['USERNAME']);
            ?>
</a>]</b></li>
            <?php 
        }
        if (WEB_ACCESS) {
            ?>
            <li><a href="./?c=settings&amp;<?php 
            if ($logged_in) {
                e(CSRF_TOKEN . "=" . $data[CSRF_TOKEN] . "&amp;");
            }
            ?>
l=<?php 
            e(getLocaleTag());
            e(isset($data['its']) ? '&amp;its=' . $data['its'] : '');
            e(isset($data['ACTIVITY_METHOD']) ? '&amp;return=' . $data['ACTIVITY_METHOD'] : '');
            e(isset($data['ACTIVITY_CONTROLLER']) ? '&amp;oldc=' . $data['ACTIVITY_CONTROLLER'] : '');
            ?>
"><?php 
            e(tl('signin_element_settings'));
            ?>
</a></li><?php 
        }
        if (SIGNIN_LINK && !$logged_in) {
            ?>
<li><a href="./?c=admin"><?php 
            e(tl('signin_element_signin'));
            ?>
</a></li><?php 
        }
        if ($logged_in) {
            ?>
<li><a href="./?a=signout"><?php 
            e(tl('signin_element_signout'));
            ?>
</a></li><?php 
        }
        ?>
        </ul>
        </div>
        <?php 
    }
Пример #2
0
 /**
  * Creates a web archive iterator with the given parameters.
  *
  * @param string $mix_timestamp timestamp of the crawl mix to
  *     iterate over the pages of
  * @param string $result_timestamp timestamp of the web archive bundle
  *     results are being stored in
  */
 function __construct($mix_timestamp, $result_timestamp)
 {
     global $INDEXING_PLUGINS;
     setLocaleObject(getLocaleTag());
     $this->mix_timestamp = $mix_timestamp;
     $this->result_timestamp = $result_timestamp;
     $this->query = "site:any m:" . $mix_timestamp;
     $this->searchController = new SearchController($INDEXING_PLUGINS);
     $archive_name = $this->getArchiveName($result_timestamp);
     if (!file_exists($archive_name)) {
         mkdir($archive_name);
     }
     if (file_exists("{$archive_name}/iterate_status.txt")) {
         $this->restoreCheckpoint();
     } else {
         $this->reset();
     }
 }
Пример #3
0
 /**
  * Get a list of admin activities that a user is allowed to perform.
  * This includes their name and their associated method.
  *
  * @param string $user_id  id of user to get activities fors
  */
 function getUserActivities($user_id)
 {
     $db = $this->db;
     $activities = array();
     $status = $this->getUserStatus($user_id);
     if (!$status || in_array($status, array(BANNED_STATUS, INACTIVE_STATUS))) {
         return array();
     }
     $locale_tag = getLocaleTag();
     $limit_offset = $db->limitOffset(1);
     $sql = "SELECT LOCALE_ID FROM LOCALE " . "WHERE LOCALE_TAG = ? {$limit_offset}";
     $result = $db->execute($sql, array($locale_tag));
     $row = $db->fetchArray($result);
     $locale_id = $row['LOCALE_ID'];
     $sql = "SELECT DISTINCT A.ACTIVITY_ID AS ACTIVITY_ID, " . "T.TRANSLATION_ID AS TRANSLATION_ID, A.METHOD_NAME AS METHOD_NAME," . " T.IDENTIFIER_STRING AS IDENTIFIER_STRING FROM ACTIVITY A, " . " USER_ROLE UR, ROLE_ACTIVITY RA, TRANSLATION T " . "WHERE UR.USER_ID = ? " . "AND UR.ROLE_ID=RA.ROLE_ID AND T.TRANSLATION_ID=A.TRANSLATION_ID " . "AND RA.ACTIVITY_ID = A.ACTIVITY_ID ORDER BY A.ACTIVITY_ID ASC";
     $result = $db->execute($sql, array($user_id));
     $i = 0;
     $sub_sql = "SELECT TRANSLATION AS ACTIVITY_NAME " . "FROM TRANSLATION_LOCALE " . "WHERE TRANSLATION_ID=? AND LOCALE_ID=? {$limit_offset}";
     // maybe do left join at some point
     while ($activities[$i] = $this->db->fetchArray($result)) {
         $id = $activities[$i]['TRANSLATION_ID'];
         $result_sub = $db->execute($sub_sql, array($id, $locale_id));
         $translate = $db->fetchArray($result_sub);
         if ($translate) {
             $activities[$i]['ACTIVITY_NAME'] = $translate['ACTIVITY_NAME'];
         }
         if (!isset($activities[$i]['ACTIVITY_NAME']) || $activities[$i]['ACTIVITY_NAME'] == "") {
             $activities[$i]['ACTIVITY_NAME'] = $this->translateDb($activities[$i]['IDENTIFIER_STRING'], DEFAULT_LOCALE);
         }
         $i++;
     }
     unset($activities[$i]);
     //last one will be null
     return $activities;
 }
Пример #4
0
 /**
  * Parses from a string phrase representing a conjunctive query, a struct
  * consisting of the words keys searched for, the allowed and disallowed
  * phrases, the weight that should be put on these query results, and
  * which archive to use.
  *
  * @param string& $phrase string to extract struct from, if the phrase
  * semantics is guessed or an if condition is processed the value of
  * phrase will be altered. (Helps for feeding to network queries)
  * @param bool $guess_semantics whether to do query rewriting before parse
  * @return array struct representing the conjunctive query
  */
 function parseWordStructConjunctiveQuery(&$phrase, $guess_semantics = true)
 {
     $query = $phrase;
     $indent = "&nbsp;&nbsp;";
     $in2 = $indent . $indent;
     $in3 = $in2 . $indent;
     $in4 = $in2 . $in2;
     $phrase = " " . $phrase;
     if ($guess_semantics) {
         $phrase = $this->guessSemantics($phrase);
     }
     $phrase = $this->parseIfConditions($phrase);
     $phrase_string = $phrase;
     list($found_metas, $found_materialized_metas, $disallow_phrases, $phrase_string, $query_string, $index_name, $weight) = $this->extractMetaWordInfo($phrase);
     /*
        we search using the stemmed/char-grammed words, but we format
        snippets in the results by bolding either
     */
     $query_words = explode(" ", $query_string);
     //not stemmed
     if ($this->program_indicator) {
         $query_string = $query;
         $this->program_indicator = false;
     }
     $locale_tag = guessLocaleFromString($query_string);
     $quote_state = false;
     $phrase_parts = explode('"', $phrase_string);
     $base_words = array();
     $num_words = 0;
     $quote_positions = array();
     foreach ($phrase_parts as $phrase_part) {
         if (trim($phrase_part) == "") {
             $quote_state = $quote_state ? false : true;
             continue;
         }
         /*still use original phrase string here to handle
           acronyms abbreviations and the like that use periods */
         if ($quote_state) {
             $sub_parts = explode('*', $phrase_part);
             $first_part = true;
             $quote_position = array();
             foreach ($sub_parts as $sub_part) {
                 if (!$first_part) {
                     $quote_position["*{$num_words}"] = "*";
                 }
                 $new_words = PhraseParser::extractPhrases($sub_part, $locale_tag, $index_name, true);
                 $base_words = array_merge($base_words, $new_words);
                 foreach ($new_words as $new_word) {
                     $len = substr_count($new_word, " ") + 1;
                     $quote_position[$num_words] = $len;
                     $num_words++;
                 }
                 $first_part = false;
             }
             $quote_positions[] = $quote_position;
         } else {
             $new_words = PhraseParser::extractPhrases($phrase_part, $locale_tag, $index_name);
             if (strpos($new_words[0], " ") > 0 && $found_materialized_metas == array()) {
                 array_pop($new_words);
             }
             $base_words = array_merge($base_words, $new_words);
         }
         $num_words = count($base_words);
         $quote_state = $quote_state ? false : true;
     }
     //stemmed, if have stemmer
     $index_version = IndexManager::getVersion($index_name);
     $add_metas = $found_metas;
     if (count($base_words) > 0 && $index_version > 0) {
         $add_metas = array_diff($found_metas, $found_materialized_metas);
     }
     $words = array_merge($base_words, $add_metas);
     if (count($words) == 0 && count($disallow_phrases) > 0) {
         $words[] = "site:any";
     }
     if (QUERY_STATISTICS) {
         if (!isset($this->query_info['QUERY'])) {
             $this->query_info['QUERY'] = "";
         }
         $this->query_info['QUERY'] .= "{$in3}<i>Index</i>: " . $index_name . "<br />";
         $this->query_info['QUERY'] .= "{$in3}<i>LocaleTag</i>: " . $locale_tag . "<br />";
         $this->query_info['QUERY'] .= "{$in3}<i>Stemmed/Char-grammed Words</i>:<br />";
         foreach ($base_words as $word) {
             $this->query_info['QUERY'] .= "{$in4}{$word}<br />";
         }
         $this->query_info['QUERY'] .= "{$in3}<i>Meta Words</i>:<br />";
         foreach ($found_metas as $word) {
             $this->query_info['QUERY'] .= "{$in4}{$word}<br />";
         }
         $this->query_info['QUERY'] .= "{$in3}<i>Quoted Word Locs</i>:<br />";
         foreach ($quote_positions as $quote_position) {
             $this->query_info['QUERY'] .= "{$in4}(";
             $comma = "";
             foreach ($quote_position as $pos => $len) {
                 $this->query_info['QUERY'] .= "{$comma} {$pos} => {$len}";
                 $comma = ",";
             }
             $this->query_info['QUERY'] .= ")<br />";
         }
     }
     if (isset($words) && count($words) == 1 && count($disallow_phrases) < 1 && !strpos($words[0], " ")) {
         $phrase_string = $words[0];
         if ($index_version == 0) {
             $tmp_hash = allCrawlHashPaths($phrase_string);
             $tmp_hash = is_array($tmp_hash) ? $tmp_hash : array($tmp_hash);
             $phrase_hash = array_merge(array($tmp_hash), array(crawlHash($phrase_string)));
         } else {
             if ($found_materialized_metas == array()) {
                 $phrase_hash = allCrawlHashPaths($phrase_string);
             } else {
                 $phrase_hash = allCrawlHashPaths($phrase_string, $found_materialized_metas, PhraseParser::$materialized_metas);
             }
         }
         $word_struct = array("KEYS" => array($phrase_hash), "QUOTE_POSITIONS" => NULL, "DISALLOW_KEYS" => array(), "WEIGHT" => $weight, "INDEX_NAME" => $index_name);
     } else {
         //get a raw list of words and their hashes
         $hashes = array();
         $metas_accounted = false;
         $materialized_metas = array();
         foreach ($words as $word) {
             if (!$metas_accounted && substr_count($word, " ") == 0 && !in_array($word, $found_metas)) {
                 $metas_accounted = true;
                 $materialized_metas = $found_materialized_metas;
             }
             $tmp_hash = allCrawlHashPaths($word, $materialized_metas, PhraseParser::$materialized_metas);
             if ($index_version == 0) {
                 $tmp_hash = is_array($tmp_hash) ? $tmp_hash : array($tmp_hash);
                 $test = array_merge($tmp_hash, array(crawlHash($word)));
                 $word_keys[] = $test;
             } else {
                 $word_keys[] = $tmp_hash;
             }
         }
         if (!isset($word_keys) || count($word_keys) == 0) {
             $word_keys = NULL;
             $word_struct = NULL;
         }
         $disallow_keys = array();
         $num_disallow_keys = min(MAX_QUERY_TERMS, count($disallow_phrases));
         if ($num_disallow_keys > 0 && QUERY_STATISTICS) {
             $this->query_info['QUERY'] .= "{$in3}<i>Disallowed Words</i>:" . "<br />";
         }
         for ($i = 0; $i < $num_disallow_keys; $i++) {
             // check if disallowed is a meta word and stem or not stem
             if (mb_strstr($disallow_phrases[$i], ':') === false) {
                 $disallow_stem = PhraseParser::extractPhrases($disallow_phrases[$i], getLocaleTag());
                 //stemmed
             } else {
                 $disallow_stem[0] = $disallow_phrases[$i];
             }
             if (QUERY_STATISTICS) {
                 $this->query_info['QUERY'] .= "{$in4}{$disallow_stem[0]}" . "<br />";
             }
             $disallow_keys[] = crawlHashWord($disallow_stem[0]);
             if ($index_version == 0) {
                 $disallow_keys[] = crawlHash($word);
             }
         }
         if ($word_keys !== NULL) {
             $word_struct = array("KEYS" => $word_keys, "QUOTE_POSITIONS" => $quote_positions, "DISALLOW_KEYS" => $disallow_keys, "WEIGHT" => $weight, "INDEX_NAME" => $index_name);
         }
     }
     $pre_format_words = array();
     foreach ($base_words as $base_word) {
         $pre_format_words = array_merge($pre_format_words, explode(" * ", $base_word));
     }
     $pre_format_words = array_values(array_unique(array_merge($query_words, $pre_format_words)));
     $format_words = array();
     $count = count($pre_format_words);
     for ($i = 0; $i < $count; $i++) {
         $flag = true;
         if ($pre_format_words[$i] == "") {
             continue;
         }
         for ($j = 0; $j < $count; $j++) {
             if ($j == $i) {
                 continue;
             }
             $hay = mb_strtolower($pre_format_words[$j]);
             $needle = mb_strtolower($pre_format_words[$i]);
             if ($hay == $needle && $j > $i) {
                 continue;
             }
             if (mb_strstr($hay, $needle)) {
                 $flag = false;
                 break;
             }
         }
         if ($flag) {
             $format_words[] = $pre_format_words[$i];
         }
     }
     return array($word_struct, $format_words);
 }
Пример #5
0
/**
 * Attempts to guess the user's locale based on a string sample
 *
 * @param string $phrase_string used to make guess
 * @param string $locale_tag language tag to use if can't guess -- if not
 *     provided uses current locale's value
 * @param int threshold number of chars to guess a particular encoding
 * @return string IANA language tag of the guessed locale
 */
function guessLocaleFromString($phrase_string, $locale_tag = NULL)
{
    $query_string = $phrase_string;
    $locale_tag = $locale_tag == NULL ? getLocaleTag() : $locale_tag;
    $sub = PUNCT . "|[0-9]|\\s";
    $phrase_string = preg_replace('/' . $sub . '/u', "", $phrase_string);
    $phrase_string = mb_convert_encoding($phrase_string, "UTF-32", "UTF-8");
    $len = strlen($phrase_string);
    $guess['zh-CN'] = 0;
    $guess['ru'] = 0;
    $guess['he'] = 0;
    $guess['ar'] = 0;
    $guess['th'] = 0;
    $guess['ja'] = 0;
    $guess['ko'] = 0;
    $guess[$locale_tag] = 0;
    for ($i = 0; $i < $len; $i += 4) {
        $start = ord($phrase_string[$i + 2]);
        $next = ord($phrase_string[$i + 3]);
        if ($start >= 78 && $start <= 159) {
            $guess['zh-CN'] += 4;
        } else {
            if ($start == 4 || $start == 5 && $next < 48) {
                $guess['ru']++;
            } else {
                if ($start == 5 && $next >= 144) {
                    $guess['he'] += 2;
                } else {
                    if ($start >= 6 && $start <= 7) {
                        $guess['ar'] += 2;
                    } else {
                        if ($start == 14 && $next < 128) {
                            $guess['th'] += 2;
                        } else {
                            if ($start >= 48 && $start <= 49) {
                                $guess['ja'] += 3;
                            } else {
                                if ($start == 17 || $start >= 172 && $start < 215) {
                                    $guess['ko'] += 2;
                                } else {
                                    if ($start == 0 && $next < 128) {
                                        $guess[$locale_tag]++;
                                        // assume ascii is from $locale_tag
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    $num_points = $len / 4 - 1;
    //there will be a lead and tail space
    $max = $guess[$locale_tag];
    if ($num_points >= 0) {
        foreach ($guess as $tag => $cnt) {
            if ($cnt >= $num_points && $cnt > $max) {
                $locale_tag = $tag;
                $max = $cnt;
                break;
            }
        }
    }
    if ($locale_tag == 'en-US') {
        $locale_tag = checkQuery($query_string);
    }
    return $locale_tag;
}
Пример #6
0
 /**
  * Gets a list of activity ids, method names, and translated
  * name of each available activity
  *
  * @return array activities
  */
 function getActivityList()
 {
     $db = $this->db;
     $activities = array();
     $locale_tag = getLocaleTag();
     $sql = "SELECT LOCALE_ID FROM LOCALE " . "WHERE LOCALE_TAG = :locale_tag " . $db->limitOffset(1);
     $result = $db->execute($sql, array(":locale_tag" => $locale_tag));
     $row = $db->fetchArray($result);
     $locale_id = $row['LOCALE_ID'];
     $sql = "SELECT A.ACTIVITY_ID AS ACTIVITY_ID, " . "A.METHOD_NAME AS METHOD_NAME, " . " T.IDENTIFIER_STRING AS IDENTIFIER_STRING, " . " T.TRANSLATION_ID AS TRANSLATION_ID FROM " . " ACTIVITY A, TRANSLATION T WHERE  " . " T.TRANSLATION_ID = A.TRANSLATION_ID";
     $result = $db->execute($sql);
     $i = 0;
     $sub_sql = "SELECT TRANSLATION AS ACTIVITY_NAME " . "FROM TRANSLATION_LOCALE " . " WHERE TRANSLATION_ID=:id AND LOCALE_ID=:locale_id " . $db->limitOffset(1);
     // maybe do left join at some point
     while ($activities[$i] = $db->fetchArray($result)) {
         $id = $activities[$i]['TRANSLATION_ID'];
         $result_sub = $db->execute($sub_sql, array(":id" => $id, ":locale_id" => $locale_id));
         $translate = $db->fetchArray($result_sub);
         if ($translate) {
             $activities[$i]['ACTIVITY_NAME'] = $translate['ACTIVITY_NAME'];
         } else {
             $activities[$i]['ACTIVITY_NAME'] = $this->translateDb($activities[$i]['IDENTIFIER_STRING'], DEFAULT_LOCALE);
         }
         $i++;
     }
     unset($activities[$i]);
     //last one will be null
     return $activities;
 }
Пример #7
0
    /**
     * Handles requests to reading, editing, viewing history, reverting, etc
     * wiki pages
     * @return $data an associative array of form variables used to draw
     *     the appropriate wiki page
     */
    function wiki()
    {
        $parent = $this->parent;
        $controller_name = get_class($parent) == "AdminController" ? "admin" : "group";
        $data = array();
        $data["CONTROLLER"] = $controller_name;
        $other_controller_name = get_class($parent) == "AdminController" ? "group" : "admin";
        $data["ELEMENT"] = "wiki";
        $data["VIEW"] = "wiki";
        $data["SCRIPT"] = "";
        $data["INCLUDE_STYLES"] = array("editor");
        $group_model = $parent->model("group");
        $locale_tag = getLocaleTag();
        $data['CURRENT_LOCALE_TAG'] = $locale_tag;
        if (isset($_SESSION['USER_ID'])) {
            $user_id = $_SESSION['USER_ID'];
            $data['ADMIN'] = 1;
        } else {
            $user_id = PUBLIC_USER_ID;
        }
        $search_translation = tl('social_component_search');
        $search_form = <<<EOD
<form method="get" class="search-box \$2-search-box" >
<input type='hidden' name="its" value='\$1' />
<input type='text'  name='q'  value="" placeholder='\$3'
    title='\$3' class='search-input' />
<button type="submit" class='search-button'><img
    src='./resources/search-button.png'  alt='{$search_translation}'/></button>
</form>
EOD;
        $additional_substitutions[] = array('/{{\\s*search\\s*:\\s*(.+?)\\s*\\|' . '\\s*size\\s*:\\s*(.+?)\\s*\\|\\s*placeholder\\s*:\\s*(.+?)}}/', $search_form);
        $clean_array = array("group_id" => "int", "page_name" => "string", "page" => "string", "edit_reason" => "string", "filter" => 'string', "limit" => 'int', "num" => 'int', "page_id" => 'int', "show" => 'int', "diff" => 'int', "diff1" => 'int', "diff2" => 'int', "revert" => 'int');
        $strings_array = array("page_name" => TITLE_LEN, "page" => MAX_GROUP_PAGE_LEN, "edit_reason" => SHORT_TITLE_LEN, "filter" => SHORT_TITLE_LEN);
        $last_care_missing = 2;
        $missing_fields = false;
        $i = 0;
        if ($user_id == PUBLIC_USER_ID) {
            $_SESSION['LAST_ACTIVITY']['a'] = 'wiki';
        } else {
            unset($_SESSION['LAST_ACTIVITY']);
        }
        foreach ($clean_array as $field => $type) {
            if (isset($_REQUEST[$field])) {
                $tmp = $parent->clean($_REQUEST[$field], $type);
                if (isset($strings_array[$field])) {
                    $tmp = substr($tmp, 0, $strings_array[$field]);
                }
                if ($field == "page_name") {
                    $tmp = str_replace(" ", "_", $tmp);
                }
                ${$field} = $tmp;
                if ($user_id == PUBLIC_USER_ID) {
                    $_SESSION['LAST_ACTIVITY'][$field] = $tmp;
                }
            } else {
                if ($i < $last_care_missing) {
                    ${$field} = false;
                    $missing_fields = true;
                }
            }
            $i++;
        }
        if (isset($_REQUEST['group_id']) && $_REQUEST['group_id']) {
            $group_id = $parent->clean($_REQUEST['group_id'], "int");
        } else {
            if (isset($page_id)) {
                $page_info = $group_model->getPageInfoByPageId($page_id);
                if (isset($page_info["GROUP_ID"])) {
                    $group_id = $page_info["GROUP_ID"];
                    unset($page_info);
                } else {
                    $group_id = PUBLIC_GROUP_ID;
                }
            } else {
                $group_id = PUBLIC_GROUP_ID;
            }
        }
        $group = $group_model->getGroupById($group_id, $user_id);
        $data["CAN_EDIT"] = false;
        if (isset($_REQUEST['c']) && $_REQUEST['c'] == "api") {
            $data['MODE'] = 'api';
            $data['VIEW'] = 'api';
        } else {
            $data["MODE"] = "read";
        }
        if (!$group) {
            if ($data['MODE'] !== 'api') {
                $parent->redirectWithMessage(tl("group_controller_no_group_access"));
            } else {
                $data['errors'] = array();
                $data['errors'][] = tl("group_controller_no_group_access");
            }
            $group_id = PUBLIC_GROUP_ID;
            $group = $group_model->getGroupById($group_id, $user_id);
        } else {
            if ($group["OWNER_ID"] == $user_id || $group["STATUS"] == ACTIVE_STATUS && $group["MEMBER_ACCESS"] == GROUP_READ_WIKI) {
                $data["CAN_EDIT"] = true;
            }
        }
        $page_defaults = array('page_type' => 'standard', 'page_alias' => '', 'page_border' => 'solid', 'toc' => true, 'title' => '', 'author' => '', 'robots' => '', 'description' => '', 'page_header' => '', 'page_footer' => '');
        $data['page_types'] = array("standard" => tl('social_component_standard_page'), "page_alias" => tl('social_component_page_alias'), "media_list" => tl('social_component_media_list'), "presentation" => tl('social_component_presentation'));
        $data['page_borders'] = array("solid-border" => tl('social_component_solid'), "dashed-border" => tl('social_component_dashed'), "none" => tl('social_component_none'));
        if ($group_id == PUBLIC_GROUP_ID) {
            $read_address = "[{controller_and_page}]";
        } else {
            $read_address = "?c=[{controller}]&amp;a=wiki&amp;" . "arg=read&amp;group_id={$group_id}&amp;page_name=";
        }
        if (isset($_REQUEST["arg"])) {
            switch ($_REQUEST["arg"]) {
                case "edit":
                    if (!$data["CAN_EDIT"]) {
                        continue;
                    }
                    if (isset($_REQUEST['caret']) && isset($_REQUEST['scroll_top']) && !isset($page)) {
                        $caret = $parent->clean($_REQUEST['caret'], 'int');
                        $scroll_top = $parent->clean($_REQUEST['scroll_top'], 'int');
                        $data['SCRIPT'] .= "wiki = elt('wiki-page');" . "if (wiki.setSelectionRange) { " . "   wiki.focus();" . "   wiki.setSelectionRange({$caret}, {$caret});" . "} " . "wiki.scrollTop = {$scroll_top};";
                    }
                    if (isset($page)) {
                        $data["MODE"] = "read";
                    } else {
                        $data["MODE"] = "edit";
                    }
                    $page_info = $group_model->getPageInfoByName($group_id, $page_name, $locale_tag, 'resources');
                    /* if page not yet created than $page_info will be null
                         so in the below $page_info['ID'] won't be set.
                       */
                    if ($missing_fields) {
                        $parent->redirectWithMessage(tl("group_controller_missing_fields"));
                    } else {
                        if (!$missing_fields && isset($page)) {
                            $action = "wikiupdate_" . "group=" . $group_id . "&page=" . $page_name;
                            if (!$parent->checkCSRFTime(CSRF_TOKEN, $action)) {
                                $data['SCRIPT'] .= "doMessage('<h1 class=\"red\" >" . tl('social_component_wiki_edited_elsewhere') . "</h1>');";
                                break;
                            }
                            $write_head = false;
                            $head_vars = array();
                            $page_types = array_keys($data['page_types']);
                            $page_borders = array_keys($data['page_borders']);
                            foreach ($page_defaults as $key => $default) {
                                $head_vars[$key] = $default;
                                if (isset($_REQUEST[$key])) {
                                    $head_vars[$key] = trim($parent->clean($_REQUEST[$key], "string"));
                                    if ($key == 'page_type') {
                                        if (!in_array($head_vars[$key], $page_types)) {
                                            $head_vars[$key] = $default;
                                        }
                                    } else {
                                        if ($key == 'page_borders') {
                                            if (!in_array($head_vars[$key], $page_types)) {
                                                $head_vars[$key] = $default;
                                            }
                                        } else {
                                            $head_vars[$key] = trim(preg_replace("/\n+/", "\n", $head_vars[$key]));
                                        }
                                    }
                                    if ($head_vars[$key] != $default) {
                                        $write_head = true;
                                    }
                                } else {
                                    if ($key == 'toc') {
                                        if (isset($_REQUEST['title'])) {
                                            $head_vars[$key] = false;
                                        } else {
                                            $head_vars[$key] == true;
                                        }
                                    }
                                }
                            }
                            if ($write_head) {
                                $head_string = "";
                                foreach ($page_defaults as $key => $default) {
                                    $head_string .= $key . "=" . $head_vars[$key] . "\n\n";
                                }
                                $page = $head_string . "END_HEAD_VARS" . $page;
                            }
                            $group_model->setPageName($user_id, $group_id, $page_name, $page, $locale_tag, $edit_reason, tl('group_controller_page_created', $page_name), tl('group_controller_page_discuss_here'), $read_address, $additional_substitutions);
                            $parent->redirectWithMessage(tl("group_controller_page_saved"), array('arg', 'page_name', 'settings', 'caret', 'scroll_top', 'back_params'));
                        } else {
                            if (!$missing_fields && isset($_FILES['page_resource']['name']) && $_FILES['page_resource']['name'] != "") {
                                if (!isset($page_info['ID'])) {
                                    $parent->redirectWithMessage(tl('social_component_resource_save_first'), array('arg', 'page_name', 'settings', 'caret', 'scroll_top'));
                                } else {
                                    $upload_parts = array('name', 'type', 'tmp_name');
                                    $file = array();
                                    $upload_okay = true;
                                    foreach ($upload_parts as $part) {
                                        if (isset($_FILES['page_resource'][$part])) {
                                            $file[$part] = $parent->clean($_FILES['page_resource'][$part], 'string');
                                        } else {
                                            $upload_okay = false;
                                            break;
                                        }
                                    }
                                }
                                if ($upload_okay) {
                                    $group_model->copyFileToGroupPageResource($file['tmp_name'], $file['name'], $file['type'], $group_id, $page_info['ID']);
                                    $parent->redirectWithMessage(tl('social_component_resource_uploaded'), array('arg', 'page_name', 'settings', 'caret', 'scroll_top'));
                                } else {
                                    $parent->redirectWithMessage(tl('social_component_upload_error'), array('arg', 'page_name', 'settings', 'caret', 'scroll_top'));
                                }
                            } else {
                                if (!$missing_fields && isset($_REQUEST['delete'])) {
                                    $resource_name = $parent->clean($_REQUEST['delete'], "string");
                                    if (isset($page_info['ID']) && $group_model->deleteResource($resource_name, $group_id, $page_info['ID'])) {
                                        $parent->redirectWithMessage(tl('social_component_resource_deleted'), array('arg', 'page_name', 'settings', 'caret', 'scroll_top'));
                                    } else {
                                        $parent->redirectWithMessage(tl('social_component_resource_not_deleted'), array('arg', 'page_name', 'settings', 'caret', 'scroll_top'));
                                    }
                                } else {
                                    if (!$missing_fields && isset($_REQUEST['new_resource_name']) && isset($_REQUEST['old_resource_name'])) {
                                        $old_resource_name = $parent->clean($_REQUEST['old_resource_name'], "string");
                                        $new_resource_name = $parent->clean($_REQUEST['new_resource_name'], "string");
                                        if (isset($page_info['ID']) && $group_model->renameResource($old_resource_name, $new_resource_name, $group_id, $page_info['ID'])) {
                                            $parent->redirectWithMessage(tl('social_component_resource_renamed'), array('arg', 'page_name', 'settings', 'caret', 'scroll_top'));
                                        } else {
                                            $parent->redirectWithMessage(tl('social_component_resource_not_renamed'), array('arg', 'page_name', 'settings', 'caret', 'scroll_top'));
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (isset($page_info['ID'])) {
                        $data['RESOURCES_INFO'] = $group_model->getGroupPageResourceUrls($group_id, $page_info['ID']);
                    } else {
                        $data['RESOURCES_INFO'] = array();
                    }
                    break;
                case "history":
                    if (!$data["CAN_EDIT"] || !isset($page_id) || !$page_id) {
                        continue;
                    }
                    $data["MODE"] = "history";
                    $data["PAGE_NAME"] = "history";
                    $limit = isset($limit) ? $limit : 0;
                    $num = isset($_SESSION["MAX_PAGES_TO_SHOW"]) ? $_SESSION["MAX_PAGES_TO_SHOW"] : DEFAULT_ADMIN_PAGING_NUM;
                    $default_history = true;
                    if (isset($show)) {
                        $page_info = $group_model->getHistoryPage($page_id, $show);
                        if ($page_info) {
                            $data["MODE"] = "show";
                            $default_history = false;
                            $data["PAGE_NAME"] = $page_info["PAGE_NAME"];
                            $parser = new WikiParser($read_address, $additional_substitutions);
                            $parsed_page = $parser->parse($page_info["PAGE"]);
                            $data["PAGE_ID"] = $page_id;
                            $data[CSRF_TOKEN] = $parent->generateCSRFToken($user_id);
                            $history_link = "?c={$data['CONTROLLER']}&amp;" . "a=wiki&amp;" . CSRF_TOKEN . '=' . $data[CSRF_TOKEN] . '&amp;arg=history&amp;page_id=' . $data['PAGE_ID'];
                            $data["PAGE"] = "<div>&nbsp;</div>" . "<div class='black-box back-dark-gray'>" . "<div class='float-opposite'>" . "<a href='{$history_link}'>" . tl("group_controller_back") . "</a></div>" . tl("group_controller_history_page", $data["PAGE_NAME"], date("c", $show)) . "</div>" . $parsed_page;
                            $data["DISCUSS_THREAD"] = $page_info["DISCUSS_THREAD"];
                        }
                    } else {
                        if (isset($diff) && $diff && isset($diff1) && isset($diff2)) {
                            $page_info1 = $group_model->getHistoryPage($page_id, $diff1);
                            $page_info2 = $group_model->getHistoryPage($page_id, $diff2);
                            $data["MODE"] = "diff";
                            $default_history = false;
                            $data["PAGE_NAME"] = $page_info2["PAGE_NAME"];
                            $data["PAGE_ID"] = $page_id;
                            $data[CSRF_TOKEN] = $parent->generateCSRFToken($user_id);
                            $history_link = "?c={$data['CONTROLLER']}" . "&amp;a=wiki&amp;" . CSRF_TOKEN . '=' . $data[CSRF_TOKEN] . '&amp;arg=history&amp;page_id=' . $data['PAGE_ID'];
                            $out_diff = "<div>--- {$data["PAGE_NAME"]}\t" . "''{$diff1}''\n";
                            $out_diff .= "<div>+++ {$data["PAGE_NAME"]}\t" . "''{$diff2}''\n";
                            $out_diff .= diff($page_info1["PAGE"], $page_info2["PAGE"], true);
                            $data["PAGE"] = "<div>&nbsp;</div>" . "<div class='black-box back-dark-gray'>" . "<div class='float-opposite'>" . "<a href='{$history_link}'>" . tl("group_controller_back") . "</a></div>" . tl("group_controller_diff_page", $data["PAGE_NAME"], date("c", $diff1), date("c", $diff2)) . "</div>" . "{$out_diff}";
                        } else {
                            if (isset($revert)) {
                                $page_info = $group_model->getHistoryPage($page_id, $revert);
                                if ($page_info) {
                                    $action = "wikiupdate_" . "group=" . $group_id . "&page=" . $page_info["PAGE_NAME"];
                                    if (!$parent->checkCSRFTime(CSRF_TOKEN, $action)) {
                                        $data['SCRIPT'] .= "doMessage('<h1 class=\"red\" >" . tl('social_component_wiki_edited_elsewhere') . "</h1>');";
                                        break;
                                    }
                                    $group_model->setPageName($user_id, $group_id, $page_info["PAGE_NAME"], $page_info["PAGE"], $locale_tag, tl('group_controller_page_revert_to', date('c', $revert)), "", "", $read_address, $additional_substitutions);
                                    $parent->redirectWithMessage(tl("group_controller_page_reverted"), array('arg', 'page_name', 'page_id'));
                                } else {
                                    $parent->redirectWithMessage(tl("group_controller_revert_error"), array('arg', 'page_name', 'page_id'));
                                }
                            }
                        }
                    }
                    if ($default_history) {
                        $data["LIMIT"] = $limit;
                        $data["RESULTS_PER_PAGE"] = $num;
                        list($data["TOTAL_ROWS"], $data["PAGE_NAME"], $data["HISTORY"]) = $group_model->getPageHistoryList($page_id, $limit, $num);
                        if (!isset($diff1) || !isset($diff2)) {
                            $data['diff1'] = $data["HISTORY"][0]["PUBDATE"];
                            $data['diff2'] = $data["HISTORY"][0]["PUBDATE"];
                            if (count($data["HISTORY"]) > 1) {
                                $data['diff2'] = $data["HISTORY"][1]["PUBDATE"];
                            }
                        }
                    }
                    $data['page_id'] = $page_id;
                    break;
                case "media":
                    if (!isset($page_id) || !isset($_REQUEST['n'])) {
                        break;
                    }
                    $media_name = $parent->clean($_REQUEST['n'], "string");
                    $page_info = $group_model->getPageInfoByPageId($page_id);
                    $data['PAGE_NAME'] = $page_info['PAGE_NAME'];
                    $name_parts = pathinfo($media_name);
                    $file_name = $name_parts['filename'];
                    $data['MEDIA_NAME'] = $media_name;
                    $page_string = "((resource:{$media_name}|{$file_name}))";
                    $data["PAGE"] = $group_model->insertResourcesParsePage($group_id, $page_id, $locale_tag, $page_string);
                    $data["PAGE_ID"] = $page_id;
                    break;
                case "pages":
                    $data["MODE"] = "pages";
                    $limit = isset($limit) ? $limit : 0;
                    $num = isset($_SESSION["MAX_PAGES_TO_SHOW"]) ? $_SESSION["MAX_PAGES_TO_SHOW"] : DEFAULT_ADMIN_PAGING_NUM;
                    if (!isset($filter)) {
                        $filter = "";
                    }
                    if (isset($page_name)) {
                        $data['PAGE_NAME'] = $page_name;
                    }
                    $data["LIMIT"] = $limit;
                    $data["RESULTS_PER_PAGE"] = $num;
                    $data["FILTER"] = $filter;
                    $search_page_info = false;
                    if ($filter != "") {
                        $search_page_info = $group_model->getPageInfoByName($group_id, $filter, $locale_tag, "read");
                    }
                    if (!$search_page_info) {
                        list($data["TOTAL_ROWS"], $data["PAGES"]) = $group_model->getPageList($group_id, $locale_tag, $filter, $limit, $num);
                        if ($data["TOTAL_ROWS"] == 0 && $filter != "") {
                            $data["MODE"] = "read";
                            $page_name = $filter;
                        }
                    } else {
                        $data["MODE"] = "read";
                        $page_name = $filter;
                    }
                    break;
            }
        }
        if (!$page_name) {
            $page_name = tl('group_controller_main');
        }
        $data["GROUP"] = $group;
        if (in_array($data["MODE"], array("read", "edit", "media", "api"))) {
            if (!isset($data["PAGE"]) || !$data['PAGE']) {
                $data["PAGE_NAME"] = $page_name;
                if (isset($search_page_info) && $search_page_info) {
                    $page_info = $search_page_info;
                } else {
                    $page_info = $group_model->getPageInfoByName($group_id, $page_name, $locale_tag, $data["MODE"]);
                }
                $data["PAGE"] = $page_info["PAGE"];
                $data["PAGE_ID"] = $page_info["ID"];
                $data["DISCUSS_THREAD"] = $page_info["DISCUSS_THREAD"];
            }
            if ((!isset($data["PAGE"]) || !$data["PAGE"]) && $locale_tag != DEFAULT_LOCALE) {
                //fallback to default locale for translation
                $page_info = $group_model->getPageInfoByName($group_id, $page_name, DEFAULT_LOCALE, $data["MODE"]);
                $data["PAGE"] = $page_info["PAGE"];
                $data["PAGE_ID"] = $page_info["ID"];
                $data["DISCUSS_THREAD"] = $page_info["DISCUSS_THREAD"];
            }
            $view = $parent->view($data['VIEW']);
            $parent->parsePageHeadVars($view, $data["PAGE_ID"], $data["PAGE"]);
            $data["PAGE"] = $this->dynamicSubstitutions($group_id, $data, $view->page_objects[$data["PAGE_ID"]]);
            $data["HEAD"] = $view->head_objects[$data["PAGE_ID"]];
            if (isset($data["HEAD"]['page_type']) && $data["HEAD"]['page_type'] == 'page_alias' && $data["HEAD"]['page_alias'] != '' && $data['MODE'] == "read" && !isset($_REQUEST['noredirect'])) {
                $_REQUEST['page_name'] = $data["HEAD"]['page_alias'];
                $parent->redirectWithMessage("", array('page_name'));
            }
            if ($data['MODE'] == "read" && isset($data["HEAD"]['page_header']) && $data["HEAD"]['page_type'] != 'presentation') {
                $page_header = $group_model->getPageInfoByName($group_id, $data["HEAD"]['page_header'], $locale_tag, $data["MODE"]);
                if (isset($page_header['PAGE'])) {
                    $header_parts = explode("END_HEAD_VARS", $page_header['PAGE']);
                }
                $data["PAGE_HEADER"] = isset($header_parts[1]) ? $header_parts[1] : "" . $page_header['PAGE'];
                $data["PAGE_HEADER"] = $this->dynamicSubstitutions($group_id, $data, $data["PAGE_HEADER"]);
            }
            if ($data['MODE'] == "read" && isset($data["HEAD"]['page_footer']) && $data["HEAD"]['page_type'] != 'presentation') {
                $page_footer = $group_model->getPageInfoByName($group_id, $data["HEAD"]['page_footer'], $locale_tag, $data["MODE"]);
                if (isset($page_footer['PAGE'])) {
                    $footer_parts = explode("END_HEAD_VARS", $page_footer['PAGE']);
                }
                $data['PAGE_FOOTER'] = isset($footer_parts[1]) ? $footer_parts[1] : "" . $page_footer['PAGE'];
                $data["PAGE_FOOTER"] = $this->dynamicSubstitutions($group_id, $data, $data["PAGE_FOOTER"]);
            }
            if ($data['MODE'] == "read" && strpos($data["PAGE"], "`") !== false) {
                if (!isset($data["INCLUDE_SCRIPTS"])) {
                    $data["INCLUDE_SCRIPTS"] = array();
                }
                $data["INCLUDE_SCRIPTS"][] = "math";
            }
            if ($data['MODE'] == "read" && isset($data["HEAD"]['page_type'])) {
                if ($data["HEAD"]['page_type'] == 'media_list') {
                    $data['RESOURCES_INFO'] = $group_model->getGroupPageResourceUrls($group_id, $data['PAGE_ID']);
                }
                if ($data["HEAD"]['page_type'] == 'presentation' && $data['CONTROLLER'] == 'group') {
                    $data['page_type'] = 'presentation';
                    $data['INCLUDE_SCRIPTS'][] = "slidy";
                    $data['INCLUDE_STYLES'][] = "slidy";
                }
            }
            if ($data['MODE'] == "edit") {
                foreach ($page_defaults as $key => $default) {
                    $data[$key] = $default;
                    if (isset($data["HEAD"][$key])) {
                        $data[$key] = $data["HEAD"][$key];
                    }
                }
                $data['settings'] = "false";
                if (isset($_REQUEST['settings']) && $_REQUEST['settings'] == 'true') {
                    $data['settings'] = "true";
                }
                $data['current_page_type'] = $data["page_type"];
                $data['SCRIPT'] .= <<<EOD
                setDisplay('page-settings', {$data['settings']});
                function toggleSettings()
                {
                    var settings = elt('p-settings');
                    settings.value = (settings.value =='true')
                        ? 'false' : 'true';
                    var value = (settings.value == 'true') ? true : false;
                    setDisplay('page-settings', value);
                    var page_type = elt("page-type");
                    var cur_type = page_type.options[
                        page_type.selectedIndex].value;
                    if(cur_type == "media_list") {
                        setDisplay('save-container', value);
                    }
                }
                ptype = document.getElementById("page-type");
                is_media_list = ('media_list'=='{$data['current_page_type']}');
                is_settings = {$data['settings']};
                is_page_alias = ('page_alias'=='{$data['current_page_type']}');
                setDisplay('page-settings', is_settings || is_page_alias);
                setDisplay("media-list-page", is_media_list && !is_page_alias);
                setDisplay("page-container", !is_media_list && !is_page_alias);
                setDisplay("non-alias-type", !is_page_alias);
                setDisplay("alias-type", is_page_alias);
                setDisplay('save-container', !is_media_list || is_settings);
                setDisplay("toggle-settings", !is_page_alias, "inline");
                setDisplay("page-resources", !is_page_alias);
                ptype.onchange = function() {
                    var cur_type = ptype.options[ptype.selectedIndex].value;
                    if(cur_type == "media_list") {
                        setDisplay("media-list-page", true, "inline");
                        setDisplay("page-container", false);
                        setDisplay("toggle-settings", true);
                        setDisplay("non-alias-type", true);
                        setDisplay("alias-type", false);
                        setDisplay("page-resources", true);
                    } else if(cur_type == "page_alias") {
                        setDisplay("toggle-settings", false);
                        setDisplay("media-list-page", false);
                        setDisplay("page-container", false);
                        setDisplay("non-alias-type", false);
                        setDisplay("alias-type", true);
                        setDisplay("page-resources", false);
                    } else {
                        setDisplay("page-container", true);
                        setDisplay("media-list-page", false);
                        setDisplay("toggle-settings", true, "inline");
                        setDisplay("non-alias-type", true);
                        setDisplay("alias-type", false);
                        setDisplay("page-resources", true);
                    }
                }
EOD;
                $this->initializeWikiEditor($data);
            }
        }
        /** Check if back params need to be set. Set them if required.
         * the back params are usually sent when the wiki action is initiated
         * from within an open help article.
         */
        $data["OTHER_BACK_URL"] = "";
        if (isset($_REQUEST['back_params']) && (isset($_REQUEST['arg']) && in_array($parent->clean($_REQUEST['arg'], "string"), array('edit', 'read')) || isset($_REQUEST['page_name']))) {
            $back_params_cleaned = $_REQUEST['back_params'];
            array_walk($back_params_cleaned, array($parent, 'clean'));
            foreach ($back_params_cleaned as $back_param_key => $back_param_value) {
                $data['BACK_PARAMS']["back_params[{$back_param_key}]"] = $back_param_value;
                $data["OTHER_BACK_URL"] .= "&amp;back_params[{$back_param_key}]" . "=" . $back_param_value;
            }
            $data['BACK_URL'] = http_build_query($back_params_cleaned);
        }
        return $data;
    }
Пример #8
0
    /**
     * Responsible for handling admin request related to the configure activity
     *
     * The configure activity allows a user to set the work directory for
     * storing data local to this SeekQuarry/Yioop instance. It also allows one
     * to set the default language of the installation, dbms info, robot info,
     * test info, as well as which machine acts as the queue server.
     *
     * @return array $data fields for available language, dbms, etc as well as
     *     results of processing sub activity if any
     */
    function configure()
    {
        $parent = $this->parent;
        $profile_model = $parent->model("profile");
        $group_model = $parent->model("group");
        $data = array();
        $profile = array();
        $data['SYSTEM_CHECK'] = $this->systemCheck();
        $languages = $parent->model("locale")->getLocaleList();
        foreach ($languages as $language) {
            $data['LANGUAGES'][$language['LOCALE_TAG']] = $language['LOCALE_NAME'];
        }
        if (isset($_REQUEST['lang']) && $_REQUEST['lang']) {
            $data['lang'] = $parent->clean($_REQUEST['lang'], "string");
            $profile['DEFAULT_LOCALE'] = $data['lang'];
            setLocaleObject($data['lang']);
        }
        $data["ELEMENT"] = "configure";
        $data['SCRIPT'] = "";
        $data['PROFILE'] = false;
        if (isset($_REQUEST['WORK_DIRECTORY']) || defined('WORK_DIRECTORY') && defined('FIX_NAME_SERVER') && FIX_NAME_SERVER) {
            if (defined('WORK_DIRECTORY') && defined('FIX_NAME_SERVER') && FIX_NAME_SERVER && !isset($_REQUEST['WORK_DIRECTORY'])) {
                $_REQUEST['WORK_DIRECTORY'] = WORK_DIRECTORY;
                $_REQUEST['arg'] = "directory";
                @unlink($_REQUEST['WORK_DIRECTORY'] . "/profile.php");
            }
            $dir = $parent->clean($_REQUEST['WORK_DIRECTORY'], "string");
            $data['PROFILE'] = true;
            if (strstr(PHP_OS, "WIN")) {
                //convert to forward slashes so consistent with rest of code
                $dir = str_replace("\\", "/", $dir);
                if ($dir[0] != "/" && $dir[1] != ":") {
                    $data['PROFILE'] = false;
                }
            } else {
                if ($dir[0] != "/") {
                    $data['PROFILE'] = false;
                }
            }
            if ($data['PROFILE'] == false) {
                $data["MESSAGE"] = tl('system_component_configure_use_absolute_path');
                $data['SCRIPT'] .= "doMessage('<h1 class=\"red\" >" . $data["MESSAGE"] . "</h1>');" . "setTimeout('window.location.href= " . "window.location.href', 3000);";
                $data['WORK_DIRECTORY'] = $dir;
                return $data;
            }
            if (strstr($dir . "/", BASE_DIR . "/")) {
                $data['PROFILE'] = false;
                $data["MESSAGE"] = tl('system_component_configure_configure_diff_base_dir');
                $data['SCRIPT'] .= "doMessage('<h1 class=\"red\" >" . $data["MESSAGE"] . "</h1>');" . "setTimeout('window.location.href= " . "window.location.href', 3000);";
                $data['WORK_DIRECTORY'] = $dir;
                return $data;
            }
            $data['WORK_DIRECTORY'] = $dir;
        } else {
            if (defined("WORK_DIRECTORY") && strlen(WORK_DIRECTORY) > 0 && strcmp(realpath(WORK_DIRECTORY), realpath(BASE_DIR)) != 0 && (is_dir(WORK_DIRECTORY) || is_dir(WORK_DIRECTORY . "../"))) {
                $data['WORK_DIRECTORY'] = WORK_DIRECTORY;
                $data['PROFILE'] = true;
            }
        }
        $arg = "";
        if (isset($_REQUEST['arg'])) {
            $arg = $_REQUEST['arg'];
        }
        switch ($arg) {
            case "directory":
                if (!isset($data['WORK_DIRECTORY'])) {
                    break;
                }
                if ($data['PROFILE'] && file_exists($data['WORK_DIRECTORY'] . "/profile.php")) {
                    $data = array_merge($data, $profile_model->getProfile($data['WORK_DIRECTORY']));
                    $profile_model->setWorkDirectoryConfigFile($data['WORK_DIRECTORY']);
                    $data["MESSAGE"] = tl('system_component_configure_work_dir_set');
                    $data['SCRIPT'] .= "doMessage('<h1 class=\"red\" >" . $data["MESSAGE"] . "</h1>');setTimeout(" . "'window.location.href=window.location.href', 3000);";
                } else {
                    if ($data['PROFILE'] && strlen($data['WORK_DIRECTORY']) > 0) {
                        if ($profile_model->makeWorkDirectory($data['WORK_DIRECTORY'])) {
                            $profile['DBMS'] = 'sqlite3';
                            $data['DBMS'] = 'sqlite3';
                            $profile['DB_NAME'] = 'default';
                            $data['DB_NAME'] = 'default';
                            $profile['USER_AGENT_SHORT'] = tl('system_component_name_your_bot');
                            $data['USER_AGENT_SHORT'] = $profile['USER_AGENT_SHORT'];
                            $uri = UrlParser::getPath($_SERVER['REQUEST_URI']);
                            $http = isset($_SERVER['HTTPS']) ? "https://" : "http://";
                            $profile['NAME_SERVER'] = $http . $_SERVER['SERVER_NAME'] . $uri;
                            $data['NAME_SERVER'] = $profile['NAME_SERVER'];
                            $profile['AUTH_KEY'] = crawlHash($data['WORK_DIRECTORY'] . time());
                            $data['AUTH_KEY'] = $profile['AUTH_KEY'];
                            $profile['FIAT_SHAMIR_MODULUS'] = generateFiatShamirModulus();
                            $robot_instance = str_replace(".", "_", $_SERVER['SERVER_NAME']) . "-" . time();
                            $profile['ROBOT_INSTANCE'] = $robot_instance;
                            $data['ROBOT_INSTANCE'] = $profile['ROBOT_INSTANCE'];
                            if ($profile_model->updateProfile($data['WORK_DIRECTORY'], array(), $profile)) {
                                if (defined('WORK_DIRECTORY') && $data['WORK_DIRECTORY'] == WORK_DIRECTORY || $profile_model->setWorkDirectoryConfigFile($data['WORK_DIRECTORY'])) {
                                    $data["MESSAGE"] = tl('system_component_configure_work_profile_made');
                                    $data['SCRIPT'] .= "doMessage('<h1 class=\"red\" >" . $data["MESSAGE"] . "</h1>');" . "setTimeout('window.location.href= " . "window.location.href', 3000);";
                                    $data = array_merge($data, $profile_model->getProfile($data['WORK_DIRECTORY']));
                                    $data['PROFILE'] = true;
                                } else {
                                    $data['PROFILE'] = false;
                                    $data["MESSAGE"] = tl('system_component_configure_no_set_config');
                                    $data['SCRIPT'] .= "doMessage('<h1 class=\"red\" >" . $data["MESSAGE"] . "</h1>');" . "setTimeout('window.location.href= " . "window.location.href', 3000);";
                                }
                            } else {
                                $profile_model->setWorkDirectoryConfigFile($data['WORK_DIRECTORY']);
                                $data['PROFILE'] = false;
                                $data["MESSAGE"] = tl('system_component_configure_no_create_profile');
                                $data['SCRIPT'] .= "doMessage('<h1 class=\"red\" >" . $data["MESSAGE"] . "</h1>'); setTimeout('window.location.href=" . "window.location.href', 3000);";
                            }
                        } else {
                            $profile_model->setWorkDirectoryConfigFile($data['WORK_DIRECTORY']);
                            $data["MESSAGE"] = tl('system_component_configure_work_dir_invalid');
                            $data['SCRIPT'] .= "doMessage('<h1 class=\"red\" >" . $data["MESSAGE"] . "</h1>');" . "setTimeout('window.location.href=" . "window.location.href', 3000);";
                            $data['PROFILE'] = false;
                        }
                    } else {
                        $profile_model->setWorkDirectoryConfigFile($data['WORK_DIRECTORY']);
                        $data["MESSAGE"] = tl('system_component_configure_work_dir_invalid');
                        $data['SCRIPT'] .= "doMessage('<h1 class=\"red\" >" . $data["MESSAGE"] . "</h1>');" . "setTimeout('window.location.href=" . "window.location.href', 3000);";
                        $data['PROFILE'] = false;
                    }
                }
                break;
            case "profile":
                $parent->updateProfileFields($data, $profile, array('WEB_ACCESS', 'RSS_ACCESS', 'API_ACCESS', 'LANDING_PAGE'));
                $data['DEBUG_LEVEL'] = 0;
                $data['DEBUG_LEVEL'] |= isset($_REQUEST["ERROR_INFO"]) ? ERROR_INFO : 0;
                $data['DEBUG_LEVEL'] |= isset($_REQUEST["QUERY_INFO"]) ? QUERY_INFO : 0;
                $data['DEBUG_LEVEL'] |= isset($_REQUEST["TEST_INFO"]) ? TEST_INFO : 0;
                $profile['DEBUG_LEVEL'] = $data['DEBUG_LEVEL'];
                $old_profile = $profile_model->getProfile($data['WORK_DIRECTORY']);
                $folder = APP_DIR . "/resources";
                if (!file_exists(APP_DIR) && !mkdir(APP_DIR) || !file_exists($folder) && !mkdir($folder)) {
                    $data["MESSAGE"] = tl('system_component_no_resource_folder');
                    $data['SCRIPT'] .= "doMessage('<h1 class=\"red\" >" . $data["MESSAGE"] . "</h1>')";
                    return $data;
                }
                foreach (array('BACKGROUND_IMAGE', 'LOGO', 'M_LOGO', 'FAVICON', 'SEARCHBAR_PATH') as $field) {
                    if (isset($_FILES[$field]['name']) && $_FILES[$field]['name'] != "") {
                        if (!in_array($_FILES[$field]['type'], array('image/png', 'image/gif', 'image/jpeg', 'image/x-icon')) && $field != 'SEARCHBAR_PATH' || $_FILES[$field]['type'] != 'text/xml' && $field == 'SEARCHBAR_PATH') {
                            $data["MESSAGE"] = tl('system_component_invalid_filetype');
                            $data['SCRIPT'] .= "doMessage('<h1 class=\"red\" >" . $data["MESSAGE"] . "</h1>')";
                            return $data;
                        }
                        if ($_FILES[$field]['size'] > THUMB_SIZE) {
                            $data["MESSAGE"] = tl('system_component_file_too_big');
                            $data['SCRIPT'] .= "doMessage('<h1 class=\"red\" >" . $data["MESSAGE"] . "</h1>')";
                            return $data;
                        }
                        $profile[$field] = array();
                        $profile[$field]['name'] = $_FILES[$field]['name'];
                        $profile[$field]['tmp_name'] = $_FILES[$field]['tmp_name'];
                        $data[$field] = "./?c=resource&amp;a=get&amp;" . "f=resources&amp;n=" . $profile[$field]['name'];
                    }
                }
                if ($profile_model->updateProfile($data['WORK_DIRECTORY'], $profile, $old_profile)) {
                    $data['MESSAGE'] = tl('system_component_configure_profile_change');
                    $data['SCRIPT'] = "doMessage('<h1 class=\"red\" >" . $data['MESSAGE'] . "</h1>');";
                    if ($old_profile['DEBUG_LEVEL'] != $profile['DEBUG_LEVEL']) {
                        $data['SCRIPT'] .= "setTimeout('window.location.href=\"" . "?c=admin&amp;a=configure&amp;" . CSRF_TOKEN . "=" . $_REQUEST[CSRF_TOKEN] . "\"', 3*sec);";
                    }
                } else {
                    $data['PROFILE'] = false;
                    $data["MESSAGE"] = tl('system_component_configure_no_change_profile');
                    $data['SCRIPT'] .= "doMessage('<h1 class=\"red\" >" . $data["MESSAGE"] . "</h1>');";
                    break;
                }
                break;
            case "reset":
                $base_url = NAME_SERVER;
                if (defined("BASE_URL")) {
                    $base_url = BASE_URL;
                }
                $profile = array('LANDING_PAGE' => false, 'BACKGROUND_COLOR' => "#FFF", 'BACKGROUND_IMAGE' => "", 'FOREGROUND_COLOR' => "#FFF", 'SIDEBAR_COLOR' => "#8A4", 'TOPBAR_COLOR' => "#EEF", 'LOGO' => "resources/yioop.png", 'M_LOGO' => "resources/m-yioop.png", 'FAVICON' => $base_url . "favicon.ico", 'TIMEZONE' => 'America/Los_Angeles', 'SESSION_NAME' => "yioopbiscuit", 'CSRF_TOKEN' => "YIOOP_TOKEN", 'AUXILIARY_CSS' => "");
                $old_profile = $profile_model->getProfile($data['WORK_DIRECTORY']);
                foreach ($old_profile as $key => $value) {
                    $data[$key] = $value;
                }
                $tmp_image = $old_profile['BACKGROUND_IMAGE'];
                $old_profile['BACKGROUND_IMAGE'] = "";
                if ($profile_model->updateProfile($data['WORK_DIRECTORY'], $profile, $old_profile, true)) {
                    $old_profile['BACKGROUND_IMAGE'] = $tmp_image;
                    foreach ($profile as $key => $value) {
                        $data[$key] = $value;
                        if (in_array($key, array('BACKGROUND_IMAGE', 'LOGO', 'M_LOGO', 'FAVICON', 'SEARCHBAR_PATH')) && $old_profile[$key] != "") {
                            $resource_name = APP_DIR . "/resources/" . $old_profile[$key];
                            if (file_exists($resource_name)) {
                                unlink($resource_name);
                            }
                        }
                    }
                    $data['MESSAGE'] = tl('system_component_configure_reset_completed');
                    $data['SCRIPT'] = "doMessage('<h1 class=\"red\" >" . $data['MESSAGE'] . "</h1>');";
                } else {
                    $data['PROFILE'] = false;
                    $data["MESSAGE"] = tl('system_component_configure_no_change_profile');
                    $data['SCRIPT'] .= "doMessage('<h1 class=\"red\" >" . $data["MESSAGE"] . "</h1>');";
                    break;
                }
                break;
            default:
                if (isset($data['WORK_DIRECTORY']) && file_exists($data['WORK_DIRECTORY'] . "/profile.php")) {
                    $data = array_merge($data, $profile_model->getProfile($data['WORK_DIRECTORY']));
                } else {
                    $data['WORK_DIRECTORY'] = "";
                    $data['PROFILE'] = false;
                }
        }
        $data['advanced'] = "false";
        if ($data['PROFILE']) {
            $locale_tag = getLocaleTag();
            $not_null_fields = array('LOGO' => "resources/yioop.png", 'M_LOGO' => "resources/m-yioop.png", 'FAVICON' => BASE_URL . "favicon.ico", 'TIMEZONE' => 'America/Los_Angeles', 'SESSION_NAME' => "yioopbiscuit", 'CSRF_TOKEN' => "YIOOP_TOKEN");
            foreach ($not_null_fields as $field => $default) {
                if (!$data[$field]) {
                    $data[$field] = $default;
                }
            }
            if (isset($_REQUEST['ROBOT_DESCRIPTION'])) {
                $robot_description = substr($parent->clean($_REQUEST['ROBOT_DESCRIPTION'], "string"), 0, MAX_GROUP_PAGE_LEN);
                $group_model->setPageName(ROOT_ID, PUBLIC_GROUP_ID, "bot", $robot_description, $locale_tag, "", "", "", "");
            }
            $robot_info = $group_model->getPageInfoByName(PUBLIC_GROUP_ID, "bot", $locale_tag, "edit");
            $data['ROBOT_DESCRIPTION'] = isset($robot_info["PAGE"]) ? $robot_info["PAGE"] : tl('system_component_describe_robot');
            if (isset($_REQUEST['advanced']) && $_REQUEST['advanced'] == 'true') {
                $data['advanced'] = "true";
            }
            $data['SCRIPT'] .= <<<EOD
    setDisplay('advance-configure', {$data['advanced']});
    setDisplay('advance-robot', {$data['advanced']});
    function toggleAdvance() {
        var advanced = elt('a-settings');
        advanced.value = (advanced.value =='true')
            ? 'false' : 'true';
        var value = (advanced.value == 'true') ? true : false;
        setDisplay('advance-configure', value);
        setDisplay('advance-robot', value);
    }
EOD;
        }
        $data['SCRIPT'] .= "\nelt('locale').onchange = " . "function () { elt('configureProfileForm').submit();};\n";
        return $data;
    }
Пример #9
0
    /**
     * Used to draw a list of Wiki Pages for the current group. It also
     * draws a search form and can be used to create pages
     *
     * @param array $data fields for the current controller, CSRF_TOKEN
     *     etc needed to render the search for and paging queries
     * @param bool $can_edit whether the current user has permissions to
     *     edit or create this page
     * @param bool $logged_in whethe current user is logged in or not
     */
    function renderPages($data, $can_edit, $logged_in)
    {
        $append_url = $logged_in ? "&amp;" . CSRF_TOKEN . "=" . $data[CSRF_TOKEN] : "";
        $base_query = "?c={$data['CONTROLLER']}&amp;group_id=" . $data["GROUP"]["GROUP_ID"] . "&amp;a=wiki{$append_url}";
        $create_query = $base_query . "&amp;arg=edit&amp;page_name=" . $data["FILTER"];
        $base_query .= "&amp;arg=read";
        $paging_query = "?c={$data['CONTROLLER']}{$append_url}&amp;group_id=" . $data["GROUP"]["GROUP_ID"] . "&amp;a=wiki&amp;arg=pages";
        e("<h2>" . tl("wiki_view_wiki_page_list", $data["GROUP"]["GROUP_NAME"]) . "</h2>");
        ?>
        <form id="editpageForm" method="get">
        <input type="hidden" name="c" value="<?php 
        e($data['CONTROLLER']);
        ?>
" />
        <input type="hidden" name="<?php 
        e(CSRF_TOKEN);
        ?>
" value="<?php 
        e($data[CSRF_TOKEN]);
        ?>
" />
        <input type="hidden" name="a" value="wiki" />
        <input type="hidden" name="arg" value="pages" />
        <input type="hidden" name="group_id" value="<?php 
        e($data['GROUP']['GROUP_ID']);
        ?>
" />
        <input type="text" name="filter" class="extra-wide-field"
            maxlength="<?php 
        e(SHORT_TITLE_LEN);
        ?>
"
            placeholder="<?php 
        e(tl("wiki_view_filter_or_create"));
        ?>
" value="<?php 
        e($data['FILTER']);
        ?>
" />
        <button class="button-box" type="submit"><?php 
        e(tl('wiki_element_go'));
        ?>
</button>
        </form>
        <?php 
        if ($data["FILTER"] != "") {
            e("<a href='{$create_query}'>" . tl("wiki_view_create_page", $data['FILTER']) . "</a>");
        }
        ?>
        <div>&nbsp;</div>
        <?php 
        if ($data['PAGES'] != array()) {
            foreach ($data['PAGES'] as $page) {
                $ellipsis = mb_strlen($page["DESCRIPTION"]) > MIN_SNIPPET_LENGTH ? "..." : "";
                if ($page['TYPE'] == 'page_alias' && isset($page['ALIAS'])) {
                    $page["DESCRIPTION"] = tl('wiki_element_redirect_to') . " <a href='{$base_query}&amp;" . "page_name={$page['ALIAS']}'>{$page['ALIAS']}</a>";
                } else {
                    $page["DESCRIPTION"] = strip_tags($page["DESCRIPTION"]);
                }
                ?>
                <div class='group-result'>
                <a href="<?php 
                e($base_query . '&amp;page_name=' . $page['TITLE']);
                ?>
&noredirect=true" ><?php 
                e($page["TITLE"]);
                ?>
</a></br />
                <?php 
                e($page["DESCRIPTION"] . $ellipsis);
                ?>
                </div>
                <div>&nbsp;</div>
                <?php 
            }
            $this->view->helper("pagination")->render($paging_query, $data['LIMIT'], $data['RESULTS_PER_PAGE'], $data['TOTAL_ROWS']);
        }
        if ($data['PAGES'] == array()) {
            e('<div>' . tl('wiki_view_no_pages', "<b>" . getLocaleTag() . "</b>") . '</div>');
        }
    }
Пример #10
0
 /**
  * Used to read in a PUBLIC_GROUP_ID wiki page that will be presented
  * to non-logged in visitors to the site.
  *
  * @param string $page_name name of file less extension to read in
  * @return string text of page
  */
 function getPage($page_name)
 {
     $group_model = $this->model("group");
     $locale_tag = getLocaleTag();
     $page_info = $group_model->getPageInfoByName(PUBLIC_GROUP_ID, $page_name, $locale_tag, "read");
     $page_string = isset($page_info["PAGE"]) ? $page_info["PAGE"] : "";
     if (!$page_string && $locale_tag != DEFAULT_LOCALE) {
         //fallback to default locale for translation
         $page_info = $group_model->getPageInfoByName(PUBLIC_GROUP_ID, $page_name, DEFAULT_LOCALE, "read");
         $page_string = $page_info["PAGE"];
     }
     $data['CONTROLLER'] = "static";
     $page_string = $this->component("social")->dynamicSubstitutions(PUBLIC_GROUP_ID, $data, $page_string);
     return $page_string;
 }
Пример #11
0
 /**
  * Responsible for setting the view for a feed if something other
  * than HTML (for example, RSS or JSON) is desired. It also
  * sets up any particular $data fields needed for displaying that
  * view correctly.
  *
  * @param string $format can be one of rss, json, or serialize,
  *      if different, default HTML GroupView used.
  * @param string& $view variable used to set the view in calling
  *     method
  * @param array& $data used to send data to the view for drawing
  */
 function setupViewFormatOutput($format, &$view, &$data)
 {
     $data["QUERY"] = "groups:feed";
     if (isset($data["JUST_GROUP_ID"])) {
         $data["QUERY"] = "groups:just_group_id:" . $data["JUST_GROUP_ID"];
     }
     if (isset($data["JUST_USER_ID"])) {
         $data["QUERY"] = "groups:just_user_id:" . $data["JUST_USER_ID"];
     }
     if (isset($data["JUST_THREAD"])) {
         $data["QUERY"] = "groups:just_thread:" . $data["JUST_THREAD"];
     }
     $data["its"] = 0;
     $num_pages = count($data["PAGES"]);
     if (isset($data['ADMIN']) && $data['ADMIN']) {
         $base_query = $data['PAGING_QUERY'] . "&amp;" . CSRF_TOKEN . "=" . $data[CSRF_TOKEN] . "&amp;";
     } else {
         $base_query = $data['PAGING_QUERY'] . "&amp;";
     }
     for ($i = 0; $i < $num_pages; $i++) {
         $data["PAGES"][$i][self::URL] = BASE_URL . $base_query . "just_thread=" . $data["PAGES"][$i]['PARENT_ID'];
     }
     switch ($format) {
         case "rss":
             $view = "rss";
             break;
         case "json":
             $out_data = array();
             $out_data["language"] = getLocaleTag();
             $out_data["link"] = NAME_SERVER . "?f={$format}&amp;q={$data['QUERY']}";
             $out_data["totalResults"] = $data['TOTAL_ROWS'];
             $out_data["startIndex"] = $data['LIMIT'];
             $out_data["itemsPerPage"] = $data['RESULTS_PER_PAGE'];
             foreach ($data['PAGES'] as $page) {
                 $item = array();
                 $item["title"] = $page[self::TITLE];
                 if (!isset($page[self::TYPE]) || isset($page[self::TYPE]) && $page[self::TYPE] != "link") {
                     $item["link"] = $page[self::URL];
                 } else {
                     $item["link"] = strip_tags($page[self::TITLE]);
                 }
                 $item["description"] = strip_tags($page[self::DESCRIPTION]);
                 if (isset($page[self::THUMB]) && $page[self::THUMB] != 'NULL') {
                     $item["thumb"] = $page[self::THUMB];
                 }
                 if (isset($page[self::TYPE])) {
                     $item["type"] = $page[self::TYPE];
                 }
                 $out_data['item'][] = $item;
             }
             e(json_encode($out_data));
             exit;
             break;
         case "serial":
             e(serialize($out_data));
             exit;
             break;
     }
 }
Пример #12
0
    /**
     * Responsible for drawing the header of the document containing
     * Yioop! title and including basic.js. It calls the renderView method of
     * the View that lives on the layout. If the QUERY_STATISTIC config setting
     * is set, it output statistics about each query run on the database.
     * Finally, it draws the footer of the document.
     *
     * @param array $data  an array of data set up by the controller to be
     * be used in drawing the WebLayout and its View.
     */
    function render($data)
    {
        header("Content-type: application/rss+xml");
        e('<?xml version="1.0" encoding="UTF-8" ?>' . "\n");
        ?>
<rss version="2.0" xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/"
xmlns:atom="http://www.w3.org/2005/Atom"
>
    <channel>
        <title><?php 
        e(tl('rss_layout_title', mb_convert_encoding(html_entity_decode(urldecode($data['QUERY'])), "UTF-8")));
        ?>
</title>
        <language><?php 
        e(getLocaleTag());
        ?>
</language>
        <link><?php 
        e(NAME_SERVER);
        ?>
?f=rss&amp;q=<?php 
        e($data['QUERY']);
        ?>
&amp;<?php 
        ?>
its=<?php 
        e($data['its']);
        ?>
</link>
        <description><?php 
        e(tl('rss_layout_description', mb_convert_encoding(html_entity_decode(urldecode($data['QUERY'])), "UTF-8")));
        ?>
</description>
        <opensearch:totalResults><?php 
        e($data['TOTAL_ROWS']);
        ?>
</opensearch:totalResults>
        <opensearch:startIndex><?php 
        e($data['LIMIT']);
        ?>
</opensearch:startIndex>
        <opensearch:itemsPerPage><?php 
        e($data['RESULTS_PER_PAGE']);
        ?>
</opensearch:itemsPerPage>
        <atom:link rel="search" type="application/opensearchdescription+xml"
            href="<?php 
        e(NAME_SERVER);
        ?>
yioopbar.xml"/>
        <opensearch:Query role="request" searchTerms="<?php 
        e($data['QUERY']);
        ?>
"/>
                <?php 
        $this->view->renderView($data);
        ?>
    </channel>
</rss>
    <?php 
    }
Пример #13
0
 /**
  * Deletes the archive iterator and savepoint files created during the
  * process of iterating through a crawl mix.
  *
  * @param int $timestamp The timestamp of the crawl mix
  */
 function deleteCrawlMixIteratorState($timestamp)
 {
     global $INDEXING_PLUGINS;
     setLocaleObject(getLocaleTag());
     $searchController = new SearchController($INDEXING_PLUGINS);
     $searchController->clearQuerySavepoint($timestamp);
     $archive_dir = WORK_DIRECTORY . "/schedules/" . self::name_archive_iterator . $timestamp;
     if (file_exists($archive_dir)) {
         $this->db->unlinkRecursive($archive_dir);
     }
 }
Пример #14
0
 /**
  * Determines if query results are using a subsearch, and if so
  * initializes them, also it sets up list of subsearches to draw
  * at top of screen.
  *
  * @return array (subsearches, no_query) where subsearches is itself
  *     an array of data about each subsearch to draw, and no_query
  *     is a bool flag used in the case of a news subsearch when no query
  *     was entered by the user but still want to display news
  */
 function initializeSubsearches()
 {
     $subsearches = $this->model("source")->getSubsearches();
     array_unshift($subsearches, array("FOLDER_NAME" => "", "SUBSEARCH_NAME" => tl('search_controller_web')));
     $no_query = false;
     if (isset($_REQUEST["s"])) {
         $search_found = false;
         foreach ($subsearches as $search) {
             if ($search["FOLDER_NAME"] == $_REQUEST["s"]) {
                 $search_found = true;
                 $this->subsearch_name = $_REQUEST["s"];
                 $this->subsearch_identifier = $search["INDEX_IDENTIFIER"];
                 if (!isset($_REQUEST['num']) && isset($search["PER_PAGE"])) {
                     $_REQUEST['num'] = $search["PER_PAGE"];
                 }
                 break;
             }
         }
         if (!$search_found) {
             $pathinfo = pathinfo($_SERVER['SCRIPT_FILENAME']);
             include $pathinfo["dirname"] . "/error.php";
             exit;
         }
         if ($this->subsearch_name == "news" && (!isset($_REQUEST['q']) || $_REQUEST['q'] == "")) {
             $lang = getLocaleTag();
             $lang_parts = explode("-", $lang);
             if (isset($lang_parts[0])) {
                 $lang = $lang_parts[0];
             }
             $_REQUEST['q'] = "lang:" . $lang;
             $no_query = true;
         }
     }
     return array($subsearches, $no_query);
 }
Пример #15
0
 /**
  * Gets all the roles associated with a user id
  *
  * @param string $user_id  the user_id to get roles of
  * @param string $filter to SQL LIKE filter roles
  * @param int $limit starting index of first role to return
  * @param int $num number of roles to return
  * @return array of role_ids and their names
  */
 function getUserRoles($user_id, $filter, $limit, $num = NUM_RESULTS_PER_PAGE)
 {
     $db = $this->db;
     $user_id = $db->escapeString($user_id);
     $roles = array();
     $locale_tag = getLocaleTag();
     $limit = $db->limitOffset($limit, $num);
     $like = "";
     $param_array = array($user_id);
     if ($filter != "") {
         $like = "AND R.NAME LIKE ?";
         $param_array[] = "%" . $filter . "%";
     }
     $sql = "SELECT LOCALE_ID FROM LOCALE " . "WHERE LOCALE_TAG = ? " . $db->limitOffset(1);
     $result = $db->execute($sql, array($locale_tag));
     $row = $db->fetchArray($result);
     $locale_id = $row['LOCALE_ID'];
     $sql = "SELECT UR.ROLE_ID AS ROLE_ID, R.NAME AS ROLE_NAME " . " FROM  USER_ROLE UR, ROLE R WHERE UR.USER_ID = ? " . " AND R.ROLE_ID = UR.ROLE_ID {$like}  ORDER BY R.NAME ASC {$limit}";
     $result = $db->execute($sql, $param_array);
     $i = 0;
     while ($roles[$i] = $db->fetchArray($result)) {
         $i++;
     }
     unset($roles[$i]);
     //last one will be null
     return $roles;
 }
Пример #16
0
    /**
     * Method responsible for drawing the page with more
     * search option, account, and tool info
     *
     * @param array $data to draw links on page
     */
    function render($data)
    {
        $logged_in = isset($data['ADMIN']) && $data['ADMIN'];
        $append_url = $logged_in && isset($data[CSRF_TOKEN]) ? "&amp;" . CSRF_TOKEN . "=" . $data[CSRF_TOKEN] : "";
        if (SUBSEARCH_LINK) {
            $max_column_num = 10;
            if (MOBILE) {
                $num_columns = 1;
            } else {
                $num_columns = 4;
            }
            $max_items = $max_column_num * $num_columns;
            $subsearches = array_slice($data["SUBSEARCHES"], $max_items * $data['MORE_PAGE']);
            $spacer = "";
            $prev_link = false;
            $next_link = false;
            if ($data['MORE_PAGE'] > 0) {
                $prev_link = true;
            }
            $num_remaining = count($subsearches);
            if ($num_remaining > $max_items) {
                $next_link = true;
                $subsearches = array_slice($subsearches, 0, $max_items);
            }
            if ($next_link && $prev_link) {
                $spacer = "&nbsp;&nbsp;--&nbsp;&nbsp;";
            }
            $num_rows = ceil(count($subsearches) / $num_columns);
            ?>
            <h2><?php 
            e(tl('moreoptions_element_other_searches'));
            ?>
</h2>
            <table>
            <tr class="align-top">
            <?php 
            $cur_row = 0;
            foreach ($subsearches as $search) {
                if ($cur_row == 0) {
                    e("<td><ul class='square-list'>");
                    $ul_open = true;
                }
                $cur_row++;
                if (!$search['SUBSEARCH_NAME']) {
                    $search['SUBSEARCH_NAME'] = $search['LOCALE_STRING'];
                }
                $query = $search["FOLDER_NAME"] == "" ? "?" : "?s={$search["FOLDER_NAME"]}";
                $query .= $append_url;
                e("<li><a href='{$query}'>" . "{$search['SUBSEARCH_NAME']}</a></li>");
                if ($cur_row >= $num_rows) {
                    $ul_open = false;
                    e("</ul></td>");
                    $cur_row = 0;
                }
            }
            if ($ul_open) {
                e("</ul></td>");
            }
            ?>
            </tr>
            </table>
            <div class="indent"><?php 
            if ($prev_link) {
                e("<a href='./?a=more{$append_url}" . "&amp;more_page=" . ($data['MORE_PAGE'] - 1) . "'>" . tl('moreoptions_element_previous') . "</a>");
            }
            e($spacer);
            if ($next_link) {
                e("<a href='./?a=more{$append_url}" . "&amp;more_page=" . ($data['MORE_PAGE'] + 1) . "'>" . tl('moreoptions_element_next') . "</a>");
            }
            ?>
</div>
        <?php 
        }
        ?>
        <h2 class="reduce-top"><?php 
        e(tl('moreoptions_element_my_accounts'));
        ?>
</h2>
        <table class="reduce-top">
        <tr><td><ul class='square-list'><li><a href="./?c=settings<?php 
        e($append_url);
        ?>
&amp;l=<?php 
        e(getLocaleTag());
        e(isset($data['its']) ? '&amp;its=' . $data['its'] : '');
        ?>
"><?php 
        e(tl('signin_element_settings'));
        ?>
</a></li>
            <?php 
        if (!MOBILE) {
            ?>
                </ul></td>
                <td><ul  class='square-list'>
            <?php 
        }
        if (!$logged_in) {
            ?>
<li><a href="./?c=admin"><?php 
            e(tl('signin_element_signin'));
            ?>
</a></li><?php 
        } else {
            ?>
<li><a href="./?c=admin<?php 
            e($append_url);
            ?>
"><?php 
            e(tl('signin_element_admin'));
            ?>
</a></li><?php 
        }
        if (!MOBILE) {
            e('</ul></td>');
        }
        ?>

            <?php 
        if (!$logged_in && in_array(REGISTRATION_TYPE, array('no_activation', 'email_registration', 'admin_activation'))) {
            if (!MOBILE) {
                e("<td><ul  class='square-list'>");
            }
            ?>
                <li><a href="./?c=register&amp;a=createAccount<?php 
            e($append_url);
            ?>
"><?php 
            e(tl('signin_view_create_account'));
            ?>
</a></li>
                </ul></td>
                <?php 
        }
        ?>
        </tr>
        </table>
        <?php 
        $tools = array();
        if (in_array(REGISTRATION_TYPE, array('no_activation', 'email_registration', 'admin_activation'))) {
            $tools["?c=register&amp;a=suggestUrl{$append_url}"] = tl('moreoptions_element_suggest');
        }
        $tools["?c=group&amp;a=wiki&amp;arg=pages{$append_url}"] = tl('moreoptions_element_wiki_pages');
        if ($tools != array()) {
            $max_column_num = 10;
            if (MOBILE) {
                $num_columns = 1;
            } else {
                $num_columns = 4;
            }
            $num_rows = ceil(count($tools) / $num_columns);
            ?>
            <h2 id="tools" class="reduce-top"><?php 
            e(tl('moreoptions_element_tools'));
            ?>
</h2>
            <table class="reduce-top">
            <tr class="align-top">
            <?php 
            $cur_row = 0;
            foreach ($tools as $tool_url => $tool_name) {
                if ($cur_row == 0) {
                    e("<td><ul class='square-list'>");
                    $ul_open = true;
                }
                $cur_row++;
                e("<li><a href='{$tool_url}'>{$tool_name}</a></li>");
                if ($cur_row >= $num_rows) {
                    $ul_open = false;
                    e("</ul></td>");
                    $cur_row = 0;
                }
            }
            if ($ul_open) {
                e("</ul></td>");
            }
            ?>
            </tr>
            </table>
            <?php 
        }
    }
Пример #17
0
 /**
  * Runs the QueryTool on the supplied command line arguments
  */
 function start()
 {
     global $argv, $INDEXING_PLUGINS;
     if (!isset($argv[1])) {
         $this->usageMessageAndExit();
     }
     $query = $argv[1];
     $results_per_page = isset($argv[2]) ? $argv[2] : 10;
     $limit = isset($argv[3]) ? $argv[3] : 0;
     setLocaleObject(getLocaleTag());
     $start_time = microtime();
     $controller = new SearchController($INDEXING_PLUGINS);
     $data = $controller->queryRequest($query, $results_per_page, $limit);
     if (!isset($data['PAGES'])) {
         $data['PAGES'] = array();
     }
     foreach ($data['PAGES'] as $page) {
         echo "============\n";
         echo "TITLE: " . trim($page[self::TITLE]) . "\n";
         echo "URL: " . trim($page[self::URL]) . "\n";
         echo "IPs: ";
         if (isset($page[self::IP_ADDRESSES])) {
             foreach ($page[self::IP_ADDRESSES] as $address) {
                 echo $address . " ";
             }
         }
         echo "\n";
         echo "DESCRIPTION: " . wordwrap(trim($page[self::DESCRIPTION])) . "\n";
         echo "Rank: " . $page[self::DOC_RANK] . "\n";
         echo "Relevance: " . $page[self::RELEVANCE] . "\n";
         echo "Proximity: " . $page[self::PROXIMITY] . "\n";
         echo "Score: " . $page[self::SCORE] . "\n";
         echo "============\n\n";
     }
     $data['ELAPSED_TIME'] = changeInMicrotime($start_time);
     echo "QUERY STATISTICS\n";
     echo "============\n";
     echo "ELAPSED TIME: " . $data['ELAPSED_TIME'] . "\n";
     if (isset($data['LIMIT'])) {
         echo "LOW: " . $data['LIMIT'] . "\n";
     }
     if (isset($data['HIGH'])) {
         echo "HIGH: " . min($data['TOTAL_ROWS'], $data['LIMIT'] + $data['RESULTS_PER_PAGE']) . "\n";
     }
     if (isset($data['TOTAL_ROWS'])) {
         echo "TOTAL ROWS: " . $data['TOTAL_ROWS'] . "\n";
     }
     if (isset($data['ERROR'])) {
         echo $data['ERROR'] . "\n";
     }
 }
Пример #18
0
 /**
  * Send the provided view to output, drawing it with the given
  * data variable, using the current locale for translation, and
  * writing mode
  *
  * @param string $view   the name of the view to draw
  * @param array $data   an array of values to use in drawing the view
  */
 function displayView($view, $data)
 {
     $data['LOCALE_TAG'] = getLocaleTag();
     $data['LOCALE_DIR'] = getLocaleDirection();
     $data['BLOCK_PROGRESSION'] = getBlockProgression();
     $data['WRITING_MODE'] = getWritingMode();
     if (QUERY_STATISTICS) {
         $data['QUERY_STATISTICS'] = array();
         $machine = isset($_SERVER["HTTP_HOST"]) ? htmlentities($_SERVER["HTTP_HOST"]) : "localhost";
         $machine_uri = isset($_SERVER['REQUEST_URI']) ? htmlentities($_SERVER['REQUEST_URI']) : "/";
         $protocol = isset($_SERVER["HTTPS"]) ? "https://" : "http://";
         if ($machine == '::1') {
             //IPv6 :(
             $machine = "[::1]/";
             //used if the fetching and queue serving on the same machine
         }
         $data['YIOOP_INSTANCE'] = $protocol . $machine . $machine_uri;
         $data['TOTAL_ELAPSED_TIME'] = 0;
         foreach ($this->model_instances as $model_name => $model) {
             $data['QUERY_STATISTICS'] = array_merge($model->db->query_log, $data['QUERY_STATISTICS']);
             $data['TOTAL_ELAPSED_TIME'] += $model->db->total_time;
         }
         $locale_info = getLocaleQueryStatistics();
         $data['QUERY_STATISTICS'] = array_merge($locale_info['QUERY_LOG'], $data['QUERY_STATISTICS']);
         $data['TOTAL_ELAPSED_TIME'] += $locale_info['TOTAL_ELAPSED_TIME'];
         $mail_total_time = AnalyticsManager::get("MAIL_TOTAL_TIME");
         $mail_messages = AnalyticsManager::get("MAIL_MESSAGES");
         if ($mail_total_time && $mail_messages) {
             $data['QUERY_STATISTICS'] = array_merge($mail_messages, $data['QUERY_STATISTICS']);
             $data['TOTAL_ELAPSED_TIME'] += $mail_total_time;
         }
     }
     $data['c'] = isset($_REQUEST['c']) ? $_REQUEST['c'] : NULL;
     if (isset($_SESSION['DISPLAY_MESSAGE'])) {
         $data['DISPLAY_MESSAGE'] = $_SESSION['DISPLAY_MESSAGE'];
         unset($_SESSION['DISPLAY_MESSAGE']);
     }
     $this->view($view)->render($data);
 }
Пример #19
0
 /**
  * Sets up the available perpage language options.
  * If handling data sent from a  form, it stores cleaned versions of
  * the number of results per page and language options into a sesssion
  *
  */
 function processRequest()
 {
     $data = array();
     $view = "settings";
     $changed_settings_flag = false;
     $crawl_model = $this->model("crawl");
     if (isset($_SESSION['USER_ID'])) {
         $user = $_SESSION['USER_ID'];
         $data['ADMIN'] = 1;
     } else {
         $user = $_SERVER['REMOTE_ADDR'];
     }
     $data[CSRF_TOKEN] = $this->generateCSRFToken($user);
     $token_okay = $this->checkCSRFToken(CSRF_TOKEN, $user);
     $languages = $this->model("locale")->getLocaleList();
     foreach ($languages as $language) {
         $data['LANGUAGES'][$language['LOCALE_TAG']] = $language['LOCALE_NAME'];
     }
     if ($token_okay && isset($_REQUEST['lang']) && in_array($_REQUEST['lang'], array_keys($data['LANGUAGES']))) {
         $_SESSION['l'] = $_REQUEST['lang'];
         setLocaleObject($_SESSION['l']);
         $changed_settings_flag = true;
     }
     $data['LOCALE_TAG'] = getLocaleTag();
     $n = NUM_RESULTS_PER_PAGE;
     $data['PER_PAGE'] = array($n => $n, 2 * $n => 2 * $n, 5 * $n => 5 * $n, 10 * $n => 10 * $n);
     if ($token_okay && isset($_REQUEST['perpage']) && in_array($_REQUEST['perpage'], array_keys($data['PER_PAGE']))) {
         $_SESSION['MAX_PAGES_TO_SHOW'] = $_REQUEST['perpage'];
         $changed_settings_flag = true;
     }
     if (isset($_SESSION['MAX_PAGES_TO_SHOW'])) {
         $data['PER_PAGE_SELECTED'] = $_SESSION['MAX_PAGES_TO_SHOW'];
     } else {
         $data['PER_PAGE_SELECTED'] = NUM_RESULTS_PER_PAGE;
     }
     if ($token_okay && isset($_REQUEST['perpage'])) {
         $_SESSION['OPEN_IN_TABS'] = isset($_REQUEST['open_in_tabs']) ? true : false;
     }
     if (isset($_SESSION['OPEN_IN_TABS'])) {
         $data['OPEN_IN_TABS'] = $_SESSION['OPEN_IN_TABS'];
     } else {
         $data['OPEN_IN_TABS'] = false;
     }
     $machine_urls = $this->model("machine")->getQueueServerUrls();
     $crawls = $crawl_model->getCrawlList(false, true, $machine_urls, true);
     $data['CRAWLS'] = array();
     foreach ($crawls as $crawl) {
         $data['CRAWLS'][$crawl['CRAWL_TIME']] = $crawl['DESCRIPTION'] . " ... " . $crawl['COUNT'] . " urls";
     }
     $mixes = $crawl_model->getMixList($user);
     foreach ($mixes as $mix) {
         $data['CRAWLS'][$mix['TIMESTAMP']] = $mix['NAME'] . " ... " . tl('settings_controller_crawl_mix');
     }
     $crawl_stamps = array_keys($data['CRAWLS']);
     if ($token_okay) {
         $changed_settings_flag = $this->loggedInChangeSettings($data);
     } else {
         if (isset($_REQUEST['its']) && in_array($_REQUEST['its'], $crawl_stamps)) {
             $data['its'] = $_REQUEST['its'];
         } else {
             $data['its'] = $crawl_model->getCurrentIndexDatabaseName();
         }
     }
     if ($changed_settings_flag) {
         $data['SCRIPT'] = "doMessage('<h1 class=\"red\" >" . tl('settings_controller_settings_saved') . "</h1>')";
         if ($user != $_SERVER['REMOTE_ADDR']) {
             $this->model("user")->setUserSession($user, $_SESSION);
         }
     }
     $this->displayView($view, $data);
 }
Пример #20
0
 /**
  * Returns a list of the subsearches used by the current Yioop instances
  * including their names translated to the current locale
  *
  * @return array associative array containing subsearch info name in locale,
  *    folder name, index, number of results per page
  */
 function getSubsearches()
 {
     $subsearches = array();
     $db = $this->db;
     $locale_tag = getLocaleTag();
     $sql = "SELECT LOCALE_ID FROM LOCALE " . "WHERE LOCALE_TAG = ? " . $db->limitOffset(1);
     $result = $db->execute($sql, array($locale_tag));
     $row = $db->fetchArray($result);
     $locale_id = $row['LOCALE_ID'];
     $sql = "SELECT S.LOCALE_STRING AS LOCALE_STRING, " . "S.FOLDER_NAME AS FOLDER_NAME, " . " S.PER_PAGE AS PER_PAGE, " . " S.INDEX_IDENTIFIER AS INDEX_IDENTIFIER, " . " T.TRANSLATION_ID AS TRANSLATION_ID FROM " . " SUBSEARCH S, TRANSLATION T WHERE  " . " T.IDENTIFIER_STRING = S.LOCALE_STRING";
     $i = 0;
     $result = $db->execute($sql);
     $sub_sql = "SELECT TRANSLATION AS SUBSEARCH_NAME " . "FROM TRANSLATION_LOCALE " . " WHERE TRANSLATION_ID=? AND LOCALE_ID=? " . $db->limitOffset(1);
     // maybe do left join at some point
     while ($subsearches[$i] = $db->fetchArray($result)) {
         $id = $subsearches[$i]["TRANSLATION_ID"];
         $result_sub = $db->execute($sub_sql, array($id, $locale_id));
         $translate = false;
         if ($result_sub) {
             $translate = $db->fetchArray($result_sub);
         }
         if ($translate) {
             $subsearches[$i]['SUBSEARCH_NAME'] = $translate['SUBSEARCH_NAME'];
         } else {
             $subsearches[$i]['SUBSEARCH_NAME'] = $this->translateDb($subsearches[$i]['LOCALE_STRING'], DEFAULT_LOCALE);
         }
         $i++;
     }
     unset($subsearches[$i]);
     //last one will be null
     return $subsearches;
 }