Example #1
0
/**
 * Set a user's display name
 * 
 * @return bool
 * @since 1.8.0
 * @access private
 */
function _elgg_set_user_name()
{
    $name = strip_tags(get_input('name'));
    $user_guid = get_input('guid');
    if ($user_guid) {
        $user = get_user($user_guid);
    } else {
        $user = elgg_get_logged_in_user_entity();
    }
    if (elgg_strlen($name) > 50) {
        register_error(elgg_echo('user:name:fail'));
        return false;
    }
    if ($user && $user->canEdit() && $name) {
        if ($name != $user->name) {
            $user->name = $name;
            if ($user->save()) {
                system_message(elgg_echo('user:name:success'));
                return true;
            } else {
                register_error(elgg_echo('user:name:fail'));
            }
        } else {
            // no change
            return null;
        }
    } else {
        register_error(elgg_echo('user:name:fail'));
    }
    return false;
}
Example #2
0
/**
 * Web service to update profile information
 *
 * @param string $username username to update profile information
 *
 * @return bool 
 */
function user_save_profile($username, $profile)
{
    $user = get_user_by_username($username);
    if (!$user) {
        throw new InvalidParameterException('registration:usernamenotvalid');
    }
    $owner = get_entity($user->guid);
    $profile_fields = elgg_get_config('profile_fields');
    foreach ($profile_fields as $shortname => $valuetype) {
        $value = $profile[$shortname];
        $value = html_entity_decode($value, ENT_COMPAT, 'UTF-8');
        if ($valuetype != 'longtext' && elgg_strlen($value) > 250) {
            $error = elgg_echo('profile:field_too_long', array(elgg_echo("profile:{$shortname}")));
            return $error;
        }
        if ($valuetype == 'tags') {
            $value = string_to_tag_array($value);
        }
        $input[$shortname] = $value;
    }
    $name = strip_tags($profile['name']);
    if ($name) {
        if (elgg_strlen($name) > 50) {
            return elgg_echo('user:name:fail');
        } elseif ($owner->name != $name) {
            $owner->name = $name;
            return $owner->save();
            if (!$owner->save()) {
                return elgg_echo('user:name:fail');
            }
        }
    }
    if (sizeof($input) > 0) {
        foreach ($input as $shortname => $value) {
            $options = array('guid' => $owner->guid, 'metadata_name' => $shortname);
            elgg_delete_metadata($options);
            if (isset($accesslevel[$shortname])) {
                $access_id = (int) $accesslevel[$shortname];
            } else {
                // this should never be executed since the access level should always be set
                $access_id = ACCESS_DEFAULT;
            }
            if (is_array($value)) {
                $i = 0;
                foreach ($value as $interval) {
                    $i++;
                    $multiple = $i > 1 ? TRUE : FALSE;
                    create_metadata($owner->guid, $shortname, $interval, 'text', $owner->guid, $access_id, $multiple);
                }
            } else {
                create_metadata($owner->guid, $shortname, $value, 'text', $owner->guid, $access_id);
            }
        }
    }
    return "Success";
}
Example #3
0
 /**
  * {@inheritdoc}
  */
 public function put(ParameterBag $params)
 {
     $owner = get_entity($params->guid);
     if (!$owner->canEdit()) {
         throw new GraphException("You are not allowed to modify this user's profile", HttpResponse::HTTP_FORBIDDEN);
     }
     $profile_fields = (array) elgg_get_config('profile_fields');
     $access_id = $params->access_id !== null ? $params->access_id : get_default_access($owner);
     $input = array();
     foreach ($profile_fields as $field => $valuetype) {
         // Making sure the consumer has sent these fields with the request
         if (isset($params->{$field}) && $this->request->get($field) !== null) {
             $value = $params->{$field};
             $value = _elgg_html_decode($value);
             if (!is_array($value) && $valuetype != 'longtext' && elgg_strlen($value) > 250) {
                 throw new GraphException(elgg_echo('profile:field_too_long', array(elgg_echo("profile:{$field}")), HttpResponse::HTTP_BAD_REQUEST));
             }
             if ($value && $valuetype == 'url' && !preg_match('~^https?\\://~i', $value)) {
                 $value = "http://{$value}";
             }
             if ($valuetype == 'tags') {
                 $value = string_to_tag_array($value);
             }
             if ($valuetype == 'email' && !empty($value) && !is_email_address($value)) {
                 throw new GraphException(elgg_echo('profile:invalid_email', array(elgg_echo("profile:{$field}"))), HttpResponse::HTTP_BAD_REQUEST);
             }
             $input[$field] = $value;
         }
     }
     // go through custom fields
     if (sizeof($input) > 0) {
         foreach ($input as $shortname => $value) {
             $options = array('guid' => $owner->guid, 'metadata_name' => $shortname, 'limit' => false);
             elgg_delete_metadata($options);
             if (!is_null($value) && $value !== '') {
                 // only create metadata for non empty values (0 is allowed) to prevent metadata records
                 // with empty string values #4858
                 if (is_array($value)) {
                     $i = 0;
                     foreach ($value as $interval) {
                         $i++;
                         $multiple = $i > 1 ? TRUE : FALSE;
                         create_metadata($owner->guid, $shortname, $interval, 'text', $owner->guid, $access_id, $multiple);
                     }
                 } else {
                     create_metadata($owner->getGUID(), $shortname, $value, 'text', $owner->getGUID(), $access_id);
                 }
             }
         }
         $owner->save();
         // Notify of profile update
         elgg_trigger_event('profileupdate', $owner->type, $owner);
     }
     return $this->get($params);
 }
Example #4
0
/**
 * Returns an excerpt.
 * Will return up to n chars stopping at the nearest space.
 * If no spaces are found (like in Japanese) will crop off at the
 * n char mark. Adds ... if any text was chopped.
 *
 * @param string $text      The full text to excerpt
 * @param int    $num_chars Return a string up to $num_chars long
 *
 * @return string
 * @since 1.7.2
 */
function elgg_get_excerpt($text, $num_chars = 250)
{
    $text = trim(elgg_strip_tags($text));
    $string_length = elgg_strlen($text);
    if ($string_length <= $num_chars) {
        return $text;
    }
    // handle cases
    $excerpt = elgg_substr($text, 0, $num_chars);
    $space = elgg_strrpos($excerpt, ' ', 0);
    // don't crop if can't find a space.
    if ($space === false) {
        $space = $num_chars;
    }
    $excerpt = trim(elgg_substr($excerpt, 0, $space));
    if ($string_length != elgg_strlen($excerpt)) {
        $excerpt .= '...';
    }
    return $excerpt;
}
Example #5
0
 /**
  * Add or update a config setting.
  * 
  * Plugin authors should use elgg_set_config().
  *
  * If the config name already exists, it will be updated to the new value.
  *
  * @warning Names should be selected so as not to collide with the names for the
  * datalist (application configuration)
  * 
  * @note Internal: These settings are stored in the dbprefix_config table and read
  * during system boot into $CONFIG.
  * 
  * @note Internal: The value is serialized so we maintain type information.
  *
  * @param string $name      The name of the configuration value
  * @param mixed  $value     Its value
  * @param int    $site_guid Optionally, the GUID of the site (current site is assumed by default)
  *
  * @return bool
  */
 function set($name, $value, $site_guid = 0)
 {
     $name = trim($name);
     // cannot store anything longer than 255 characters in db, so catch before we set
     if (elgg_strlen($name) > 255) {
         _elgg_services()->logger->error("The name length for configuration variables cannot be greater than 255");
         return false;
     }
     $site_guid = (int) $site_guid;
     if ($site_guid == 0) {
         $site_guid = (int) $this->CONFIG->site_guid;
     }
     if ($site_guid == $this->CONFIG->site_guid) {
         $this->CONFIG->{$name} = $value;
     }
     $escaped_name = sanitize_string($name);
     $escaped_value = sanitize_string(serialize($value));
     $result = _elgg_services()->db->insertData("INSERT INTO {$this->CONFIG->dbprefix}config\n\t\t\tSET name = '{$escaped_name}', value = '{$escaped_value}', site_guid = {$site_guid}\n\t\t\tON DUPLICATE KEY UPDATE value = '{$escaped_value}'");
     return $result !== false;
 }
Example #6
0
function file_tools_generate_thumbs($file)
{
    $formats = array("thumbnail" => 60, "smallthumb" => 153, "largethumb" => 600);
    $file->icontime = time();
    $filestorename = $file->getFilename();
    $filestorename = elgg_substr($filestorename, elgg_strlen("file/"));
    foreach ($formats as $name => $size) {
        $thumbnail = get_resized_image_from_existing_file($file->getFilenameOnFilestore(), $size, $size, true);
        if ($thumbnail) {
            $filename = "file/{$name}" . $filestorename;
            $thumb = new ElggFile();
            $thumb->setFilename($filename);
            $thumb->open("write");
            $thumb->write($thumbnail);
            $thumb->close();
            $file->{$name} = $filename;
            unset($thumbnail);
        }
    }
}
Example #7
0
 /**
  * Returns a where clause for a search query.
  *
  * @see search_get_where_sql
  * 
  * @param str   $table        Prefix for table to search on
  * @param array $fields       Fields to match against
  * @param array $params       Original search params
  * @param bool  $use_fulltext Use fulltext search
  * @return str
  */
 public static function getFieldSearchWhereClause($table, $fields, $params, $use_fulltext = TRUE)
 {
     if (is_callable('search_get_where_sql')) {
         return search_get_where_sql($table, $fields, $params, $use_fulltext);
     }
     $query = $params['query'];
     // add the table prefix to the fields
     foreach ($fields as $i => $field) {
         if ($table) {
             $fields[$i] = "{$table}.{$field}";
         }
     }
     $where = '';
     $search_info = elgg_get_config('search_info');
     // if query is shorter than the min for fts words
     // it's likely a single acronym or similar
     // switch to literal mode
     if (elgg_strlen($query) < $search_info['min_chars']) {
         $likes = array();
         $query = sanitise_string($query);
         foreach ($fields as $field) {
             $likes[] = "{$field} LIKE '%{$query}%'";
         }
         $likes_str = implode(' OR ', $likes);
         $where = "({$likes_str})";
     } else {
         // if we're not using full text, rewrite the query for bool mode.
         // exploiting a feature(ish) of bool mode where +-word is the same as -word
         if (!$use_fulltext) {
             $query = '+' . str_replace(' ', ' +', $query);
         }
         // if using advanced, boolean operators, or paired "s, switch into boolean mode
         $booleans_used = preg_match("/([\\-\\+~])([\\w]+)/i", $query);
         $advanced_search = isset($params['advanced_search']) && $params['advanced_search'];
         $quotes_used = elgg_substr_count($query, '"') >= 2;
         $options = '';
         if (!$use_fulltext || $booleans_used || $advanced_search || $quotes_used) {
             $options = 'IN BOOLEAN MODE';
         }
         $query = sanitise_string($query);
         $fields_str = implode(',', $fields);
         $where = "(MATCH ({$fields_str}) AGAINST ('{$query}' {$options}))";
     }
     return $where;
 }
Example #8
0
/**
 * Add or update a config setting.
 *
 * If the config name already exists, it will be updated to the new value.
 *
 * @internal
 * These settings are stored in the dbprefix_config table and read during system
 * boot into $CONFIG.
 *
 * @param string $name      The name of the configuration value
 * @param string $value     Its value
 * @param int    $site_guid Optionally, the GUID of the site (current site is assumed by default)
 *
 * @return bool
 * @todo The config table doens't have numeric primary keys so insert_data returns 0.
 * @todo Use "INSERT ... ON DUPLICATE KEY UPDATE" instead of trying to delete then add.
 * @see unset_config()
 * @see get_config()
 * @access private
 */
function set_config($name, $value, $site_guid = 0)
{
    global $CONFIG;
    $name = trim($name);
    // cannot store anything longer than 255 characters in db, so catch before we set
    if (elgg_strlen($name) > 255) {
        elgg_log("The name length for configuration variables cannot be greater than 255", "ERROR");
        return false;
    }
    // Unset existing
    unset_config($name, $site_guid);
    $site_guid = (int) $site_guid;
    if ($site_guid == 0) {
        $site_guid = (int) $CONFIG->site_id;
    }
    $CONFIG->{$name} = $value;
    $value = sanitise_string(serialize($value));
    $query = "insert into {$CONFIG->dbprefix}config" . " set name = '{$name}', value = '{$value}', site_guid = {$site_guid}";
    $result = insert_data($query);
    return $result !== false;
}
Example #9
0
$file->description = $desc;
$file->access_id = $access_id;
$file->container_guid = $container_guid;
$file->tags = string_to_tag_array($tags);
// we have a file upload, so process it
if (isset($_FILES['upload']['name']) && !empty($_FILES['upload']['name'])) {
    $prefix = "file/";
    // if previous file, delete it
    if ($new_file == false) {
        $filename = $file->getFilenameOnFilestore();
        if (file_exists($filename)) {
            unlink($filename);
        }
        // use same filename on the disk - ensures thumbnails are overwritten
        $filestorename = $file->getFilename();
        $filestorename = elgg_substr($filestorename, elgg_strlen($prefix));
    } else {
        $filestorename = elgg_strtolower(time() . $_FILES['upload']['name']);
    }
    $file->setFilename($prefix . $filestorename);
    /*$indexOfExt = strrpos($_FILES['upload']['name'], ".") + 1;
    	$ext = substr($_FILES['upload']['name'],$indexOfExt);
    	error_log($ext);*/
    $ext = pathinfo($_FILES['upload']['name'], PATHINFO_EXTENSION);
    if ($ext == "ppt") {
        $mime_type = 'application/vnd.ms-powerpoint';
    } else {
        $mime_type = ElggFile::detectMimeType($_FILES['upload']['tmp_name'], $_FILES['upload']['type'], $_FILES['upload']['name']);
    }
    // hack for Microsoft zipped formats
    $info = pathinfo($_FILES['upload']['name']);
Example #10
0
$video->tags = $tags;
// Save the entity to push attributes to database
// and to get access to guid if adding a new video
$video->save();
// we have a video upload, so process it
if (isset($_FILES['upload']['name']) && !empty($_FILES['upload']['name'])) {
    $prefix = "video/{$video->getGUID()}/";
    // if previous video, delete it
    if ($new_video == false) {
        $videoname = $video->getFilenameOnFilestore();
        if (file_exists($videoname)) {
            unlink($videoname);
        }
        // use same videoname on the disk - ensures thumbnails are overwritten
        $videostorename = $video->getFilename();
        $videostorename = elgg_substr($videostorename, elgg_strlen($prefix));
    } else {
        $videostorename = elgg_strtolower($_FILES['upload']['name']);
    }
    $video->setFilename($prefix . $videostorename);
    $mime_type = ElggFile::detectMimeType($_FILES['upload']['tmp_name'], $_FILES['upload']['type']);
    $video->setMimeType($mime_type);
    $video->originalvideoname = $_FILES['upload']['name'];
    $video->simpletype = 'video';
    // Open the video to guarantee the directory exists
    $video->open("write");
    $video->close();
    move_uploaded_file($_FILES['upload']['tmp_name'], $video->getFilenameOnFilestore());
    // Change the directory mode
    chmod($video->getFileDirectory(), 0775);
    $guid = $video->save();
Example #11
0
                if ($col == 3) {
                    echo "</tr>";
                    $col = 0;
                }
            }
            if ($col < 3) {
                echo "</tr>";
            }
            echo "</table>";
        }
        ?>

			</div>
		</div>
<?php 
        $substr = elgg_substr($chararray, elgg_strlen($chararray) - 1, 1);
        if ($letter == $substr) {
            break;
        }
        //$letter++;
        $letpos++;
        $letter = elgg_substr($chararray, $letpos, 1);
    }
    ?>
	</div>

<?php 
    if ($formtarget) {
        if (isset($vars['formcontents'])) {
            echo $vars['formcontents'];
        }
Example #12
0
<?php

/**
 * Output view for elgg_get_excerpt
 *
 * @uses $vars['text'] The text to get the excerpt for
 * @uses $vars['num_chars'] The max number of characters of the excerpt 
 * @uses $vars['suffix'] The suffix to be added if text is cut 
 */
$text = elgg_extract('text', $vars);
$text = trim(elgg_strip_tags($text));
$suffix = elgg_extract('suffix', $vars, '...');
$string_length = elgg_strlen($text);
$num_chars = (int) elgg_extract('num_chars', $vars, 250);
if ($string_length <= $num_chars) {
    echo $text;
    return;
}
// handle cases
$excerpt = elgg_substr($text, 0, $num_chars);
$space = elgg_strrpos($excerpt, ' ', 0);
// don't crop if can't find a space.
if ($space === false) {
    $space = $num_chars;
}
$excerpt = trim(elgg_substr($excerpt, 0, $space));
if ($string_length != elgg_strlen($excerpt)) {
    $excerpt .= $suffix;
}
echo $excerpt;
Example #13
0
File: Datalist.php Project: n8b/VMN
 /**
  * Set the value for a datalist element.
  * 
  * Plugin authors should use elgg_save_config() and pass null for the site GUID.
  * 
  * @warning Names should be selected so as not to collide with the names for the
  * site config.
  * 
  * @warning Values set here are not available in $CONFIG until next page load.
  *
  * @param string $name  The name of the datalist
  * @param string $value The new value
  *
  * @return bool
  * @access private
  */
 function set($name, $value)
 {
     $name = trim($name);
     // cannot store anything longer than 255 characters in db, so catch before we set
     if (elgg_strlen($name) > 255) {
         $this->logger->error("The name length for configuration variables cannot be greater than 255");
         return false;
     }
     $escaped_name = $this->db->sanitizeString($name);
     $escaped_value = $this->db->sanitizeString($value);
     $success = $this->db->insertData("INSERT INTO {$this->table}" . " SET name = '{$escaped_name}', value = '{$escaped_value}'" . " ON DUPLICATE KEY UPDATE value = '{$escaped_value}'");
     $this->cache->put($name, $value);
     return $success !== false;
 }
Example #14
0
/**
 * Process uploaded files
 *
 * @param mixed $files		Uploaded files
 * @param mixed $entity		If an entity is set and it doesn't belong to one of the file subtypes, uploaded files will be converted into hjFile objects and attached to the entity
 * @return void
 */
function hj_framework_process_file_upload($name, $entity = null)
{
    // Normalize the $_FILES array
    if (is_array($_FILES[$name]['name'])) {
        $files = hj_framework_prepare_files_global($_FILES);
        $files = $files[$name];
    } else {
        $files = $_FILES[$name];
        $files = array($files);
    }
    if (elgg_instanceof($entity)) {
        if (!$entity instanceof hjFile) {
            $is_attachment = true;
        }
        $subtype = $entity->getSubtype();
    }
    foreach ($files as $file) {
        if (!is_array($file) || $file['error']) {
            continue;
        }
        if ($is_attachment) {
            $filehandler = new hjFile();
        } else {
            $filehandler = new hjFile($entity->guid);
        }
        $prefix = 'hjfile/';
        if ($entity instanceof hjFile) {
            $filename = $filehandler->getFilenameOnFilestore();
            if (file_exists($filename)) {
                unlink($filename);
            }
            $filestorename = $filehandler->getFilename();
            $filestorename = elgg_substr($filestorename, elgg_strlen($prefix));
        } else {
            $filestorename = elgg_strtolower(time() . $file['name']);
        }
        $filehandler->setFilename($prefix . $filestorename);
        $filehandler->title = $file['name'];
        $mime_type = ElggFile::detectMimeType($file['tmp_name'], $file['type']);
        // hack for Microsoft zipped formats
        $info = pathinfo($file['name']);
        $office_formats = array('docx', 'xlsx', 'pptx');
        if ($mime_type == "application/zip" && in_array($info['extension'], $office_formats)) {
            switch ($info['extension']) {
                case 'docx':
                    $mime_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                    break;
                case 'xlsx':
                    $mime_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    break;
                case 'pptx':
                    $mime_type = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
                    break;
            }
        }
        // check for bad ppt detection
        if ($mime_type == "application/vnd.ms-office" && $info['extension'] == "ppt") {
            $mime_type = "application/vnd.ms-powerpoint";
        }
        $filehandler->setMimeType($mime_type);
        $filehandler->originalfilename = $file['name'];
        $filehandler->simpletype = hj_framework_get_simple_type($mime_type);
        $filehandler->filesize = $file['size'];
        $filehandler->open("write");
        $filehandler->close();
        move_uploaded_file($file['tmp_name'], $filehandler->getFilenameOnFilestore());
        if ($filehandler->save()) {
            if ($is_attachment && elgg_instanceof($entity)) {
                make_attachment($entity->guid, $filehandler->getGUID());
            }
            // Generate icons for images
            if ($filehandler->simpletype == "image") {
                if (!elgg_instanceof($entity) || $is_attachment) {
                    // no entity provided or this is an attachment generating icons for self
                    hj_framework_generate_entity_icons($filehandler, $filehandler);
                } else {
                    if (elgg_instanceof($entity)) {
                        hj_framework_generate_entity_icons($entity, $filehandler);
                    }
                }
                // the settings tell us not to keep the original image file, so downsizing to master
                if (!HYPEFRAMEWORK_FILES_KEEP_ORIGINALS) {
                    $icon_sizes = hj_framework_get_thumb_sizes($subtype);
                    $values = $icon_sizes['master'];
                    $master = get_resized_image_from_existing_file($filehandler->getFilenameOnFilestore(), $values['w'], $values['h'], $values['square'], 0, 0, 0, 0, $values['upscale']);
                    $filehandler->open('write');
                    $filehandler->write($master);
                    $filehandler->close();
                }
            }
            $return[$file['name']] = $filehandler->getGUID();
        } else {
            $return[$file['name']] = false;
        }
    }
    return $return;
}
Example #15
0
File: start.php Project: elgg/elgg
/**
 * Return a string with highlighted matched queries and relevant context
 * Determines context based upon occurance and distance of words with each other.
 *
 * @param string $haystack
 * @param string $query
 * @param int $min_match_context = 30
 * @param int $max_length = 300
 * @param bool $tag_match Search is for tags. Don't ignore words.
 * @return string
 */
function search_get_highlighted_relevant_substrings($haystack, $query, $min_match_context = 30, $max_length = 300, $tag_match = false)
{
    $haystack = strip_tags($haystack);
    $haystack_length = elgg_strlen($haystack);
    $haystack_lc = elgg_strtolower($haystack);
    if (!$tag_match) {
        $words = search_remove_ignored_words($query, 'array');
    } else {
        $words = array();
    }
    // if haystack < $max_length return the entire haystack w/formatting immediately
    if ($haystack_length <= $max_length) {
        $return = search_highlight_words($words, $haystack);
        return $return;
    }
    // get the starting positions and lengths for all matching words
    $starts = array();
    $lengths = array();
    foreach ($words as $word) {
        $word = elgg_strtolower($word);
        $count = elgg_substr_count($haystack_lc, $word);
        $word_len = elgg_strlen($word);
        $haystack_len = elgg_strlen($haystack_lc);
        // find the start positions for the words
        if ($count > 1) {
            $offset = 0;
            while (FALSE !== ($pos = elgg_strpos($haystack_lc, $word, $offset))) {
                $start = $pos - $min_match_context > 0 ? $pos - $min_match_context : 0;
                $starts[] = $start;
                $stop = $pos + $word_len + $min_match_context;
                $lengths[] = $stop - $start;
                $offset += $pos + $word_len;
                if ($offset >= $haystack_len) {
                    break;
                }
            }
        } else {
            $pos = elgg_strpos($haystack_lc, $word);
            $start = $pos - $min_match_context > 0 ? $pos - $min_match_context : 0;
            $starts[] = $start;
            $stop = $pos + $word_len + $min_match_context;
            $lengths[] = $stop - $start;
        }
    }
    $offsets = search_consolidate_substrings($starts, $lengths);
    // figure out if we can adjust the offsets and lengths
    // in order to return more context
    $total_length = array_sum($offsets);
    $add_length = 0;
    if ($total_length < $max_length && $offsets) {
        $add_length = floor(($max_length - $total_length) / count($offsets) / 2);
        $starts = array();
        $lengths = array();
        foreach ($offsets as $offset => $length) {
            $start = $offset - $add_length > 0 ? $offset - $add_length : 0;
            $length = $length + $add_length;
            $starts[] = $start;
            $lengths[] = $length;
        }
        $offsets = search_consolidate_substrings($starts, $lengths);
    }
    // sort by order of string size descending (which is roughly
    // the proximity of matched terms) so we can keep the
    // substrings with terms closest together and discard
    // the others as needed to fit within $max_length.
    arsort($offsets);
    $return_strs = array();
    $total_length = 0;
    foreach ($offsets as $start => $length) {
        $string = trim(elgg_substr($haystack, $start, $length));
        // continue past if adding this substring exceeds max length
        if ($total_length + $length > $max_length) {
            continue;
        }
        $total_length += $length;
        $return_strs[$start] = $string;
    }
    // put the strings in order of occurence
    ksort($return_strs);
    // add ...s where needed
    $return = implode('...', $return_strs);
    if (!array_key_exists(0, $return_strs)) {
        $return = "...{$return}";
    }
    // add to end of string if last substring doesn't hit the end.
    $starts = array_keys($return_strs);
    $last_pos = $starts[count($starts) - 1];
    if ($last_pos + elgg_strlen($return_strs[$last_pos]) < $haystack_length) {
        $return .= '...';
    }
    $return = search_highlight_words($words, $return);
    return $return;
}
Example #16
0
/**
 * Process uploaded files
 *
 * @param string $name           Name of the HTML file input
 * @param string $subtype        Object subtype to be assigned to newly created objects
 * @param type   $guid           GUID of an existing object
 * @param type   $container_guid GUID of the container entity
 * @return array An associative array of original file names and guids (or false) of created object
 */
function process_file_upload($name, $subtype = hjAlbumImage::SUBTYPE, $guid = null, $container_guid = null)
{
    // Normalize the $_FILES array
    if (is_array($_FILES[$name]['name'])) {
        $files = prepare_files_global($_FILES);
        $files = $files[$name];
    } else {
        $files = $_FILES[$name];
        $files = array($files);
    }
    foreach ($files as $file) {
        if (!is_array($file) || $file['error']) {
            continue;
        }
        $filehandler = new ElggFile($guid);
        $prefix = 'hjfile/';
        if ($guid) {
            $filename = $filehandler->getFilenameOnFilestore();
            if (file_exists($filename)) {
                unlink($filename);
            }
            $filestorename = $filehandler->getFilename();
            $filestorename = elgg_substr($filestorename, elgg_strlen($prefix));
        } else {
            $filehandler->subtype = $subtype;
            $filehandler->container_guid = $container_guid;
            $filestorename = elgg_strtolower(time() . $file['name']);
        }
        $filehandler->setFilename($prefix . $filestorename);
        $filehandler->title = $file['name'];
        $mime_type = ElggFile::detectMimeType($file['tmp_name'], $file['type']);
        // hack for Microsoft zipped formats
        $info = pathinfo($file['name']);
        $office_formats = array('docx', 'xlsx', 'pptx');
        if ($mime_type == "application/zip" && in_array($info['extension'], $office_formats)) {
            switch ($info['extension']) {
                case 'docx':
                    $mime_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                    break;
                case 'xlsx':
                    $mime_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    break;
                case 'pptx':
                    $mime_type = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
                    break;
            }
        }
        // check for bad ppt detection
        if ($mime_type == "application/vnd.ms-office" && $info['extension'] == "ppt") {
            $mime_type = "application/vnd.ms-powerpoint";
        }
        $filehandler->setMimeType($mime_type);
        $filehandler->originalfilename = $file['name'];
        $filehandler->simpletype = get_simple_type($mime_type);
        $filehandler->filesize = $file['size'];
        $filehandler->open("write");
        $filehandler->close();
        move_uploaded_file($file['tmp_name'], $filehandler->getFilenameOnFilestore());
        if ($filehandler->save()) {
            // Generate icons for images
            if ($filehandler->simpletype == "image") {
                generate_entity_icons($filehandler);
                // the settings tell us not to keep the original image file, so downsizing to master
                if (elgg_get_plugin_setting('remove_original_files', 'hypeGallery')) {
                    $icon_sizes = elgg_get_config('icon_sizes');
                    $values = $icon_sizes['master'];
                    $master = get_resized_image_from_existing_file($filehandler->getFilenameOnFilestore(), $values['w'], $values['h'], $values['square'], 0, 0, 0, 0, $values['upscale']);
                    $filehandler->open('write');
                    $filehandler->write($master);
                    $filehandler->close();
                }
            }
            $return[$file['name']] = $filehandler->getGUID();
        } else {
            $return[$file['name']] = false;
        }
    }
    return $return;
}
Example #17
0
<?php 
                    }
                }
            }
            ?>
</table>

<?php 
        }
        ?>
			
				</div>
			</div>
<?php 
        $letpos++;
        if ($letpos == elgg_strlen($chararray)) {
            break;
        }
        $letter = elgg_substr($chararray, $letpos, 1);
    }
    ?>
		</div>		
	</div>
	</div>
	
<?php 
} else {
    echo $vars['replacement'];
}
if (!$callback) {
    ?>
Example #18
0
 /**
  * Returns a where clause for a search query.
  *
  * @param string $table  Prefix for table to search on
  * @param array  $fields Fields to match against
  * @return string
  */
 function sqlGetWhereFulltextClause($table, $fields, $query, $use_fulltext = TRUE)
 {
     $query = str_replace(array('_', '%'), array('\\_', '\\%'), sanitize_string($query));
     // add the table prefix to the fields
     foreach ($fields as $i => $field) {
         if ($table) {
             $fields[$i] = "{$table}.{$field}";
         }
     }
     $where = '';
     // if query is shorter than the min for fts words
     // it's likely a single acronym or similar
     // switch to literal mode
     if (elgg_strlen($this->query) < $this->ft_min_chars) {
         $likes = array();
         foreach ($fields as $field) {
             $likes[] = "{$field} LIKE '%{$query}%'";
         }
         $likes_str = implode(' OR ', $likes);
         $where = "({$likes_str})";
     } else {
         // if we're not using full text, rewrite the query for bool mode.
         // exploiting a feature(ish) of bool mode where +-word is the same as -word
         if (!$use_fulltext) {
             $query = '+' . str_replace(' ', ' +', $query);
         }
         // if using advanced, boolean operators, or paired "s, switch into boolean mode
         $booleans_used = preg_match("/([\\-\\+~])([\\w]+)/i", $query);
         $quotes_used = elgg_substr_count($query, '"') >= 2;
         if (!$use_fulltext || $booleans_used || $quotes_used) {
             $options = 'IN BOOLEAN MODE';
         } else {
             $options = '';
         }
         $query = sanitise_string($query);
         $fields_str = implode(',', $fields);
         $where = "(MATCH ({$fields_str}) AGAINST ('{$query}' {$options}))";
     }
     return $where;
 }
/**
 * Returns a where clause for a search query.
 *
 * @param str $table Prefix for table to search on
 * @param array $fields Fields to match against
 * @param array $params Original search params
 * @return str
 */
function search_get_where_sql($table, $fields, $params, $use_fulltext = TRUE)
{
    global $CONFIG;
    $query = $params['query'];
    // add the table prefix to the fields
    foreach ($fields as $i => $field) {
        if ($table) {
            $fields[$i] = "{$table}.{$field}";
        }
    }
    // if we're not using full text, rewrite the query for bool mode.
    // exploiting a feature(ish) of bool mode where +-word is the same as -word
    if (!$use_fulltext) {
        $query = '+' . str_replace(' ', ' +', $query);
    }
    // if query is shorter than the min for fts words
    // it's likely a single acronym or similar
    // switch to literal mode
    if (elgg_strlen($query) < $CONFIG->search_info['min_chars']) {
        $likes = array();
        $query = sanitise_string($query);
        foreach ($fields as $field) {
            $likes[] = "{$field} LIKE '%{$query}%'";
        }
        $likes_str = implode(' OR ', $likes);
        $where = "({$likes_str})";
    } else {
        // if using advanced or paired "s, switch into boolean mode
        if (!$use_fulltext || isset($params['advanced_search']) && $params['advanced_search'] || elgg_substr_count($query, '"') >= 2) {
            $options = 'IN BOOLEAN MODE';
        } else {
            // natural language mode is default and this keyword isn't supported in < 5.1
            //$options = 'IN NATURAL LANGUAGE MODE';
            $options = '';
        }
        // if short query, use query expansion.
        // @todo doesn't seem to be working well.
        if (elgg_strlen($query) < 5) {
            //$options .= ' WITH QUERY EXPANSION';
        }
        $query = sanitise_string($query);
        $fields_str = implode(',', $fields);
        $where = "(MATCH ({$fields_str}) AGAINST ('{$query}' {$options}))";
    }
    return $where;
}
Example #20
0
 /**
  * Add or update a config setting.
  *
  * Plugin authors should use elgg_set_config().
  *
  * If the config name already exists, it will be updated to the new value.
  *
  * @note Internal: These settings are stored in the dbprefix_config table and read
  * during system boot into $CONFIG.
  *
  * @note Internal: The value is serialized so we maintain type information.
  *
  * @param string $name  The name of the configuration value
  * @param mixed  $value Its value
  *
  * @return bool
  */
 function set($name, $value)
 {
     $name = trim($name);
     // cannot store anything longer than 255 characters in db, so catch before we set
     if (elgg_strlen($name) > 255) {
         $this->logger->error("The name length for configuration variables cannot be greater than 255");
         return false;
     }
     $this->CONFIG->{$name} = $value;
     $dbprefix = $this->CONFIG->dbprefix;
     $sql = "\n\t\t\tINSERT INTO {$dbprefix}config\n\t\t\tSET name = :name,\n\t\t\t\tvalue = :value\n\t\t\tON DUPLICATE KEY UPDATE value = :value\n\t\t";
     $params = [':name' => $name, ':value' => serialize($value)];
     $version = (int) $this->CONFIG->version;
     if (!empty($version) && $version < 2016102500) {
         // need to do this the old way as long as site_guid columns have not been dropped
         $sql = "\n\t\t\t\tINSERT INTO {$dbprefix}config\n\t\t\t\tSET name = :name,\n\t\t\t\t\tvalue = :value,\n\t\t\t\t\tsite_guid = :site_guid\n\t\t\t\tON DUPLICATE KEY UPDATE value = :value\n\t\t\t";
         $params[':site_guid'] = 1;
     }
     $result = $this->db->insertData($sql, $params);
     $this->boot->invalidateCache();
     return $result !== false;
 }
Example #21
0
        $error = elgg_echo('profile:field_too_long', array(elgg_echo("profile:{$shortname}")));
        register_error($error);
        forward(REFERER);
    }
    if ($value && $valuetype == 'url' && !preg_match('~^https?\\://~i', $value)) {
        $value = "http://{$value}";
    }
    if ($valuetype == 'tags') {
        $value = string_to_tag_array($value);
    }
    $input[$shortname] = $value;
}
// display name is handled separately
$name = strip_tags(get_input('name'));
if ($name) {
    if (elgg_strlen($name) > 50) {
        register_error(elgg_echo('user:name:fail'));
    } elseif ($owner->name != $name) {
        $owner->name = $name;
        $owner->save();
    }
}
// go through custom fields
if (sizeof($input) > 0) {
    foreach ($input as $shortname => $value) {
        $options = array('guid' => $owner->guid, 'metadata_name' => $shortname, 'limit' => false);
        elgg_delete_metadata($options);
        if (!is_null($value) && $value !== '') {
            // only create metadata for non empty values (0 is allowed) to prevent metadata records
            // with empty string values #4858
            if (isset($accesslevel[$shortname])) {
Example #22
0
/**
 * Set a user's display name
 * 
 * @return bool
 * @since 1.8.0
 * @access private
 */
function elgg_set_user_name()
{
    $name = strip_tags(get_input('name'));
    $user_id = get_input('guid');
    if (!$user_id) {
        $user = elgg_get_logged_in_user_entity();
    } else {
        $user = get_entity($user_id);
    }
    if (elgg_strlen($name) > 50) {
        register_error(elgg_echo('user:name:fail'));
        return false;
    }
    if ($user && $user->canEdit() && $name) {
        if ($name != $user->name) {
            $user->name = $name;
            if ($user->save()) {
                if (smf_updateMemberData($user->username, array('real_name' => $name))) {
                    system_message(elgg_echo('user:name:success'));
                } else {
                    register_error(elgg_echo('bbsname:save:fail') . elgg_echo('zhaohu:sorry'));
                    elgg_log("ZHError failed to set BBS real name for user {$user->guid}", "ERROR");
                }
                return true;
            } else {
                register_error(elgg_echo('user:name:fail') . elgg_echo('zhaohu:sorry'));
                elgg_log("ZHError failed to set name for user {$user->guid}", "ERROR");
            }
        } else {
            // no change
            return null;
        }
    } else {
        register_error(elgg_echo('user:name:fail'));
    }
    return false;
}
function create_file($container_guid, $title, $desc, $access_id, $guid, $tags, $new_file)
{
    // register_error("Creating file: " . $container_guid . ", vars: " . print_r(array($title, $desc, $access_id, $guid, $tags, $new_file), true));
    if ($new_file) {
        // must have a file if a new file upload
        if (empty($_FILES['upload']['name'])) {
            // cache information in session
            $_SESSION['uploadtitle'] = $title;
            $_SESSION['uploaddesc'] = $desc;
            $_SESSION['uploadtags'] = $tags;
            $_SESSION['uploadaccessid'] = $access_id;
            register_error(elgg_echo('file:nofile') . "no file new");
            forward($_SERVER['HTTP_REFERER']);
        }
        $file = new FilePluginFile();
        $file->subtype = "file";
        // if no title on new upload, grab filename
        if (empty($title)) {
            $title = $_FILES['upload']['name'];
        }
    } else {
        // load original file object
        $file = get_entity($guid);
        if (!$file) {
            register_error(elgg_echo('file:cannotload') . 'can"t load existing');
            forward($_SERVER['HTTP_REFERER']);
        }
        // user must be able to edit file
        if (!$file->canEdit()) {
            register_error(elgg_echo('file:noaccess') . 'no access to existing');
            forward($_SERVER['HTTP_REFERER']);
        }
    }
    $file->title = $title;
    $file->description = $desc;
    $file->access_id = $access_id;
    $file->container_guid = $container_guid;
    $tags = explode(",", $tags);
    $file->tags = $tags;
    // we have a file upload, so process it
    if (isset($_FILES['upload']['name']) && !empty($_FILES['upload']['name'])) {
        $prefix = "file/";
        // if previous file, delete it
        if ($new_file == false) {
            $filename = $file->getFilenameOnFilestore();
            if (file_exists($filename)) {
                unlink($filename);
            }
            // use same filename on the disk - ensures thumbnails are overwritten
            $filestorename = $file->getFilename();
            $filestorename = elgg_substr($filestorename, elgg_strlen($prefix));
        } else {
            $filestorename = elgg_strtolower(time() . $_FILES['upload']['name']);
        }
        $file->setFilename($prefix . $filestorename);
        $file->setMimeType($_FILES['upload']['type']);
        $file->originalfilename = $_FILES['upload']['name'];
        $file->simpletype = get_general_file_type($_FILES['upload']['type']);
        $file->open("write");
        $file->write(get_uploaded_file('upload'));
        $file->close();
        $guid = $file->save();
        // if image, we need to create thumbnails (this should be moved into a function)
        if ($guid && $file->simpletype == "image") {
            $thumbnail = get_resized_image_from_existing_file($file->getFilenameOnFilestore(), 60, 60, true);
            if ($thumbnail) {
                $thumb = new ElggFile();
                $thumb->setMimeType($_FILES['upload']['type']);
                $thumb->setFilename($prefix . "thumb" . $filestorename);
                $thumb->open("write");
                $thumb->write($thumbnail);
                $thumb->close();
                $file->thumbnail = $prefix . "thumb" . $filestorename;
                unset($thumbnail);
            }
            $thumbsmall = get_resized_image_from_existing_file($file->getFilenameOnFilestore(), 153, 153, true);
            if ($thumbsmall) {
                $thumb->setFilename($prefix . "smallthumb" . $filestorename);
                $thumb->open("write");
                $thumb->write($thumbsmall);
                $thumb->close();
                $file->smallthumb = $prefix . "smallthumb" . $filestorename;
                unset($thumbsmall);
            }
            $thumblarge = get_resized_image_from_existing_file($file->getFilenameOnFilestore(), 600, 600, false);
            if ($thumblarge) {
                $thumb->setFilename($prefix . "largethumb" . $filestorename);
                $thumb->open("write");
                $thumb->write($thumblarge);
                $thumb->close();
                $file->largethumb = $prefix . "largethumb" . $filestorename;
                unset($thumblarge);
            }
        }
    } else {
        // not saving a file but still need to save the entity to push attributes to database
        $file->save();
    }
    return array($file, $guid);
}
Example #24
0
function pleio_api_change_setting($name = "", $password = "", $language = "", $email = "")
{
    $fail = false;
    $dirty = false;
    $user = elgg_get_logged_in_user_entity();
    if ($language && $language != $user->language && array_key_exists($language, get_installed_translations())) {
        $user->language = $language;
        $dirty = true;
    }
    if ($email && $email != $user->email) {
        if (!is_email_address($email)) {
            $fail = elgg_echo('email:save:fail');
        } else {
            if (!get_user_by_email($email)) {
                $user->email = $email;
                $dirty = true;
            } else {
                $fail = elgg_echo('registration:dupeemail');
            }
        }
    }
    if ($name && $name != $user->name) {
        $name = strip_tags($name);
        if (elgg_strlen($name) > 50) {
            $fail = elgg_echo('user:name:fail');
        } else {
            $user->name = $name;
            $dirty = true;
        }
    }
    if ($password) {
        try {
            $result = validate_password($password);
            if ($result) {
                $user->salt = generate_random_cleartext_password();
                $user->password = generate_user_password($user, $password);
                $dirty = true;
            } else {
                $fail = elgg_echo('user:password:fail');
            }
        } catch (RegistrationException $e) {
            $fail = $e->getMessage();
        }
    }
    if ($fail) {
        return new ErrorResult($fail);
    } else {
        if ($dirty) {
            if ($user->canEdit() && $user->save()) {
                return new SuccessResult("Instellingen opgeslagen");
            } else {
                return new ErrorResult("Opslaan mislukt");
            }
        } else {
            return new SuccessResult("Instellingen niet gewijzigd");
        }
    }
    return new ErrorResult("Niets gewijzigd");
}
Example #25
0
/**
 * Get entities with tags that match the search parameters.
 *
 * @param string $hook   Hook name
 * @param string $type   Hook type
 * @param array  $value  Empty array
 * @param array  $params Search parameters
 * @return array
 */
function search_tags_hook($hook, $type, $value, $params)
{
    $params['joins'] = (array) elgg_extract('joins', $params, array());
    $params['wheres'] = (array) elgg_extract('wheres', $params, array());
    $db_prefix = elgg_get_config('dbprefix');
    $valid_tag_names = elgg_get_registered_tag_metadata_names();
    // @todo will need to split this up to support searching multiple tags at once.
    $query = sanitise_string($params['query']);
    // if passed a tag metadata name, only search on that tag name.
    // tag_name isn't included in the params because it's specific to
    // tag searches.
    if ($tag_names = get_input('tag_names')) {
        if (is_array($tag_names)) {
            $search_tag_names = $tag_names;
        } else {
            $search_tag_names = array($tag_names);
        }
        // check these are valid to avoid arbitrary metadata searches.
        foreach ($search_tag_names as $i => $tag_name) {
            if (!in_array($tag_name, $valid_tag_names)) {
                unset($search_tag_names[$i]);
            }
        }
    } else {
        $search_tag_names = $valid_tag_names;
    }
    if (!$search_tag_names) {
        return array('entities' => array(), 'count' => $count);
    }
    // don't use elgg_get_entities_from_metadata() here because of
    // performance issues.  since we don't care what matches at this point
    // use an IN clause to grab everything that matches at once and sort
    // out the matches later.
    $params['joins'][] = "JOIN {$db_prefix}metadata md on e.guid = md.entity_guid";
    $params['joins'][] = "JOIN {$db_prefix}metastrings msn on md.name_id = msn.id";
    $params['joins'][] = "JOIN {$db_prefix}metastrings msv on md.value_id = msv.id";
    $access = _elgg_get_access_where_sql(array('table_alias' => 'md'));
    $sanitised_tags = array();
    foreach ($search_tag_names as $tag) {
        $sanitised_tags[] = '"' . sanitise_string($tag) . '"';
    }
    $tags_in = implode(',', $sanitised_tags);
    $params['wheres'][] = "(msn.string IN ({$tags_in}) AND msv.string = '{$query}' AND {$access})";
    $params['count'] = TRUE;
    $count = elgg_get_entities($params);
    // no need to continue if nothing here.
    if (!$count) {
        return array('entities' => array(), 'count' => $count);
    }
    $params['count'] = FALSE;
    if (isset($params['sort']) || !isset($params['order_by'])) {
        $params['order_by'] = search_get_order_by_sql('e', null, $params['sort'], $params['order']);
    }
    $entities = elgg_get_entities($params);
    // add the volatile data for why these entities have been returned.
    foreach ($entities as $entity) {
        $matched_tags_strs = array();
        // get tags for each tag name requested to find which ones matched.
        foreach ($search_tag_names as $tag_name) {
            $tags = $entity->getTags($tag_name);
            // @todo make one long tag string and run this through the highlight
            // function.  This might be confusing as it could chop off
            // the tag labels.
            if (in_array(strtolower($query), array_map('strtolower', $tags))) {
                if (is_array($tags)) {
                    $tag_name_str = elgg_echo("tag_names:{$tag_name}");
                    $matched_tags_strs[] = "{$tag_name_str}: " . implode(', ', $tags);
                }
            }
        }
        // different entities have different titles
        switch ($entity->type) {
            case 'site':
            case 'user':
            case 'group':
                $title_tmp = $entity->name;
                break;
            case 'object':
                $title_tmp = $entity->title;
                break;
        }
        // Nick told me my idea was dirty, so I'm hard coding the numbers.
        $title_tmp = strip_tags($title_tmp);
        if (elgg_strlen($title_tmp) > 297) {
            $title_str = elgg_substr($title_tmp, 0, 297) . '...';
        } else {
            $title_str = $title_tmp;
        }
        $desc_tmp = strip_tags($entity->description);
        if (elgg_strlen($desc_tmp) > 297) {
            $desc_str = elgg_substr($desc_tmp, 0, 297) . '...';
        } else {
            $desc_str = $desc_tmp;
        }
        $tags_str = implode('. ', $matched_tags_strs);
        $tags_str = search_get_highlighted_relevant_substrings($tags_str, $params['query'], 30, 300, true);
        $entity->setVolatileData('search_matched_title', $title_str);
        $entity->setVolatileData('search_matched_description', $desc_str);
        $entity->setVolatileData('search_matched_extra', $tags_str);
    }
    return array('entities' => $entities, 'count' => $count);
}
// Load configuration
global $CONFIG;
gatekeeper();
// Get profile fields
$input = array();
$accesslevel = get_input('accesslevel');
if (!is_array($accesslevel)) {
    $accesslevel = array();
}
foreach ($CONFIG->profile as $shortname => $valuetype) {
    // the decoding is a stop gag to prevent &amp;&amp; showing up in profile fields
    // because it is escaped on both input (get_input()) and output (view:output/text). see #561 and #1405.
    // must decode in utf8 or string corruption occurs. see #1567.
    $value = html_entity_decode(get_input($shortname), ENT_COMPAT, 'UTF-8');
    // limit to reasonable sizes.
    if ($valuetype != 'longtext' && elgg_strlen($value) > 250) {
        $error = sprintf(elgg_echo('profile:field_too_long'), elgg_echo("profile:{$shortname}"));
        register_error($error);
        forward($_SERVER['HTTP_REFERER']);
    }
    if ($valuetype == 'tags') {
        $value = string_to_tag_array($value);
    }
    $input[$shortname] = $value;
}
// Get the page owner to see if the currently logged in user canEdit() the page owner.
$user = page_owner_entity();
if (!$user) {
    $user = $_SESSION['user'];
    // @todo this doesn't make sense...???
    set_page_owner($user->getGUID());