コード例 #1
0
/**
 * Activate a named plugin.
 *
 * Parses the plugins directory to look for a pluginname.yaml
 * file and adds the plugin to the plugins database, setting
 * the inst_version field to the version specified in the yaml file.
 *
 * @param string $name Name of plugin to be activated.
 * @return bool Returns true if plugin directory was found.
 * @see deactivate_plugin
 */
function activate_plugin($name)
{
    $plugins_dir = dirname(__FILE__) . '/../plugins/';
    $plugin_dir = $plugins_dir . $name;
    if (file_exists($plugin_dir)) {
        $plugin_yaml = get_plugin_yaml("{$plugin_dir}/{$name}.yaml", false);
        # If no yaml, or yaml file but no description present, attempt to read an 'about.txt' file
        if ($plugin_yaml['desc'] == '') {
            $about = $plugins_dir . $name . '/about.txt';
            if (file_exists($about)) {
                $plugin_yaml['desc'] = substr(file_get_contents($about), 0, 95) . '...';
            }
        }
        # escape the plugin information
        $plugin_yaml_esc = array();
        foreach (array_keys($plugin_yaml) as $thekey) {
            $plugin_yaml_esc[$thekey] = escape_check($plugin_yaml[$thekey]);
        }
        # Add/Update plugin information.
        # Check if the plugin is already in the table.
        $c = sql_value("SELECT name as value FROM plugins WHERE name='{$name}'", '');
        if ($c == '') {
            sql_query("INSERT INTO plugins(name) VALUE ('{$name}')");
        }
        sql_query("UPDATE plugins SET config_url='{$plugin_yaml_esc['config_url']}', " . "descrip='{$plugin_yaml_esc['desc']}', author='{$plugin_yaml_esc['author']}', " . "inst_version='{$plugin_yaml_esc['version']}', " . "priority='{$plugin_yaml_esc['default_priority']}', " . "update_url='{$plugin_yaml_esc['update_url']}', info_url='{$plugin_yaml_esc['info_url']}' " . "WHERE name='{$plugin_yaml_esc['name']}'");
        return true;
    } else {
        return false;
    }
}
コード例 #2
0
ファイル: theme_edit.php プロジェクト: Jtgadbois/Pedadida
function save_themename()
	{
		global $baseurl, $link, $themename, $collection_column;
		$sql="update collection set	" . $collection_column . "='" . getvalescaped("rename","") . "' where " . $collection_column . "='" . escape_check($themename)."'";
		sql_query($sql);
		header("location:".$baseurl. "/pages/" . $link);
	}
コード例 #3
0
function save_themename()
{
    global $baseurl, $link, $themename, $collection_column;
    $sql = "update collection set\t" . $collection_column . "='" . getvalescaped("rename", "") . "' where " . $collection_column . "='" . escape_check($themename) . "'";
    sql_query($sql);
    hook("after_save_themename");
    redirect("pages/" . $link);
}
コード例 #4
0
function get_youtube_access_token($refresh = false)
{
    global $baseurl, $userref, $youtube_publish_client_id, $youtube_publish_client_secret, $youtube_publish_callback_url, $code;
    $url = 'https://accounts.google.com/o/oauth2/token';
    if ($refresh) {
        $refresh_token = sql_value("select youtube_refresh_token as value from user where ref='{$userref}'", "");
        if ($refresh_token == "") {
            get_youtube_authorization_code();
            exit;
        }
        $params = array("client_id" => $youtube_publish_client_id, "client_secret" => $youtube_publish_client_secret, "refresh_token" => $refresh_token, "grant_type" => "refresh_token");
    } else {
        $params = array("code" => $code, "client_id" => $youtube_publish_client_id, "client_secret" => $youtube_publish_client_secret, "redirect_uri" => $baseurl . $youtube_publish_callback_url, "grant_type" => "authorization_code");
    }
    $curl = curl_init("https://accounts.google.com/o/oauth2/token");
    curl_setopt($curl, CURLOPT_HEADER, "Content-Type:application/x-www-form-urlencoded");
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1);
    $response = json_decode(curl_exec($curl), true);
    curl_close($curl);
    //exit (print_r($response));
    if (isset($response["error"])) {
        sql_query("update user set youtube_access_token='' where ref='{$userref}'");
        //exit("ERROR: bad response" . print_r($response));
        get_youtube_authorization_code();
        exit;
    }
    if (isset($response["access_token"])) {
        $access_token = escape_check($response["access_token"]);
        sql_query("update user set youtube_access_token='{$access_token}' where ref='{$userref}'");
        if (isset($response["refresh_token"])) {
            $refresh_token = escape_check($response["refresh_token"]);
            sql_query("update user set youtube_refresh_token='{$refresh_token}' where ref='{$userref}'");
        }
        debug("YouTube plugin: Access token: " . $access_token);
        debug("YouTube plugin: Refresh token: " . $refresh_token);
    }
    # Get user account details and store these so we can tell which account they will be uploading to
    $headers = array("Authorization: Bearer " . $access_token, "GData-Version: 2");
    $curl = curl_init("https://gdata.youtube.com/feeds/api/users/default");
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_HTTPGET, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1);
    #$response = json_decode( curl_exec( $curl ), true );
    $response = curl_exec($curl);
    $userdataxml = new SimpleXmlElement($response, LIBXML_NOCDATA);
    //exit(print_r($userdataxml));
    $youtube_username = escape_check($userdataxml->title);
    sql_query("update user set youtube_username='******' where ref='{$userref}'");
    return $access_token;
}
コード例 #5
0
function HookGrant_editEditeditbeforeheader()
{
    global $ref, $baseurl, $usergroup, $grant_edit_groups, $collection;
    // Do we have access to do any of this, or is it a template
    if (!in_array($usergroup, $grant_edit_groups) || $ref < 0) {
        return;
    }
    // Check for Ajax POST to delete users
    $grant_edit_action = getvalescaped("grant_edit_action", "");
    if ($grant_edit_action != "") {
        if ($grant_edit_action == "delete") {
            $remove_user = escape_check(getvalescaped("remove_user", "", TRUE));
            if ($remove_user != "") {
                sql_query("delete from grant_edit where resource='{$ref}' and user={$remove_user}");
                exit("SUCCESS");
            }
        }
        exit("FAILED");
    }
    # If 'users' is specified (i.e. access is private) then rebuild users list
    $users = getvalescaped("users", false);
    if ($users != false) {
        # Build a new list and insert
        $users = resolve_userlist_groups($users);
        $ulist = array_unique(trim_array(explode(",", $users)));
        $urefs = sql_array("select ref value from user where username in ('" . join("','", $ulist) . "')");
        if (count($urefs) > 0) {
            $inserttext = array();
            $grant_edit_expiry = getvalescaped("grant_edit_expiry", "");
            foreach ($urefs as $uref) {
                if ($grant_edit_expiry != "") {
                    $inserttext[] = $uref . ",'" . $grant_edit_expiry . "'";
                } else {
                    $inserttext[] = $uref . ",NULL";
                }
            }
            if ($collection != "") {
                global $items;
                foreach ($items as $collection_resource) {
                    sql_query("delete from grant_edit where resource='{$collection_resource}' and user in (" . implode(",", $urefs) . ")");
                    sql_query("insert into grant_edit(resource,user,expiry) values ({$collection_resource}," . join("),(" . $collection_resource . ",", $inserttext) . ")");
                    #log this
                    global $lang;
                    resource_log($collection_resource, 's', "", "Grant Edit -  " . $users . " - " . $lang['expires'] . ": " . ($grant_edit_expiry != "" ? nicedate($grant_edit_expiry) : $lang['never']));
                }
            } else {
                sql_query("delete from grant_edit where resource='{$ref}' and user in (" . implode(",", $urefs) . ")");
                sql_query("insert into grant_edit(resource,user,expiry) values ({$ref}," . join("),(" . $ref . ",", $inserttext) . ")");
                #log this
                global $lang;
                resource_log($ref, 's', "", "Grant Edit -  " . $users . " - " . $lang['expires'] . ": " . ($grant_edit_expiry != "" ? nicedate($grant_edit_expiry) : $lang['never']));
            }
        }
    }
    return true;
}
コード例 #6
0
function HookDiscount_codePurchase_callbackPayment_complete()
{
    # Find out the discount code applied to this collection.
    $code = sql_value("select discount_code value from collection_resource where collection='" . getvalescaped("custom", "") . "' limit 1", "");
    # Find out the purchasing user
    # As this is a callback script being called by PayPal, there is no login/authentication and we can't therefore simply use $userref.
    $user = sql_value("select ref value from user where current_collection='" . getvalescaped("custom", "") . "'", 0);
    # Insert used discount code row
    sql_query("insert into discount_code_used (code,user) values ('" . escape_check($code) . "','{$user}')");
}
コード例 #7
0
/**
 * Returns the size record from the database specified by its ID.
 */
function getImageFormat($size)
{
    if (empty($size)) {
        return array('width' => 0, 'height' => 0);
    }
    $results = sql_query("select * from preview_size where id='" . escape_check($size) . "'");
    if (empty($results)) {
        die('Unknown size: "' . $size . '"');
    }
    return $results[0];
}
コード例 #8
0
function message_add($users, $text, $url = "", $owner = null, $notification_type = MESSAGE_ENUM_NOTIFICATION_TYPE_SCREEN, $ttl_seconds = MESSAGE_DEFAULT_TTL_SECONDS)
{
    global $userref;
    $text = escape_check($text);
    $url = escape_check($url);
    if (!is_array($users)) {
        $users = array($users);
    }
    if (is_null($owner)) {
        $owner = $userref;
    }
    sql_query("INSERT INTO `message` (`owner`, `created`, `expires`, `message`, `url`) VALUES ({$owner}, NOW(), DATE_ADD(NOW(), INTERVAL {$ttl_seconds} SECOND), '{$text}', '{$url}')");
    $message_ref = sql_insert_id();
    foreach ($users as $user) {
        sql_query("INSERT INTO `user_message` (`user`, `message`) VALUES ({$user},{$message_ref})");
    }
}
コード例 #9
0
function getThemeList($parents = array())
{
    if (count($parents) == 0) {
        // just retrieve all the top level themes
        $sql = "select distinct theme as value from collection where theme is not null and theme <> '' order by theme";
    } else {
        // we were passed an array of parents, so we need to narrow our search
        for ($i = 1; $i < count($parents) + 1; $i++) {
            if ($i == 1) {
                $searchfield = 'theme';
            } else {
                $searchfield = "theme{$i}";
            }
            $whereclause = "{$searchfield} = '" . escape_check($parents[$i - 1]) . "' ";
        }
        $sql = "select distinct theme{$i} as value from collection where {$whereclause} and theme{$i} is not null and theme{$i} <> '' order by theme{$i}";
        //echo $sql;
    }
    $result = sql_array($sql);
    return $result;
}
コード例 #10
0
function HookUser_preferencesuser_preferencesSaveadditionaluserpreferences()
{
    global $user_preferences_change_username, $user_preferences_change_email, $user_preferences_change_name, $userref, $useremail, $username, $userfullname, $lang;
    $newUsername = trim(safe_file_name(getvalescaped('username', $username)));
    $newEmail = getvalescaped('email', $userfullname);
    $newFullname = getvalescaped('fullname', $userfullname);
    # Check if a user with that username already exists
    if ($user_preferences_change_username && $username != $newUsername) {
        $existing = sql_query('select ref from user where username=\'' . escape_check($newUsername) . '\'');
        if (!empty($existing)) {
            $GLOBALS['errorUsername'] = $lang['useralreadyexists'];
            return false;
        }
    }
    # Check if a user with that email already exists
    if ($user_preferences_change_email && $useremail != $newEmail) {
        $existing = sql_query('select ref from user where email=\'' . escape_check($newEmail) . '\'');
        if (!empty($existing)) {
            $GLOBALS['errorEmail'] = $lang['useremailalreadyexists'];
            return false;
        }
    }
    # Store changed values in DB, and update the global variables as header.php is included next
    if ($user_preferences_change_username && $username != $newUsername) {
        sql_query("update user set username='******' where ref='" . $userref . "'");
        $username = $newUsername;
    }
    if ($user_preferences_change_email && $useremail != $newEmail) {
        sql_query("update user set email='" . escape_check($newEmail) . "' where ref='" . $userref . "'");
        $useremail = $newEmail;
    }
    if ($user_preferences_change_name && $userfullname != $newFullname) {
        sql_query("update user set fullname='" . escape_check($newFullname) . "' where ref='" . $userref . "'");
        $userfullname = $newFullname;
    }
    return getvalescaped('currentpassword', '') == '' || getvalescaped('password', '') == '' && getvalescaped('password2', '') == '';
}
コード例 #11
0
function ProcessFolder($folder)
{
    #echo "<br>processing folder $folder";
    global $syncdir, $nogo, $max, $count, $done, $modtimes, $lastsync, $ffmpeg_preview_extension, $staticsync_autotheme, $staticsync_extension_mapping_default, $staticsync_extension_mapping, $staticsync_mapped_category_tree, $staticsync_title_includes_path, $staticsync_ingest, $staticsync_mapfolders, $staticsync_alternatives_suffix, $staticsync_alt_suffixes, $staticsync_alt_suffix_array, $file_minimum_age, $staticsync_run_timestamp;
    $collection = 0;
    echo "Processing Folder: {$folder}\n";
    # List all files in this folder.
    $dh = opendir($folder);
    echo date('Y-m-d H:i:s    ');
    echo "Reading from {$folder}\n";
    while (($file = readdir($dh)) !== false) {
        // because of alternative processing, some files may disappear during the run
        // that's ok - just ignore it and move on
        if (!file_exists($folder . "/" . $file)) {
            echo date('Y-m-d H:i:s    ');
            echo "File {$file} missing. Moving on.\n";
            continue;
        }
        $filetype = filetype($folder . "/" . $file);
        $fullpath = $folder . "/" . $file;
        $shortpath = str_replace($syncdir . "/", "", $fullpath);
        if ($staticsync_mapped_category_tree) {
            $path_parts = explode("/", $shortpath);
            array_pop($path_parts);
            touch_category_tree_level($path_parts);
        }
        # -----FOLDERS-------------
        if (($filetype == "dir" || $filetype == "link") && $file != "." && $file != ".." && strpos($nogo, "[" . $file . "]") === false && strpos($file, $staticsync_alternatives_suffix) === false) {
            # Recurse
            #echo "\n$file : " . filemtime($folder . "/" . $file) . " > " . $lastsync;
            if (true || strlen($lastsync) == "" || filemtime($folder . "/" . $file) > $lastsync - 26000) {
                ProcessFolder($folder . "/" . $file);
            }
        }
        # -------FILES---------------
        if ($filetype == "file" && substr($file, 0, 1) != "." && strtolower($file) != "thumbs.db" && !ss_is_alt($file)) {
            // we want to make sure we don't touch files that are too new
            // so check this
            if (time() - filectime($folder . "/" . $file) < $file_minimum_age) {
                echo date('Y-m-d H:i:s    ');
                echo "   {$file} too new -- skipping .\n";
                //echo filectime($folder . "/" . $file) . " " . time() . "\n";
                continue;
            }
            # Already exists?
            if (!in_array($shortpath, $done)) {
                $count++;
                if ($count > $max) {
                    return true;
                }
                echo date('Y-m-d H:i:s    ');
                echo "Processing file: {$fullpath}\n";
                if ($collection == 0 && $staticsync_autotheme) {
                    # Make a new collection for this folder.
                    $e = explode("/", $shortpath);
                    $theme = ucwords($e[0]);
                    $name = count($e) == 1 ? "" : $e[count($e) - 2];
                    echo date('Y-m-d H:i:s    ');
                    echo "\nCollection {$name}, theme={$theme}";
                    $collection = sql_value("select ref value from collection where name='" . escape_check($name) . "' and theme='" . escape_check($theme) . "'", 0);
                    if ($collection == 0) {
                        sql_query("insert into collection (name,created,public,theme,allow_changes) values ('" . escape_check($name) . "',now(),1,'" . escape_check($theme) . "',0)");
                        $collection = sql_insert_id();
                    }
                }
                # Work out extension
                $extension = explode(".", $file);
                $extension = trim(strtolower($extension[count($extension) - 1]));
                // if coming from collections or la folders, assume these are the resource types
                if (stristr(strtolower($fullpath), 'collection services/curatorial')) {
                    $type = 5;
                } elseif (stristr(strtolower($fullpath), 'collection services/conservation')) {
                    $type = 5;
                } elseif (stristr(strtolower($fullpath), 'collection services/library_archives')) {
                    $type = 6;
                } else {
                    # Work out a resource type based on the extension.
                    $type = $staticsync_extension_mapping_default;
                    reset($staticsync_extension_mapping);
                    foreach ($staticsync_extension_mapping as $rt => $extensions) {
                        if ($rt == 5 or $rt == 6) {
                            continue;
                        }
                        // we already eliminated those
                        if (in_array($extension, $extensions)) {
                            $type = $rt;
                        }
                    }
                }
                # Formulate a title
                if ($staticsync_title_includes_path) {
                    $title = str_ireplace("." . $extension, "", str_replace("/", " - ", $shortpath));
                    $title = ucfirst(str_replace("_", " ", $title));
                } else {
                    $title = str_ireplace("." . $extension, "", $file);
                }
                # Import this file
                $r = import_resource($shortpath, $type, $title, $staticsync_ingest);
                if ($r !== false) {
                    # Add to mapped category tree (if configured)
                    if (isset($staticsync_mapped_category_tree)) {
                        $basepath = "";
                        # Save tree position to category tree field
                        # For each node level, expand it back to the root so the full path is stored.
                        for ($n = 0; $n < count($path_parts); $n++) {
                            if ($basepath != "") {
                                $basepath .= "~";
                            }
                            $basepath .= $path_parts[$n];
                            $path_parts[$n] = $basepath;
                        }
                        update_field($r, $staticsync_mapped_category_tree, "," . join(",", $path_parts));
                        #echo "update_field($r,$staticsync_mapped_category_tree," . "," . join(",",$path_parts) . ");\n";
                    }
                    # StaticSync path / metadata mapping
                    # Extract metadata from the file path as per $staticsync_mapfolders in config.php
                    if (isset($staticsync_mapfolders)) {
                        foreach ($staticsync_mapfolders as $mapfolder) {
                            $match = $mapfolder["match"];
                            $field = $mapfolder["field"];
                            $level = $mapfolder["level"];
                            if (strpos("/" . $shortpath, $match) !== false) {
                                # Match. Extract metadata.
                                $path_parts = explode("/", $shortpath);
                                if ($level < count($path_parts)) {
                                    # Save the value
                                    print_r($path_parts);
                                    $value = $path_parts[$level - 1];
                                    update_field($r, $field, $value);
                                    echo " - Extracted metadata from path: {$value}\n";
                                }
                            }
                        }
                    }
                    // add the timestamp from this run to the keywords field to help retrieve this batch later
                    $currentkeywords = sql_value("select value from resource_data where resource = '{$r}' and resource_type_field = '1'", "");
                    if (strlen($currentkeywords) > 0) {
                        $currentkeywords .= ',';
                    }
                    update_field($r, 1, $currentkeywords . $staticsync_run_timestamp);
                    if (function_exists('staticsync_local_functions')) {
                        // if local cleanup functions have been defined, run them
                        staticsync_local_functions($r);
                    }
                    # Add any alternative files
                    $altpath = $fullpath . $staticsync_alternatives_suffix;
                    if ($staticsync_ingest && file_exists($altpath)) {
                        $adh = opendir($altpath);
                        while (($altfile = readdir($adh)) !== false) {
                            $filetype = filetype($altpath . "/" . $altfile);
                            if ($filetype == "file" && substr($file, 0, 1) != "." && strtolower($file) != "thumbs.db") {
                                # Create alternative file
                                global $lang;
                                # Find extension
                                $ext = explode(".", $altfile);
                                $ext = $ext[count($ext) - 1];
                                $aref = add_alternative_file($r, $altfile, strtoupper($ext) . " " . $lang["file"], $altfile, $ext, filesize_unlimited($altpath . "/" . $altfile));
                                $path = get_resource_path($r, true, "", true, $ext, -1, 1, false, "", $aref);
                                rename($altpath . "/" . $altfile, $path);
                                # Move alternative file
                            }
                        }
                    }
                    # check for alt files that match suffix list
                    if ($staticsync_alt_suffixes) {
                        $ss_nametocheck = substr($file, 0, strlen($file) - strlen($extension) - 1);
                        //review all files still in directory and see if they are alt files matching this one
                        $althandle = opendir($folder);
                        while (($altcandidate = readdir($althandle)) !== false) {
                            if ($filetype == "file" && substr($file, 0, 1) != "." && strtolower($file) != "thumbs.db") {
                                # Find extension
                                $ext = explode(".", $altcandidate);
                                $ext = $ext[count($ext) - 1];
                                $altcandidate_name = substr($altcandidate, 0, strlen($altcandidate) - strlen($ext) - 1);
                                $altcandidate_validated = false;
                                foreach ($staticsync_alt_suffix_array as $sssuffix) {
                                    if ($altcandidate_name == $ss_nametocheck . $sssuffix) {
                                        $altcandidate_validated = true;
                                        $thisfilesuffix = $sssuffix;
                                        break;
                                    }
                                }
                                if ($altcandidate_validated) {
                                    echo date('Y-m-d H:i:s    ');
                                    echo "    Attaching {$altcandidate} as alternative.\n";
                                    $filetype = filetype($folder . "/" . $altcandidate);
                                    # Create alternative file
                                    global $lang;
                                    if (preg_match("/^_VERSO[0-9]*/i", $thisfilesuffix)) {
                                        $alt_title = "Verso";
                                    } elseif (preg_match("/^_DNG[0-9]*/i", $thisfilesuffix)) {
                                        $alt_title = "DNG";
                                    } elseif (preg_match("/^_ORIG[0-9]*/i", $thisfilesuffix)) {
                                        $alt_title = "Original Scan";
                                    } elseif (preg_match("/^_TPV[0-9]*/i", $thisfilesuffix)) {
                                        $alt_title = "Title Page Verso";
                                    } elseif (preg_match("/^_TP[0-9]*/i", $thisfilesuffix)) {
                                        $alt_title = "Title Page";
                                    } elseif (preg_match("/^_COV[0-9]*/i", $thisfilesuffix)) {
                                        $alt_title = "Cover";
                                    } elseif (preg_match("/^_SCR[0-9]*/i", $thisfilesuffix)) {
                                        $alt_title = "Inscription";
                                    } elseif (preg_match("/^_EX[0-9]*/i", $thisfilesuffix)) {
                                        $alt_title = "Enclosure";
                                    } else {
                                        $alt_title = $altcandidate;
                                    }
                                    $aref = add_alternative_file($r, $alt_title, strtoupper($ext) . " " . $lang["file"], $altcandidate, $ext, filesize_unlimited($folder . "/" . $altcandidate));
                                    $path = get_resource_path($r, true, "", true, $ext, -1, 1, false, "", $aref);
                                    rename($folder . "/" . $altcandidate, $path);
                                    # Move alternative file
                                    global $alternative_file_previews;
                                    if ($alternative_file_previews) {
                                        create_previews($r, false, $ext, false, false, $aref);
                                    }
                                }
                            }
                        }
                    }
                    # Add to collection
                    if ($staticsync_autotheme) {
                        sql_query("insert into collection_resource(collection,resource,date_added) values ('{$collection}','{$r}',now())");
                    }
                    // fix permissions
                    // get directory to fix
                    global $scramble_key;
                    $permfixfolder = "/hne/rs/filestore/";
                    for ($n = 0; $n < strlen($r); $n++) {
                        $permfixfolder .= substr($r, $n, 1);
                        if ($n == strlen($r) - 1) {
                            $permfixfolder .= "_" . substr(md5($r . "_" . $scramble_key), 0, 15);
                        }
                        $permfixfolder .= "/";
                    }
                    exec("/bin/chown -R wwwrun {$permfixfolder}");
                    exec("/bin/chgrp -R www {$permfixfolder}");
                } else {
                    # Import failed - file still being uploaded?
                    echo date('Y-m-d H:i:s    ');
                    echo " *** Skipping file - it was not possible to move the file (still being imported/uploaded?) \n";
                }
            } else {
                # check modified date and update previews if necessary
                $filemod = filemtime($fullpath);
                if (array_key_exists($shortpath, $modtimes) && $filemod > strtotime($modtimes[$shortpath])) {
                    # File has been modified since we last created previews. Create again.
                    $rd = sql_query("select ref,has_image,file_modified,file_extension from resource where file_path='" . escape_check($shortpath) . "'");
                    if (count($rd) > 0) {
                        $rd = $rd[0];
                        $rref = $rd["ref"];
                        echo date('Y-m-d H:i:s    ');
                        echo "Resource {$rref} has changed, regenerating previews: {$fullpath}\n";
                        create_previews($rref, false, $rd["file_extension"]);
                        sql_query("update resource set file_modified=now() where ref='{$rref}'");
                    }
                }
            }
        }
    }
}
コード例 #12
0
     $aref = add_alternative_file($alternative, $plfilename);
     # Work out the extension
     $extension = explode(".", $plfilepath);
     $extension = trim(strtolower($extension[count($extension) - 1]));
     # Find the path for this resource.
     $path = get_resource_path($alternative, true, "", true, $extension, -1, 1, false, "", $aref);
     # Move the sent file to the alternative file location
     # PLUpload - file was sent chunked and reassembled - use the reassembled file location
     $result = rename($plfilepath, $path);
     if ($result === false) {
         exit("ERROR: File upload error. Please check the size of the file you are trying to upload.");
     }
     chmod($path, 0777);
     $file_size = @filesize_unlimited($path);
     # Save alternative file data.
     sql_query("update resource_alt_files set file_name='" . escape_check($plfilename) . "',file_extension='" . escape_check($extension) . "',file_size='" . $file_size . "',creation_date=now() where resource='{$alternative}' and ref='{$aref}'");
     if ($alternative_file_previews_batch) {
         create_previews($alternative, false, $extension, false, false, $aref);
     }
     echo "SUCCESS";
     exit;
 }
 if ($replace == "" && $replace_resource == "") {
     # Standard upload of a new resource
     $ref = copy_resource(0 - $userref);
     # Copy from user template
     # Add to collection?
     if ($collection_add != "") {
         add_resource_to_collection($ref, $collection_add);
     }
     # Log this
コード例 #13
0
<?php

/***
 * plugin.php - Maps requests to plugin pages to requested plugin.
 * 
 * @package ResourceSpace
 * @subpackage Plugins
 *
 ***/
# Define this page as an acceptable entry point.
define('RESOURCESPACE', true);
include '../include/db.php';
include '../include/general.php';
$query = explode('&', $_SERVER['QUERY_STRING']);
$plugin_query = explode('/', $query[0]);
if (!is_plugin_activated(escape_check($plugin_query[0]))) {
    die('Plugin does not exist or is not enabled');
}
if (isset($plugin_query[1])) {
    if (preg_match('/[\\/]/', $plugin_query[1])) {
        die('Invalid plugin page.');
    }
    $page_path = $baseurl_short . "plugins/{$plugin_query[0]}/pages/{$plugin_query[1]}.php";
    if (file_exists($page_path)) {
        include $page_path;
    } else {
        die('Plugin page not found.');
    }
} else {
    if (file_exists("../plugins/{$plugin_query[0]}/pages/index.php")) {
        include "../plugins/{$plugin_query[0]}/pages/index.php";
コード例 #14
0
<?php

include "../../../include/db.php";
include "../../../include/general.php";
if (array_key_exists("user", $_COOKIE)) {
    # Check to see if this user is logged in.
    $session_hash = $_COOKIE["user"];
    $loggedin = sql_value("select count(*) value from user where session='" . escape_check($session_hash) . "' and approved=1 and timestampdiff(second,last_active,now())<(30*60)", 0);
    if ($loggedin > 0 || $session_hash == "|") {
        # User is logged in. Proceed to full authentication.
        include "../../../include/authenticate.php";
    }
}
if (!isset($userref)) {
    # User is not logged in. Fetch username from posted form value.
    $username = getval("username", "");
    $usergroupname = "(Not logged in)";
    $userfullname = "";
    $anonymous_login = $username;
    $pagename = "terms";
    $plugins = array();
}
$error = "";
$errorfields = array();
$sent = false;
if (getval("send", "") != "") {
    $csvheaders = "\"date\"";
    $csvline = "\"" . date("Y-m-d") . "\"";
    $message = "Date: " . date("Y-m-d") . "\n";
    for ($n = 1; $n <= count($feedback_questions); $n++) {
        $type = $feedback_questions[$n]["type"];
コード例 #15
0
ファイル: edit.php プロジェクト: chandradrupal/resourcespace
$ref = getvalescaped("ref", "");
$resource = getvalescaped("resource", "");
# Check access
$edit_access = get_edit_access($resource);
if (!$edit_access) {
    exit("Access denied");
}
# Should never arrive at this page without edit access
if (getval("submitted", "") != "") {
    # Save license data
    # Construct expiry date
    $expires = getvalescaped("expires_year", "") . "-" . getvalescaped("expires_month", "") . "-" . getvalescaped("expires_day", "");
    # Construct usage
    $license_usage = "";
    if (isset($_POST["license_usage"])) {
        $license_usage = escape_check(join(", ", $_POST["license_usage"]));
    }
    if ($ref == "new") {
        # New record
        sql_query("insert into resource_license (resource,outbound,holder,license_usage,description,expires) values ('" . getvalescaped("resource", "") . "', '" . getvalescaped("outbound", "") . "', '" . getvalescaped("holder", "") . "', '{$license_usage}', '" . getvalescaped("description", "") . "', '{$expires}')");
        $ref = sql_insert_id();
        resource_log($resource, "", "", $lang["new_license"] . " " . $ref);
    } else {
        # Existing record
        sql_query("update resource_license set outbound='" . getvalescaped("outbound", "") . "',holder='" . getvalescaped("holder", "") . "', license_usage='{$license_usage}',description='" . getvalescaped("description", "") . "',expires='{$expires}' where ref='{$ref}' and resource='{$resource}'");
        resource_log($resource, "", "", $lang["edit_license"] . " " . $ref);
    }
    redirect("pages/view.php?ref=" . $resource);
}
# Fetch license data
if ($ref == "new") {
コード例 #16
0
ファイル: general.php プロジェクト: artsmia/mia_resourcespace
function create_password_reset_key($username)
{
    global $scramble_key;
    $resetuniquecode = make_password();
    $password_reset_hash = hash('sha256', date("Ymd") . md5("RS" . $resetuniquecode . $username . $scramble_key));
    sql_query("update user set password_reset_hash='{$password_reset_hash}' where username='******'");
    $password_reset_url_key = substr(hash('sha256', date("Ymd") . $password_reset_hash . $username . $scramble_key), 0, 15);
    return $password_reset_url_key;
}
コード例 #17
0
ファイル: crop.php プロジェクト: claytondaley/resourcespace
 // avoid bad characters in filenames
 $filename = preg_replace("/[^A-Za-z0-9_\\- ]/", '', $filename);
 //$filename = str_replace(' ','_',trim($filename));
 // if there is not a filename, create one
 if ($cropper_custom_filename && strlen($filename) > 0) {
     $filename = "{$filename}";
 } else {
     if (!$alternative_file_previews || $download || getval("slideshow", "") != "") {
         $filename = $ref . "_" . strtolower($lang['transformed']);
     } elseif ($original && !$cropperestricted) {
         // fixme
     } else {
         $filename = "alt_{$newfile}";
     }
 }
 $filename = escape_check($filename);
 $lcext = strtolower($new_ext);
 $mpcalc = round($newfilewidth * $newfileheight / 1000000, 1);
 // don't show  a megapixel count if it rounded down to 0
 if ($mpcalc > 0) {
     $mptext = " ({$mpcalc} " . $lang["megapixel-short"] . ")";
 } else {
     $mptext = '';
 }
 if (strlen($mydesc) > 0) {
     $deschyphen = ' - ';
 } else {
     $deschyphen = '';
 }
 // Do something with the final file:
 if ($cropper_enable_alternative_files && !$download && !$original && getval("slideshow", "") == "" && !$cropperestricted) {
コード例 #18
0
            $accepted = sql_value("select accepted_terms value from user where username='******' and (password='******' or password='******'password_hash'] . "')", 0);
            if ($accepted == 0 && $terms_login && !checkperm("p")) {
                redirect("pages/terms.php?noredir=true&url=" . urlencode("pages/user/user_change_password.php"));
            } else {
                redirect($url);
            }
        } else {
            sleep($password_brute_force_delay);
            $error = $result['error'];
            hook("dispcreateacct");
        }
    }
}
if (getval("logout", "") != "" && array_key_exists("user", $_COOKIE)) {
    #fetch username and update logged in status
    $session = escape_check($_COOKIE["user"]);
    sql_query("update user set logged_in=0,session='' where session='{$session}'");
    hook("removeuseridcookie");
    #blank cookie
    rs_setcookie("user", "", time() - 3600);
    # Also blank search related cookies
    setcookie("search", "", 0, '', '', false, true);
    setcookie("saved_offset", "", 0, '', '', false, true);
    setcookie("saved_archive", "", 0, '', '', false, true);
    unset($username);
    hook("postlogout");
    if (isset($anonymous_login)) {
        # If the system is set up with anonymous access, redirect to the home page after logging out.
        redirect("pages/" . $default_home_page);
    }
}
コード例 #19
0
ファイル: staticsync.php プロジェクト: vachanda/ResourceSpace
function ProcessFolder($folder, $version_dir, &$resource_array, &$resource_error)
{
    global $lang, $syncdir, $nogo, $staticsync_max_files, $count, $done, $modtimes, $lastsync, $ffmpeg_preview_extension, $staticsync_autotheme, $staticsync_folder_structure, $staticsync_extension_mapping_default, $staticsync_extension_mapping, $staticsync_mapped_category_tree, $staticsync_title_includes_path, $staticsync_ingest, $staticsync_mapfolders, $staticsync_alternatives_suffix, $theme_category_levels, $staticsync_defaultstate, $additional_archive_states, $staticsync_extension_mapping_append_values, $image_alternatives, $exclude_resize, $post_host, $media_endpoint, $image_required_height, $sync_bucket, $aws_key, $aws_secret_key;
    $collection = 0;
    echo "Processing Folder: {$folder}" . PHP_EOL;
    #$alt_path = get_resource_path(59, TRUE, '', FALSE, 'png', -1, 1, FALSE, '', 4);
    # List all files in this folder.
    $dh = opendir($folder);
    while (($file = readdir($dh)) !== false) {
        if ($file == '.' || $file == '..') {
            continue;
        }
        $filetype = filetype($folder . "/" . $file);
        $fullpath = $folder . "/" . $file;
        $shortpath = str_replace($syncdir . "/", '', $fullpath);
        # Work out extension
        $extension = explode(".", $file);
        if (count($extension) > 1) {
            $extension = trim(strtolower($extension[count($extension) - 1]));
        } else {
            //No extension
            $extension = "";
        }
        if (strpos($fullpath, $nogo)) {
            echo "This directory is to be ignored." . PHP_EOL;
            continue;
        }
        if ($staticsync_mapped_category_tree) {
            $path_parts = explode("/", $shortpath);
            array_pop($path_parts);
            touch_category_tree_level($path_parts);
        }
        # -----FOLDERS-------------
        if (($filetype == "dir" || $filetype == "link") && strpos($nogo, "[{$file}]") === false && strpos($file, $staticsync_alternatives_suffix) === false) {
            # Get current version direcotries.
            if (preg_match("/[0-9]{2}-[0-9]{2}-[0-9]{4}\$/", $file)) {
                if (!in_array($file, $version_dir)) {
                    array_push($version_dir, $file);
                }
                if (preg_match('/in_progress*/', $file)) {
                    echo "The Barcode is still being processed." . PHP_EOL;
                    continue;
                }
            }
            # Recurse
            ProcessFolder($folder . "/" . $file, $version_dir, $resource_array, $resource_error);
        }
        $psd_files = array();
        if (preg_match('/images/', $fullpath)) {
            $path_array = explode('/', $fullpath);
            $psd_array = array_splice($path_array, 0, array_search('images', $path_array));
            $psd_path = implode('/', $psd_array) . '/psd/';
            $psd_files = array_diff(scandir($psd_path), array('..', '.'));
            foreach ($psd_files as $index => $psd_file) {
                $psd_files[$index] = pathinfo($psd_file, PATHINFO_FILENAME);
            }
        }
        # -------FILES---------------
        if ($filetype == "file" && substr($file, 0, 1) != "." && strtolower($file) != "thumbs.db") {
            /* Below Code Adapted  from CMay's bug report */
            global $banned_extensions;
            # Check to see if extension is banned, do not add if it is banned
            if (array_search($extension, $banned_extensions)) {
                continue;
            }
            /* Above Code Adapted from CMay's bug report */
            $count++;
            if ($count > $staticsync_max_files) {
                return true;
            }
            $last_sync_date = sql_value("select value from sysvars where name = 'last_sync'", "");
            $file_creation_date = date("Y-m-d H:i:s", filectime($fullpath));
            if (isset($last_sync_date) && $last_sync_date > $file_creation_date) {
                echo "No new file found.." . PHP_EOL;
                continue;
            }
            # Already exists?
            if (!isset($done[$shortpath])) {
                echo "Processing file: {$fullpath}" . PHP_EOL;
                if ($collection == 0 && $staticsync_autotheme) {
                    # Make a new collection for this folder.
                    $e = explode("/", $shortpath);
                    $theme = ucwords($e[0]);
                    $themesql = "theme='" . ucwords(escape_check($e[0])) . "'";
                    $themecolumns = "theme";
                    $themevalues = "'" . ucwords(escape_check($e[0])) . "'";
                    if ($staticsync_folder_structure) {
                        for ($x = 0; $x < count($e) - 1; $x++) {
                            if ($x != 0) {
                                $themeindex = $x + 1;
                                if ($themeindex > $theme_category_levels) {
                                    $theme_category_levels = $themeindex;
                                    if ($x == count($e) - 2) {
                                        echo PHP_EOL . PHP_EOL . "UPDATE THEME_CATEGORY_LEVELS TO {$themeindex} IN CONFIG!!!!" . PHP_EOL . PHP_EOL;
                                    }
                                }
                                $th_name = ucwords(escape_check($e[$x]));
                                $themesql .= " AND theme{$themeindex} = '{$th_name}'";
                                $themevalues .= ",'{$th_name}'";
                                $themecolumns .= ",theme{$themeindex}";
                            }
                        }
                    }
                    $name = count($e) == 1 ? '' : $e[count($e) - 2];
                    echo "Collection {$name}, theme={$theme}" . PHP_EOL;
                    $ul_username = $theme;
                    $escaped_name = escape_check($name);
                    $collection = sql_value("SELECT ref value FROM collection WHERE name='{$escaped_name}' AND {$themesql}", 0);
                    if ($collection == 0) {
                        sql_query("INSERT INTO collection (name,created,public,{$themecolumns},allow_changes)\n                                                   VALUES ('{$escaped_name}', NOW(), 1, {$themevalues}, 0)");
                        $collection = sql_insert_id();
                    }
                }
                # Work out a resource type based on the extension.
                $type = $staticsync_extension_mapping_default;
                reset($staticsync_extension_mapping);
                foreach ($staticsync_extension_mapping as $rt => $extensions) {
                    if (in_array($extension, $extensions)) {
                        $type = $rt;
                    }
                }
                $modified_type = hook('modify_type', 'staticsync', array($type));
                if (is_numeric($modified_type)) {
                    $type = $modified_type;
                }
                # Formulate a title
                if ($staticsync_title_includes_path) {
                    $title_find = array('/', '_', ".{$extension}");
                    $title_repl = array(' - ', ' ', '');
                    $title = ucfirst(str_ireplace($title_find, $title_repl, $shortpath));
                } else {
                    $title = str_ireplace(".{$extension}", '', $file);
                }
                $modified_title = hook('modify_title', 'staticsync', array($title));
                if ($modified_title !== false) {
                    $title = $modified_title;
                }
                # Import this file
                #$r = import_resource($shortpath, $type, $title, $staticsync_ingest);
                #Check for file name containing the psd.
                if (!empty($psd_files)) {
                    $image_file_array = explode('/', $fullpath);
                    $image_file = $image_file_array[count($image_file_array) - 1];
                    $image_psd_name = explode('_', $image_file)[0];
                    if (array_search($image_psd_name, $psd_files)) {
                        #Image name is in right format.
                        if (!validate_image_size($fullpath, $image_required_height)) {
                            $resource_error['size'][$file] = $fullpath;
                        }
                        $r = import_resource($fullpath, $type, $title, $staticsync_ingest);
                        sql_query("INSERT INTO resource_data (resource,resource_type_field,value)\n                               VALUES ('{$r}', (SELECT ref FROM resource_type_field WHERE name = 'logical_id'), '{$image_psd_name}')");
                        $original_filepath = sql_query("SELECT value FROM resource_data WHERE resource = '{$r}' AND\n                                                     resource_type_field = (SELECT ref FROM resource_type_field where name = 'original_filepath')");
                        if (isset($original_filepath)) {
                            sql_query("INSERT INTO resource_data (resource,resource_type_field,value)\n                                 VALUES ('{$r}',(SELECT ref FROM resource_type_field WHERE name = 'original_filepath'), '{$fullpath}')");
                        }
                    } else {
                        echo "Filename '{$fullpath}' is not in right format.." . PHP_EOL;
                        $resource_error['name'][$file] = $fullpath;
                        continue;
                    }
                } elseif (word_in_string($exclude_resize, explode('/', $fullpath))) {
                    $r = import_resource($fullpath, $type, $title, $staticsync_ingest);
                }
                if ($r !== false) {
                    array_push($resource_array, $r);
                    # Create current version for resource.
                    #print_r($version_dir);
                    if (count($version_dir) == 1) {
                        sql_query("INSERT into resource_data (resource,resource_type_field,value)\n                                    VALUES ('{$r}',(SELECT ref FROM resource_type_field WHERE name = 'current'), 'TRUE')");
                    }
                    $sync_status = sync_to_s3($syncdir, $sync_bucket, $aws_key, $aws_secret_key);
                    if (!$sync_status) {
                        echo "Failed to sync";
                    }
                    # Add to mapped category tree (if configured)
                    if (isset($staticsync_mapped_category_tree)) {
                        $basepath = '';
                        # Save tree position to category tree field
                        # For each node level, expand it back to the root so the full path is stored.
                        for ($n = 0; $n < count($path_parts); $n++) {
                            if ($basepath != '') {
                                $basepath .= "~";
                            }
                            $basepath .= $path_parts[$n];
                            $path_parts[$n] = $basepath;
                        }
                        update_field($r, $staticsync_mapped_category_tree, "," . join(",", $path_parts));
                    }
                    #This is an override to add user data to the resouces
                    if (!isset($userref)) {
                        $ul_username = ucfirst(strtolower($ul_username));
                        $current_user_ref = sql_query("Select ref from user where username = '******' ");
                        if (!empty($current_user_ref)) {
                            $current_user_ref = $current_user_ref[0]['ref'];
                            sql_query("UPDATE resource SET created_by='{$current_user_ref}' where ref = {$r}");
                        }
                    }
                    # default access level. This may be overridden by metadata mapping.
                    $accessval = 0;
                    # StaticSync path / metadata mapping
                    # Extract metadata from the file path as per $staticsync_mapfolders in config.php
                    if (isset($staticsync_mapfolders)) {
                        foreach ($staticsync_mapfolders as $mapfolder) {
                            $match = $mapfolder["match"];
                            $field = $mapfolder["field"];
                            $level = $mapfolder["level"];
                            if (strpos("/" . $shortpath, $match) !== false) {
                                # Match. Extract metadata.
                                $path_parts = explode("/", $shortpath);
                                if ($level < count($path_parts)) {
                                    // special cases first.
                                    if ($field == 'access') {
                                        # access level is a special case
                                        # first determine if the value matches a defined access level
                                        $value = $path_parts[$level - 1];
                                        for ($n = 0; $n < 3; $n++) {
                                            # if we get an exact match or a match except for case
                                            if ($value == $lang["access" . $n] || strtoupper($value) == strtoupper($lang['access' . $n])) {
                                                $accessval = $n;
                                                echo "Will set access level to " . $lang['access' . $n] . " ({$n})" . PHP_EOL;
                                            }
                                        }
                                    } else {
                                        if ($field == 'archive') {
                                            # archive level is a special case
                                            # first determin if the value matches a defined archive level
                                            $value = $mapfolder["archive"];
                                            $archive_array = array_merge(array(-2, -1, 0, 1, 2, 3), $additional_archive_states);
                                            if (in_array($value, $archive_array)) {
                                                $archiveval = $value;
                                                echo "Will set archive level to " . $lang['status' . $value] . " ({$archiveval})" . PHP_EOL;
                                            }
                                        } else {
                                            # Save the value
                                            #print_r($path_parts);
                                            $value = $path_parts[$level - 1];
                                            if ($staticsync_extension_mapping_append_values) {
                                                $given_value = $value;
                                                // append the values if possible...not used on dropdown, date, categroy tree, datetime, or radio buttons
                                                $field_info = get_resource_type_field($field);
                                                if (in_array($field['type'], array(0, 1, 2, 4, 5, 6, 7, 8))) {
                                                    $old_value = sql_value("select value value from resource_data where resource={$r} and resource_type_field={$field}", "");
                                                    $value = append_field_value($field_info, $value, $old_value);
                                                }
                                            }
                                            update_field($r, $field, trim($value));
                                            if (strtotime(trim($value))) {
                                                add_keyword_mappings($r, trim($value), $field, false, true);
                                            } else {
                                                add_keyword_mappings($r, trim($value), $field);
                                            }
                                            if ($staticsync_extension_mapping_append_values) {
                                                $value = $given_value;
                                            }
                                            echo " - Extracted metadata from path: {$value}" . PHP_EOL;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    #Resize only original images.
                    if (!word_in_string($exclude_resize, explode('/', $fullpath))) {
                        echo "Creating preview..";
                        create_previews($r, false, $extension, false, false, -1, false, $staticsync_ingest);
                    }
                    # update access level
                    sql_query("UPDATE resource SET access = '{$accessval}',archive='{$staticsync_defaultstate}' WHERE ref = '{$r}'");
                    # Add any alternative files
                    $altpath = $fullpath . $staticsync_alternatives_suffix;
                    if ($staticsync_ingest && file_exists($altpath)) {
                        $adh = opendir($altpath);
                        while (($altfile = readdir($adh)) !== false) {
                            $filetype = filetype($altpath . "/" . $altfile);
                            if ($filetype == "file" && substr($file, 0, 1) != "." && strtolower($file) != "thumbs.db") {
                                # Create alternative file
                                # Find extension
                                $ext = explode(".", $altfile);
                                $ext = $ext[count($ext) - 1];
                                $description = str_replace("?", strtoupper($ext), $lang["originalfileoftype"]);
                                $file_size = filesize_unlimited($altpath . "/" . $altfile);
                                $aref = add_alternative_file($r, $altfile, $description, $altfile, $ext, $file_size);
                                $path = get_resource_path($r, true, '', true, $ext, -1, 1, false, '', $aref);
                                rename($altpath . "/" . $altfile, $path);
                                # Move alternative file
                            }
                        }
                    }
                    # Add to collection
                    if ($staticsync_autotheme) {
                        $test = '';
                        $test = sql_query("SELECT * FROM collection_resource WHERE collection='{$collection}' AND resource='{$r}'");
                        if (count($test) == 0) {
                            sql_query("INSERT INTO collection_resource (collection, resource, date_added)\n                                            VALUES ('{$collection}', '{$r}', NOW())");
                        }
                    }
                } else {
                    # Import failed - file still being uploaded?
                    echo " *** Skipping file - it was not possible to move the file (still being imported/uploaded?)" . PHP_EOL;
                }
            } else {
                # check modified date and update previews if necessary
                $filemod = filemtime($fullpath);
                if (array_key_exists($shortpath, $modtimes) && $filemod > strtotime($modtimes[$shortpath])) {
                    # File has been modified since we last created previews. Create again.
                    $rd = sql_query("SELECT ref, has_image, file_modified, file_extension FROM resource\n                                        WHERE file_path='" . escape_check($shortpath) . "'");
                    if (count($rd) > 0) {
                        $rd = $rd[0];
                        $rref = $rd["ref"];
                        echo "Resource {$rref} has changed, regenerating previews: {$fullpath}" . PHP_EOL;
                        extract_exif_comment($rref, $rd["file_extension"]);
                        # extract text from documents (e.g. PDF, DOC).
                        global $extracted_text_field;
                        if (isset($extracted_text_field)) {
                            if (isset($unoconv_path) && in_array($extension, $unoconv_extensions)) {
                                // omit, since the unoconv process will do it during preview creation below
                            } else {
                                extract_text($rref, $extension);
                            }
                        }
                        # Store original filename in field, if set
                        global $filename_field;
                        if (isset($filename_field)) {
                            update_field($rref, $filename_field, $file);
                        }
                        create_previews($rref, false, $rd["file_extension"], false, false, -1, false, $staticsync_ingest);
                        sql_query("UPDATE resource SET file_modified=NOW() WHERE ref='{$rref}'");
                    }
                }
            }
        }
    }
}
コード例 #20
0
function delete_resource_custom_access_usergroups($ref)
{
    # delete all usergroup specific access to resource $ref
    sql_query("delete from resource_custom_access where resource='" . escape_check($ref) . "' and usergroup is not null");
}
コード例 #21
0
function populate_metadata_from_dump($id, $meta)
{
    global $fields_title, $fields_embeddedequiv, $fields_type, $optionlists;
    // read in the metadata file and dump it into the right places in the database
    $metadump = file_get_contents($meta);
    // lazy solution: the resourcespace XML namespace is not formally defined
    // and thus the docs will not validate. For now we're just going to do some
    // regex magic to get rid of the namespaces alltogether. Fixme - would be
    // nice to make the metadump files validate
    $metadump = preg_replace('/([<\\/])([a-z0-9]+):/i', '$1$2', $metadump);
    $metadump = preg_replace('/(resourcespace):(resourceid="\\d+">)/i', '$1$2', $metadump);
    # Fix an issue whereby the resourcespace namespace is not defined. Add a fake namespace to the header.
    $metadump = str_replace("xmlns:dc", "xmlns:resourcespace='http://www.resourcespace.org' xmlns:dc", $metadump);
    $metadump = stripInvalidXml($metadump);
    //echo $metadump;
    $xml = new SimpleXMLElement($metadump);
    //print_r($xml);
    //echo "\n field ref for title is " . $xml->dctitle['rsfieldref'] . "\n";
    foreach ($xml as $fieldxml) {
        if ($fieldxml == '') {
            continue;
        }
        $value = $fieldxml;
        $rsfieldtitle = $fieldxml['rsfieldtitle'];
        $rsembeddedequiv = $fieldxml['rsembeddedequiv'];
        $rsfieldref = $fieldxml['rsfieldref'];
        $rsfieldtype = $fieldxml['rsfieldtype'];
        echo "\n==========\n";
        echo "   rsfieldtitle: {$rsfieldtitle}\n";
        echo " rsembeddedequiv: {$rsembeddedequiv}\n";
        echo "     rsfieldref: {$rsfieldref}\n";
        echo "    rsfieldtype: {$rsfieldtype}\n";
        echo "          value: {$value}\n";
        $rsfieldtitle = escape_check($rsfieldtitle);
        $newid = sql_value("select ref value from resource_type_field where title = '{$rsfieldtitle}' and type = '{$rsfieldtype}'", 0);
        if ($newid > 0) {
            $finalid = $newid;
        } else {
            if ($rsfieldtype == '7') {
                // category trees are too complicated to construct, so we're going to treat them as text fields for now.
                $rsfieldtype = '1';
            }
            $sql = "insert into resource_type_field (title,type,name) values ('{$rsfieldtitle}','{$rsfieldtype}','{$rsembeddedequiv}')";
            $result = sql_query($sql);
            $finalid = sql_insert_id();
        }
        if ($rsfieldtype == 2 || $rsfieldtype == 3) {
            if (!isset($optionlists[$finalid])) {
                $optionlists[$finalid] = array();
            }
            if (!in_array($value, $optionlists[$finalid])) {
                $optionlists[$finalid][] = $value;
            }
        }
        $fields_title["{$rsfieldref}"] = $rsfieldtitle;
        $fields_embeddedequiv["{$rsfieldref}"] = $rsembeddedequiv;
        $fields_type["{$rsfieldref}"] = $rsfieldtype;
        $value = escape_check($value);
        $sql = "insert into resource_data (resource, resource_type_field, value) values ('{$id}','{$rsfieldref}','{$value}')";
        sql_query($sql);
    }
}
コード例 #22
0
ファイル: db.php プロジェクト: chandradrupal/resourcespace
function pagename()
{
    $name = safe_file_name(getvalescaped('pagename', ''));
    if (!empty($name)) {
        return $name;
    }
    $url = str_replace("\\", "/", $_SERVER["PHP_SELF"]);
    // To work with Windows command line scripts
    $urlparts = explode("/", $url);
    $url = $urlparts[count($urlparts) - 1];
    return escape_check($url);
}
コード例 #23
0
function collection_set_themes($collection, $themearr)
{
    // add theme categories to this collection
    if (is_numeric($collection) && is_array($themearr)) {
        global $theme_category_levels;
        $clause = '';
        for ($i = 0; $i < $theme_category_levels; $i++) {
            if ($i == 0) {
                $column = 'theme';
            } else {
                $column = "theme" . ($i + 1);
            }
            if (isset($themearr[$i])) {
                if (strlen($clause) > 0) {
                    $clause .= ", ";
                }
                $clause .= " {$column} = '" . escape_check($themearr[$i]) . "' ";
            }
        }
        if (strlen($clause) > 0) {
            $sql = "update collection set {$clause} where ref = '{$collection}'";
            sql_query($sql);
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}
コード例 #24
0
function get_resource_files($ref,$includeorphan=false){
    // returns array of all files associated with a resource
    // if $includeorphan set to true, will also return all files in the
    // resource dir even if the system doesn't understand why they're there.

    $filearray = array();
    $file_checklist = array();

    global $config_windows;
    if ($config_windows){ $sep = "\\"; } else { $sep = "/"; }


    $sizearray = sql_array("select id value from preview_size",false);
    $original_ext = sql_value("select file_extension value from resource where ref = '".escape_check($ref)."'",'');

    $rootpath=dirname(get_resource_path($ref,true,"pre",true));

    // get listing of all files in resource dir to compare mark off as we find them
    if (is_dir($rootpath)) {
    if ($dh = opendir($rootpath)) {
            while (($file = readdir($dh)) !== false) {
                if (!($file == '.' || $file == '..')){
                    $file_checklist[$rootpath.$sep.$file] = 1;
                }
            }
            closedir($dh);
        }
    }

    // first get the resource itself
    $original = get_resource_path($ref,true,'',false,$original_ext);
    if (file_exists($original)){
	    array_push($filearray,$original);
	    unset($file_checklist[$original]);
    }

    // in some cases, the system also generates a jpeg equivalent of the original, so check for that
    $original = get_resource_path($ref,true,'',false,'jpg');
    if (file_exists($original)){
	    array_push($filearray,$original);
    	unset($file_checklist[$original]);
    }

    // in some cases, the system also generates an mp3 equivalent of the original, so check for that
    $original = get_resource_path($ref,true,'',false,'mp3');
    if (file_exists($original)){
    	array_push($filearray,$original);
    	unset($file_checklist[$original]);
    }

    // in some cases, the system also generates an extracted icc profile, so check for that
    $original = get_resource_path($ref,true,'',false,'icc');
    if (file_exists($original)){
    	array_push($filearray,$original);
    	unset($file_checklist[$original]);
    }


    # check for pages
    $page = 1;
    $misscount = 0;
    // just to be safe, we'll try at least 4 pages ahead to make sure none got skipped
    while($misscount < 4){
        $thepath = get_resource_path($ref,true,"scr",false,'jpg',-1,$page,"","","");
        if (file_exists($thepath)){
            array_push($filearray,$thepath);
            unset($file_checklist[$thepath]);
            $page++;
        } else {
            $misscount++;
            $page++;
        }
    }        

    // now look for other sizes
    foreach($sizearray as $size){
        $thepath = get_resource_path($ref,true,$size,false,'jpg');
        if (file_exists($thepath)){
            array_push($filearray,$thepath);
            unset($file_checklist[$thepath]);
        }
    }


    // get alternative files
    $altfiles = get_alternative_files($ref);
    foreach($altfiles as $altfile){
        // first get original
        $alt_ext = sql_value("select file_extension value from resource_alt_files where ref = '" . $altfile['ref'] . "'",'');
        $thepath = get_resource_path($ref,true,'',false,$alt_ext,-1,1,false,"",$altfile["ref"]);
        if (file_exists($thepath)){
            array_push($filearray,$thepath);
            unset($file_checklist[$thepath]);
        }


        // now check for previews
        foreach($sizearray as $size){
            $thepath = get_resource_path($ref,true,$size,false,"jpg",-1,1,false,"",$altfile["ref"]);
            if (file_exists($thepath)){
                array_push($filearray,$thepath);
                unset($file_checklist[$thepath]);
            }
        }

        # check for pages
        $page = 1;
        while($page <> 0){
            $thepath = get_resource_path($ref,true,"scr",false,'jpg',-1,$page,"","",$altfile['ref']);
            if (file_exists($thepath)){
                array_push($filearray,$thepath);
                unset($file_checklist[$thepath]);
                $page++;
            } else {
                $page = 0;
            }
        }
        // in some cases, the system also generates a jpeg equivalent of the original, so check for that
        $original = get_resource_path($ref,true,'',false,'jpg',-1,1,'','',$altfile['ref']);
	if (file_exists($original)){
	        array_push($filearray,$original);
        	unset($file_checklist[$original]);
    	}

        // in some cases, the system also generates a mp3 equivalent of the original, so check for that
        $original = get_resource_path($ref,true,'',false,'mp3',-1,1,'','',$altfile['ref']);
	if (file_exists($original)){
	        array_push($filearray,$original);
       		unset($file_checklist[$original]);
	}

        // in some cases, the system also generates an extracted icc profile, so check for that
        $original = get_resource_path($ref,true,'',false,'icc',-1,1,'','',$altfile['ref']);
	if (file_exists($original)){
	        array_push($filearray,$original);
       		unset($file_checklist[$original]);
	}
    }


    // check for metadump
    $thefile="$rootpath/metadump.xml";
    if (file_exists($thefile)){
        array_push($filearray,$thefile);
        unset($file_checklist[$thefile]);
    }

    // check for ffmpeg previews
    global $ffmpeg_preview_extension;
    $flvfile=get_resource_path($ref,true,"pre",false,$ffmpeg_preview_extension);
    if (file_exists($flvfile)){
        array_push($filearray,$flvfile);
        unset($file_checklist[$flvfile]);
    }


    if (count($file_checklist)>0){
	foreach (array_keys($file_checklist) as $thefile){
		error_log("ResourceSpace: Orphaned file, resource $ref: $thefile");
	        if ($includeorphan) {
			array_push($filearray,$thefile);
		}
       }
    }
    return array_unique($filearray);
}
コード例 #25
0
function empty_user_dash($user, $purge = true)
{
    $usertiles = sql_query("SELECT dash_tile FROM user_dash_tile WHERE user_dash_tile.user='******'");
    sql_query("DELETE FROM user_dash_tile WHERE user='******'");
    if ($purge) {
        foreach ($usertiles as $tile) {
            $existing = sql_query("SELECT count(*) as 'count' FROM user_dash_tile WHERE dash_tile='" . $tile["dash_tile"] . "'");
            if ($existing[0]["count"] < 1) {
                delete_dash_tile($tile["dash_tile"]);
            }
        }
    }
}
コード例 #26
0
ファイル: index.php プロジェクト: claytondaley/resourcespace
 # Store original filename in field, if set
 global $filename_field;
 if (isset($filename_field)) {
     $wait = update_field($ref, $filename_field, $_FILES['userfile']['name']);
 }
 // extract metadata
 $wait = extract_exif_comment($ref, $extension);
 $resource = get_resource_data($ref);
 //create previews
 if ($camera_autorotation) {
     AutoRotateImage($filepath);
 }
 $wait = create_previews($ref, false, $extension);
 // add resource to collection
 if ($collection != "") {
     $collection_exists = sql_value("select name value from collection where ref='" . escape_check($collection) . "'", "");
     if ($collection_exists != "") {
         if (!add_resource_to_collection($ref, $collection)) {
             header("HTTP/1.0 403 Forbidden.");
             echo "HTTP/1.0 403 Forbidden. Collection is not writable by this user.\n";
             exit;
         }
     } else {
         header("HTTP/1.0 403 Forbidden.");
         echo "HTTP/1.0 403 Forbidden. Collection does not exist.\n";
         exit;
     }
 }
 // make sure non-required fields get written. Note this behavior is somewhat different than in the system since these override extracted data
 reset($_POST);
 reset($_GET);
コード例 #27
0
function generate_session_hash($password_hash)
{
    # Generates a unique session hash
    global $randomised_session_hash, $scramble_key;
    if ($randomised_session_hash) {
        # Completely randomised session hashes. May be more secure, but allows only one user at a time.
        while (true) {
            $session = md5(rand() . microtime());
            if (sql_value("select count(*) value from user where session='" . escape_check($session) . "'", 0) == 0) {
                return $session;
            }
            # Return a unique hash only.
        }
    } else {
        # Session hash is based on the password hash and the date, so there is one new session hash each day. Allows two users to use the same login.
        $suffix = "";
        while (true) {
            $session = md5($scramble_key . $password_hash . date("Ymd") . $suffix);
            if (sql_value("select count(*) value from user where session='" . escape_check($session) . "' and password<>'" . escape_check($password_hash) . "'", 0) == 0) {
                return $session;
            }
            # Return a unique hash only.
            $suffix .= ".";
            # Extremely unlikely case that this was not a unique session (hash collision) - alter the string slightly and try again.
        }
    }
}
コード例 #28
0
                    unlink($apathtmp);
                }
            }
            if (file_exists($apath)) {
                # Update the database with the new file details.
                $file_size = filesize_unlimited($apath);
                # SQL Connection may have hit a timeout
                sql_connect();
                sql_query("update resource_alt_files set file_name='" . escape_check($ffmpeg_alternatives[$n]["filename"] . "." . $ffmpeg_alternatives[$n]["extension"]) . "',file_extension='" . escape_check($ffmpeg_alternatives[$n]["extension"]) . "',file_size='" . $file_size . "',creation_date=now() where ref='{$aref}'");
                // add this filename to be added to resource.ffmpeg_alt_previews
                if (isset($ffmpeg_alternatives[$n]['alt_preview']) && $ffmpeg_alternatives[$n]['alt_preview'] == true) {
                    $ffmpeg_alt_previews[] = basename($apath);
                }
            }
        }
        /*// update the resource table with any ffmpeg_alt_previews	
        		if (count($ffmpeg_alt_previews)>0){
        			$ffmpeg_alternative_previews=implode(",",$ffmpeg_alt_previews);
        			sql_query("update resource set ffmpeg_alt_previews='".escape_check($ffmpeg_alternative_previews)."' where ref='$ref'");
        		}
        		*/
    }
}
if (RUNNING_ASYNC) {
    # SQL Connection may have hit a timeout
    sql_connect();
    sql_query("UPDATE resource SET is_transcoding = 0 WHERE ref = '" . escape_check($ref) . "'");
    if ($previewonly) {
        unlink($file);
    }
}
コード例 #29
0
/**
 * Performs the login using the global $username, and $password. Since the "externalauth" hook
 * is allowed to change the credentials later on, the $password_hash needs to be global as well.
 *
 * @return array Containing the login details ('valid' determines whether or not the login succeeded).
 */
function perform_login()
{
    global $api, $scramble_key, $enable_remote_apis, $lang, $max_login_attempts_wait_minutes, $max_login_attempts_per_ip, $max_login_attempts_per_username, $global_cookies, $username, $password, $password_hash;
    if (!$api && strlen($password) == 32 && getval("userkey", "") != md5($username . $scramble_key)) {
        exit("Invalid password.");
        # Prevent MD5s being entered directly while still supporting direct entry of plain text passwords (for systems that were set up prior to MD5 password encryption was added). If a special key is sent, which is the md5 hash of the username and the secret scramble key, then allow a login using the MD5 password hash as the password. This is for the 'log in as this user' feature.
    }
    if (strlen($password) != 32) {
        # Provided password is not a hash, so generate a hash.
        $password_hash = md5("RS" . $username . $password);
    } else {
        $password_hash = $password;
    }
    $ip = get_ip();
    # This may change the $username, $password, and $password_hash
    hook("externalauth", "", array($username, $password));
    #Attempt external auth if configured
    $session_hash = md5($password_hash . $username . $password . date("Y-m-d"));
    if ($enable_remote_apis) {
        $session_hash = md5($password_hash . $username . date("Y-m-d"));
    }
    // no longer necessary to omit password in this hash for api support
    $valid = sql_query("select ref,usergroup from user where lower(username)='" . escape_check($username) . "' and (password='******' or password='******')");
    # Prepare result array
    $result = array();
    $result['valid'] = false;
    if (count($valid) >= 1) {
        # Account expiry
        $expires = sql_value("select account_expires value from user where username='******' and password='******'", "");
        if ($expires != "" && $expires != "0000-00-00 00:00:00" && strtotime($expires) <= time()) {
            $result['error'] = $lang["accountexpired"];
            return $result;
        }
        $result['valid'] = true;
        $result['session_hash'] = $session_hash;
        $result['password_hash'] = $password_hash;
        # Update the user record. Set the password hash again in case a plain text password was provided.
        sql_query("update user set password='******',session='" . escape_check($session_hash) . "',last_active=now(),login_tries=0,lang='" . getvalescaped("language", "") . "' where lower(username)='" . escape_check($username) . "' and (password='******' or password='******')");
        # Log this
        $userref = $valid[0]["ref"];
        $usergroup = $valid[0]["usergroup"];
        daily_stat("User session", $userref);
        sql_query("insert into resource_log(date,user,resource,type) values (now()," . ($userref != "" ? "'{$userref}'" : "null") . ",0,'l')");
        # Blank the IP address lockout counter for this IP
        sql_query("delete from ip_lockout where ip='" . escape_check($ip) . "'");
        return $result;
    }
    # Invalid login
    $result['error'] = $lang["loginincorrect"];
    hook("loginincorrect");
    # Add / increment a lockout value for this IP
    $lockouts = sql_value("select count(*) value from ip_lockout where ip='" . escape_check($ip) . "' and tries<'" . $max_login_attempts_per_ip . "'", "");
    if ($lockouts > 0) {
        # Existing row with room to move
        $tries = sql_value("select tries value from ip_lockout where ip='" . escape_check($ip) . "'", 0);
        $tries++;
        if ($tries == $max_login_attempts_per_ip) {
            # Show locked out message.
            $result['error'] = str_replace("?", $max_login_attempts_wait_minutes, $lang["max_login_attempts_exceeded"]);
        }
        # Increment
        sql_query("update ip_lockout set last_try=now(),tries=tries+1 where ip='" . escape_check($ip) . "'");
    } else {
        # New row
        sql_query("delete from ip_lockout where ip='" . escape_check($ip) . "'");
        sql_query("insert into ip_lockout (ip,tries,last_try) values ('" . escape_check($ip) . "',1,now())");
    }
    # Increment a lockout value for any matching username.
    $ulocks = sql_query("select ref,login_tries,login_last_try from user where username='******'");
    if (count($ulocks) > 0) {
        $tries = $ulocks[0]["login_tries"];
        if ($tries == "") {
            $tries = 1;
        } else {
            $tries++;
        }
        if ($tries > $max_login_attempts_per_username) {
            $tries = 1;
        }
        if ($tries == $max_login_attempts_per_username) {
            # Show locked out message.
            $result['error'] = str_replace("?", $max_login_attempts_wait_minutes, $lang["max_login_attempts_exceeded"]);
        }
        sql_query("update user set login_tries='{$tries}',login_last_try=now() where username='******'");
    }
    return $result;
}
コード例 #30
0
function managed_collection_request($ref,$details,$ref_is_resource=false)
	{
	# Request mode 1
	# Managed via the administrative interface
	
	# An e-mail is still sent.
	global $applicationname,$email_from,$baseurl,$email_notify,$username,$useremail,$userref,$lang,$request_senduserupdates;

	# Has a resource reference (instead of a collection reference) been passed?
	# Manage requests only work with collections. Create a collection containing only this resource.
	if ($ref_is_resource)
		{
		$c=create_collection($userref,$lang["request"] . " " . date("ymdHis"));
		add_resource_to_collection($ref,$c);
		$ref=$c; # Proceed as normal
		}

	# Fomulate e-mail text
	$message="";
	reset ($_POST);
	foreach ($_POST as $key=>$value)
		{
		if (strpos($key,"_label")!==false)
			{
			# Add custom field
			$setting=trim($_POST[str_replace("_label","",$key)]);
			if ($setting!="")
				{
				$message.=$value . ": " . $setting . "\n\n";
				}
			}
		}
	if (trim($details)!="") {$message.=$lang["requestreason"] . ": " . newlines($details) . "\n\n";} else {return false;}
	
	# Add custom fields
	$c="";
	global $custom_request_fields,$custom_request_required;
	if (isset($custom_request_fields))
		{
		$custom=explode(",",$custom_request_fields);
	
		# Required fields?
		if (isset($custom_request_required)) {$required=explode(",",$custom_request_required);}
	
		for ($n=0;$n<count($custom);$n++)
			{
			if (isset($required) && in_array($custom[$n],$required) && getval("custom" . $n,"")=="")
				{
				return false; # Required field was not set.
				}
			
			$message.=i18n_get_translated($custom[$n]) . ": " . getval("custom" . $n,"") . "\n\n";
			}
		}
	
	# Create the request
	sql_query("insert into request(user,collection,created,request_mode,status,comments) values ('$userref','$ref',now(),1,0,'" . escape_check($message) . "')");
	$request=sql_insert_id();
	
	# Send the e-mail		
	$userconfirmmessage = $lang["requestsenttext"];
	$message=$lang["username"] . ": " . $username . "\n" . $message;
	$message.=$lang["viewrequesturl"] . ":\n$baseurl/?q=$request";
	send_mail($email_notify,$applicationname . ": " . $lang["requestcollection"] . " - $ref",$message,$useremail);
	if ($request_senduserupdates){send_mail($useremail,$applicationname . ": " . $lang["requestsent"] . " - $ref",$userconfirmmessage,$email_from);}	
	
	# Increment the request counter
	sql_query("update resource set request_count=request_count+1 where ref='$ref'");
	
	return true;
	}