Ejemplo n.º 1
0
/**
 * Replace profile field placeholders with input fields
 *
 * @param string $text the text to replace in
 *
 * @return false|string
 */
function wizard_replace_profile_fields($text)
{
    if (empty($text) || !is_string($text)) {
        return false;
    }
    $regex = '/{{profile_([a-z0-9_-]+)}}/i';
    $matches = array();
    preg_match_all($regex, $text, $matches);
    if (empty($matches)) {
        return $text;
    }
    $placeholders = $matches[0];
    $profile_names = $matches[1];
    foreach ($placeholders as $index => $placeholder) {
        if (strpos($text, $placeholder) === false) {
            // already replaced
            continue;
        }
        $input = elgg_view('input/profile_field', array('name' => $profile_names[$index]));
        if (empty($input)) {
            elgg_log("Wizard unable to replace profile placeholder: {$placeholder}", 'WARNING');
        } else {
            elgg_log("Wizard replace profile placeholder: {$placeholder}");
        }
        $text = str_replace($placeholder, $input, $text);
    }
    return $text;
}
Ejemplo n.º 2
0
/**
 * Get a working ElasticSearch client for further use
 *
 * @return false|ColdTrick\ElasticSearch\Client
 */
function elasticsearch_get_client()
{
    static $client;
    if (!isset($client)) {
        $client = false;
        // Check if the function 'curl_multi_exec' isn't blocked (for security reasons), this prevents error_log overflow
        // this isn't caught by the \Elasticseach\Client
        if (!function_exists('curl_multi_exec')) {
            return false;
        }
        $host = elasticsearch_get_setting('host');
        if (!empty($host)) {
            $params = array();
            $hosts = explode(',', $host);
            array_walk($hosts, 'elasticsearch_cleanup_host');
            $params['hosts'] = $hosts;
            $params['logging'] = true;
            $params['logObject'] = new ColdTrick\ElasticSearch\DatarootLogger('log');
            // trigger hook so other plugins can infuence the params
            $params = elgg_trigger_plugin_hook('params', 'elasticsearch', $params, $params);
            try {
                $client = new ColdTrick\ElasticSearch\Client($params);
            } catch (Exception $e) {
                elgg_log("Unable to create ElasticSearch client: {$e->getMessage()}", 'ERROR');
            }
        }
    }
    return $client;
}
Ejemplo n.º 3
0
 /**
  * Prevent outgoing e-mail to non test panel members
  *
  * @param string $hook        the name of the hook
  * @param string $type        the type of the hook
  * @param array  $returnvalue the current return value
  * @param array  $params      supplied params
  *
  * @return void|false
  */
 public static function email($hook, $type, $returnvalue, $params)
 {
     if (empty($returnvalue) || !is_array($returnvalue)) {
         // someone else already send the emails
         return;
     }
     if (!test_panel_limit_notifications()) {
         // don't limit e-mails
         return;
     }
     $to = elgg_extract('to', $returnvalue);
     if (empty($to) || !is_string($to)) {
         // don't know how to handle this
         return;
     }
     $to = EmailHandler::sanitizeEmail($to);
     elgg_log("Test panel processing: {$to}", 'INFO');
     $allowed_emails = test_panel_get_panel_members_email_addresses();
     if (empty($allowed_emails) || !is_array($allowed_emails)) {
         // nobody is allowed (shouldn't happen)
         return false;
     }
     if (!in_array($to, $allowed_emails)) {
         // user is not allowed to get e-mails
         elgg_log("Test panel blocked: {$to}", 'NOTICE');
         return false;
     }
     // user is a panel member, so can receive e-mails
 }
Ejemplo n.º 4
0
 /**
  * Resolve an IP address to location
  *
  * @param string $ip IP Address
  * @param mixed $format Format for an output string, or false to output result object
  * @return mixed
  */
 public static function resolveIP($ip = '', $format = "%S %n, %z %L, %C")
 {
     if (!$ip) {
         return false;
     }
     if (!isset(self::$geocoder)) {
         new ElggGeocoder();
     }
     $geocoder = self::$geocoder;
     if (!$geocoder) {
         return false;
     }
     try {
         $data = $geocoder->geocode($ip);
     } catch (Exception $e) {
         elgg_log("ElggIPResolver::resolveIP failed with the following message: " . $e->getMessage(), 'WARNING');
     }
     if ($data) {
         if ($format) {
             $formatter = new Formatter($data);
             return $formatter->format($format);
         } else {
             return $data;
         }
     } else {
         return false;
     }
 }
Ejemplo n.º 5
0
/**
 * Send a raw API call to an elgg api endpoint.
 *
 * @param array  $keys         The api keys.
 * @param string $url          URL of the endpoint.
 * @param array  $call         Associated array of "variable" => "value"
 * @param string $method       GET or POST
 * @param string $post_data    The post data
 * @param string $content_type The content type
 *
 * @return string
 */
function send_api_call(array $keys, $url, array $call, $method = 'GET', $post_data = '', $content_type = 'application/octet-stream')
{
    global $CONFIG;
    $headers = array();
    $encoded_params = array();
    $method = strtoupper($method);
    switch (strtoupper($method)) {
        case 'GET':
        case 'POST':
            break;
        default:
            $msg = elgg_echo('NotImplementedException:CallMethodNotImplemented', array($method));
            throw new NotImplementedException($msg);
    }
    // Time
    $time = time();
    // Nonce
    $nonce = uniqid('');
    // URL encode all the parameters
    foreach ($call as $k => $v) {
        $encoded_params[] = urlencode($k) . '=' . urlencode($v);
    }
    $params = implode('&', $encoded_params);
    // Put together the query string
    $url = $url . "?" . $params;
    // Construct headers
    $posthash = "";
    if ($method == 'POST') {
        $posthash = calculate_posthash($post_data, 'md5');
    }
    if (isset($keys['public']) && isset($keys['private'])) {
        $headers['X-Elgg-apikey'] = $keys['public'];
        $headers['X-Elgg-time'] = $time;
        $headers['X-Elgg-nonce'] = $nonce;
        $headers['X-Elgg-hmac-algo'] = 'sha1';
        $headers['X-Elgg-hmac'] = calculate_hmac('sha1', $time, $nonce, $keys['public'], $keys['private'], $params, $posthash);
    }
    if ($method == 'POST') {
        $headers['X-Elgg-posthash'] = $posthash;
        $headers['X-Elgg-posthash-algo'] = 'md5';
        $headers['Content-type'] = $content_type;
        $headers['Content-Length'] = strlen($post_data);
    }
    // Opt array
    $http_opts = array('method' => $method, 'header' => serialise_api_headers($headers));
    if ($method == 'POST') {
        $http_opts['content'] = $post_data;
    }
    $opts = array('http' => $http_opts);
    // Send context
    $context = stream_context_create($opts);
    // Send the query and get the result and decode.
    elgg_log("APICALL: {$url}");
    $results = file_get_contents($url, false, $context);
    return $results;
}
Ejemplo n.º 6
0
 /**
  * Set the search location
  * @param string $location		Location address
  * @param integer $radius		Radius in the unit of preset metric system (kilometer or mile)
  */
 public function setSearchLocation($location = '', $radius = 0)
 {
     $this->setRadius($radius);
     $this->setLocation($location);
     try {
         $query = new ElggMapQuery('proximity', array('location' => $this->getLocation(), 'latitude' => $this->getLatitude(), 'longitude' => $this->getLongitude(), 'radius' => $this->radius));
         $this->options = $query->sqlGetOptions($this->options);
     } catch (Exception $e) {
         elgg_log($e->getMessage(), 'ERROR');
     }
     return $this;
 }
Ejemplo n.º 7
0
 public function delete()
 {
     $result = false;
     $event = get_entity($this->event_guid);
     $result = remove_entity_relationship($this->event_guid, ZHAOHU_MANAGER_RELATION_ATTENDING, $this->user_guid);
     if (!$result) {
         elgg_log("ZHError ,coupon:delete, failed to remove_entity_relationship, coupon_id {$this->guid}", "ERROR");
         return false;
     }
     parent::delete();
     return true;
 }
Ejemplo n.º 8
0
Archivo: Resource.php Proyecto: n8b/VMN
 /**
  * Get contents of the page
  *
  * @param string $url     URL of the resource
  * @param array  $options HTTP request options
  * @return string
  */
 public function read($url = '', $options = array())
 {
     $body = '';
     if (!$this->exists($url)) {
         return $body;
     }
     try {
         $response = $this->client->get($url, $options)->send();
         $body = $response->getBody(true);
     } catch (Exception $ex) {
         elgg_log($ex->getMessage(), 'ERROR');
     }
     return $body;
 }
Ejemplo n.º 9
0
/**
 * This hooks into the getIcon API and returns a myicon icon
 */
function myicon_avatar_hook($hook, $type, $url, $params)
{
    $entity = $params['entity'];
    // check if user already has an icon
    if (!$entity->icontime) {
        $size = $params['size'];
        $icon = pickIcon($entity);
        if (!$icon) {
            elgg_log("ZHError ,myicon_avatar_hook, entity_id {$entity->guid}, user id " . elgg_get_logged_in_user_guid(), "ERROR");
            return false;
        }
        return "mod/myicon/icon.php?size={$size}&icon={$icon}";
    }
}
Ejemplo n.º 10
0
 /**
  * Delete a single version of the video
  */
 public function deleteFormat($format, $resolution = 0)
 {
     if (empty($resolution)) {
         // Use resolution of the original file as default
         $resolution = $this->resolution;
     }
     $sources = elgg_get_entities_from_metadata(array('type' => 'object', 'subtype' => 'video_source', 'container_guid' => $this->getGUID(), 'metadata_name_value_pairs' => array('format' => $format, 'resolution' => $resolution)));
     foreach ($sources as $source) {
         if ($source->delete()) {
             return true;
         } else {
             elgg_log("Video removal failed. Remove {$filepath} manually, please.", 'WARNING');
             return false;
         }
     }
 }
Ejemplo n.º 11
0
Archivo: Actions.php Proyecto: n8b/VMN
 /**
  * Executes an action
  * Triggers 'action:after', $ation hook that allows you to filter the Result object
  * 
  * @param mixed $controller Action name or instance of Action
  * @param bool  $feedback   Display errors and messages
  * @return ActionResult
  */
 public function execute($controller = null, $feedback = true)
 {
     try {
         $action = $this->parseActionName($controller);
         elgg_make_sticky_form($action);
         if (!$controller instanceof Action) {
             $controller = $this->getController($action);
         }
         if (!$controller instanceof Action) {
             throw new Exception("Not a valid action controller");
         }
         $controller->setup();
         if ($controller->validate() === false) {
             throw new ActionValidationException("Invalid input for action {$action}");
         }
         $controller->execute();
         $this->result = $controller->getResult();
     } catch (ActionValidationException $ex) {
         $this->result->addError($ex->getMessage());
         elgg_log($ex->getMessage(), 'ERROR');
     } catch (PermissionsException $ex) {
         $this->result->addError(elgg_echo('apps:permissions:error'));
         elgg_log($ex->getMessage(), 'ERROR');
     } catch (InvalidEntityException $ex) {
         $this->result->addError(elgg_echo('apps:entity:error'));
         elgg_log($ex->getMessage(), 'ERROR');
     } catch (Exception $ex) {
         $this->result->addError(elgg_echo('apps:action:error'));
         elgg_log($ex->getMessage(), 'ERROR');
     }
     $errors = $this->result->getErrors();
     $messages = $this->result->getMessages();
     if (empty($errors)) {
         elgg_clear_sticky_form($action);
     } else {
         $this->result->setForwardURL(REFERRER);
     }
     if ($feedback) {
         foreach ($errors as $error) {
             register_error($error);
         }
         foreach ($messages as $message) {
             system_message($message);
         }
     }
     return elgg_trigger_plugin_hook('action:after', $action, null, $this->result);
 }
Ejemplo n.º 12
0
 /**
  * Validate that the group default access isn't above the group settings for content
  *
  * @param string $hook         the name of the hook
  * @param string $type         the type of the hook
  * @param int    $return_value current return value
  * @param array  $params       supplied params
  *
  * @return void|int
  */
 public static function validateGroupDefaultAccess($hook, $type, $return_value, $params)
 {
     // check if the page owner is a group
     $page_owner = elgg_get_page_owner_entity();
     if (!$page_owner instanceof \ElggGroup) {
         return;
     }
     if ($page_owner->getContentAccessMode() !== \ElggGroup::CONTENT_ACCESS_MODE_MEMBERS_ONLY) {
         return;
     }
     if ($return_value !== ACCESS_PUBLIC && $return_value !== ACCESS_LOGGED_IN) {
         return;
     }
     // default access is higher than content access level, so lower
     elgg_log("Default access for the group {$page_owner->name} is set more public than the content access level", 'NOTICE');
     return (int) $page_owner->group_acl;
 }
Ejemplo n.º 13
0
function smf_register($user, $password)
{
    $api = new SmfRestClient(simple_auth(SMF_SEC_KEY, 'ENCODE'));
    $find = $api->get_user($user->username);
    if ($find->data != 'false') {
        return;
    }
    $code = simple_auth($password, 'ENCODE');
    $regOptions = array("member_name" => "{$user->username}", "real_name" => "{$user->name}", "email" => "{$user->email}", "password" => "{$code}", "require" => "nothing");
    // if use api call directly
    //$mem_id = smfapi_registerMember ( $regOptions );
    $mem_id = $api->register_member($regOptions);
    if (!$mem_id) {
        elgg_log("ZHError smf_register failed, user_id {$user->guid}", "ERROR");
    }
    return $mem_id;
}
Ejemplo n.º 14
0
/**
 * Register an item for an Elgg menu
 *
 * @warning Generally you should not use this in response to the plugin hook:
 * 'register', 'menu:<menu_name>'. If you do, you may end up with many incorrect
 * links on a dynamic menu.
 *
 * @warning A menu item's name must be unique per menu. If more than one menu
 * item with the same name are registered, the last menu item takes priority.
 *
 * @see elgg_view_menu() for the plugin hooks available for modifying a menu as
 * it is being rendered.
 *
 * @see ElggMenuItem::factory() is used to turn an array value of $menu_item into an
 * ElggMenuItem object.
 *
 * @param string $menu_name The name of the menu: site, page, userhover,
 *                          userprofile, groupprofile, or any custom menu
 * @param mixed  $menu_item An ElggMenuItem or options for ElggMenuItem::factory()
 *
 * @return bool False if the item could not be added
 * @since 1.8.0
 */
function elgg_register_menu_item($menu_name, $menu_item)
{
    global $CONFIG;
    if (!isset($CONFIG->menus[$menu_name])) {
        $CONFIG->menus[$menu_name] = array();
    }
    if (is_array($menu_item)) {
        $item = ElggMenuItem::factory($menu_item);
        if (!$item) {
            elgg_log("Unable to add menu item '{$menu_item['name']}' to '{$menu_name}' menu", 'WARNING');
            return false;
        }
    } else {
        $item = $menu_item;
    }
    $CONFIG->menus[$menu_name][] = $item;
    return true;
}
Ejemplo n.º 15
0
 /**
  * Loads the plugin by GUID or path.
  *
  * @warning Unlike other ElggEntity objects, you cannot null instantiate
  *          ElggPlugin. You must point it to an actual plugin GUID or location.
  *
  * @param mixed $plugin The GUID of the ElggPlugin object or the path of
  *                      the plugin to load.
  */
 public function __construct($plugin)
 {
     if (!$plugin) {
         throw new PluginException(elgg_echo('PluginException:NullInstantiated'));
     }
     // ElggEntity can be instantiated with a guid or an object.
     // @todo plugins w/id 12345
     if (is_numeric($plugin) || is_object($plugin)) {
         parent::__construct($plugin);
         $this->path = elgg_get_plugins_path() . $this->getID();
     } else {
         $plugin_path = elgg_get_plugins_path();
         // not a full path, so assume an id
         // use the default path
         if (strpos($plugin, $plugin_path) !== 0) {
             $plugin = $plugin_path . $plugin;
         }
         // path checking is done in the package
         $plugin = sanitise_filepath($plugin);
         $this->path = $plugin;
         $path_parts = explode('/', rtrim($plugin, '/'));
         $plugin_id = array_pop($path_parts);
         $this->pluginID = $plugin_id;
         // check if we're loading an existing plugin
         $existing_plugin = elgg_get_plugin_from_id($this->pluginID);
         $existing_guid = null;
         if ($existing_plugin) {
             $existing_guid = $existing_plugin->guid;
         }
         // load the rest of the plugin
         parent::__construct($existing_guid);
     }
     // We have to let the entity load so we can manipulate it with the API.
     // If the path is wrong or would cause an exception, catch it,
     // disable the plugin, and emit an error.
     try {
         $this->package = new ElggPluginPackage($this->path, false);
         $this->manifest = $this->package->getManifest();
     } catch (Exception $e) {
         // we always have to allow the entity to load.
         elgg_log("Failed to load {$this->guid} as a plugin. " . $e->getMessage(), 'WARNING');
         $this->errorMsg = $e->getmessage();
     }
 }
Ejemplo n.º 16
0
 /**
  * Process the scheduled exports
  *
  * @param string $hook         the name of the hook
  * @param string $type         the type of the hook
  * @param string $return_value current return value
  * @param array  $params       supplied params
  *
  * @return void
  */
 public static function processExports($hook, $type, $return_value, $params)
 {
     $time = (int) elgg_extract('time', $params, time());
     $options = ['type' => 'object', 'subtype' => \CSVExport::SUBTYPE, 'limit' => 10, 'metadata_name_value_pairs' => ['name' => 'scheduled', 'value' => $time, 'operand' => '<'], 'order_by_metadata' => ['name' => 'scheduled', 'direction' => 'asc', 'as' => 'integer']];
     // ignore access
     $ia = elgg_set_ignore_access(true);
     $batch = new \ElggBatch('elgg_get_entities_from_metadata', $options);
     $batch->setIncrementOffset(false);
     /* @var $csv_export \CSVExport */
     foreach ($batch as $csv_export) {
         if ($csv_export->isProcessing()) {
             elgg_log("CSV export '{$csv_export->getDisplayName()}' is already processing: {$csv_export->started}", 'NOTICE');
             continue;
         }
         $csv_export->process();
     }
     // restore access
     elgg_set_ignore_access($ia);
 }
 /**
  * Select menu items for the current context
  *
  * @return void
  */
 protected function selectFromContext()
 {
     if (!isset($this->menu)) {
         $this->menu = array();
         return;
     }
     // get menu items for this context
     $selected_menu = array();
     foreach ($this->menu as $menu_item) {
         if (!is_object($menu_item)) {
             elgg_log("A non-object was passed to ElggMenuBuilder", "ERROR");
             continue;
         }
         if ($menu_item->inContext()) {
             $selected_menu[] = $menu_item;
         }
     }
     $this->menu = $selected_menu;
 }
Ejemplo n.º 18
0
 /**
  * Open a file for reading, writing, or both.
  *
  * @note All files are opened binary safe.
  * @note This will try to create the a directory if it doesn't exist and is opened
  * in write or append mode.
  *
  * @param ElggFile $file The file to open
  * @param string   $mode read, write, or append.
  *
  * @throws InvalidParameterException
  * @return resource File pointer resource
  * @todo This really shouldn't try to create directories if not writing.
  */
 public function open(ElggFile $file, $mode)
 {
     $fullname = $this->getFilenameOnFilestore($file);
     // Split into path and name
     $ls = strrpos($fullname, "/");
     if ($ls === false) {
         $ls = 0;
     }
     $path = substr($fullname, 0, $ls);
     $name = substr($fullname, $ls);
     // @todo $name is unused, remove it or do we need to fix something?
     if ($mode != 'write' && !file_exists($fullname)) {
         return false;
     }
     // Try to create the dir for valid write modes
     if ($mode == 'write' || $mode == 'append') {
         try {
             $this->makeDirectoryRoot($path);
         } catch (Exception $e) {
             elgg_log("Couldn't create directory: {$path}", 'WARNING');
             return false;
         }
     }
     switch ($mode) {
         case "read":
             $mode = "rb";
             break;
         case "write":
             $mode = "w+b";
             break;
         case "append":
             $mode = "a+b";
             break;
         default:
             $msg = "Unrecognized file mode '" . $mode . "'";
             throw new InvalidParameterException($msg);
     }
     return fopen($fullname, $mode);
 }
Ejemplo n.º 19
0
/**
 * Creates and saves xAPI statements whenever new items are created
 *
 * @param string         $event "created"
 * @param string         $type  "river"
 * @param ElggRiverItem $river River item
 * @return bool
 */
function river_created_event($event, $type, $river)
{
    $subject = $river->getSubjectEntity();
    $object = $river->getObjectEntity();
    if (!$subject || !$object) {
        return true;
    }
    try {
        $verb = Verb::getVerbFromAction($river->action_type, $object->getType(), $object->getSubtype());
        $statement = new Statement();
        $statement->setActor($subject);
        $statement->setVerb($verb);
        $annotation = $river->getAnnotation();
        if ($annotation) {
            $statement->setTarget($annotation);
            $statement->setResult(array('response' => $annotation->value));
        } else {
            $statement->setTarget($object);
            if ($object instanceof ElggComment) {
                $statement->setResult(array('response' => $object->description));
            }
        }
        $response = $statement->save();
        if ($response->success) {
            // store TinCan Statement reference so that we can recycle it
            if ($river->action_type == 'create') {
                $object->__tincan_uuid = $response->content->getId();
            }
        } else {
            elgg_log("TinCan xAPI Error: " . print_r($response->httpResponse, true), 'ERROR');
        }
    } catch (\Exception $ex) {
        elgg_log("TinCan xAPI Fatal Error: " . $ex->getMessage(), 'ERROR');
    }
    return true;
}
Ejemplo n.º 20
0
Archivo: view.php Proyecto: ibou77/elgg
if (!$user) {
    $url = "_graphics/icons/default/{$size}.png";
    $url = elgg_normalize_url($url);
    forward($url);
}
$user_guid = $user->getGUID();
// Try and get the icon
$filehandler = new ElggFile();
$filehandler->owner_guid = $user_guid;
$filehandler->setFilename("profile/{$user_guid}{$size}.jpg");
$success = false;
try {
    if ($filehandler->open("read")) {
        if ($contents = $filehandler->read($filehandler->getSize())) {
            $success = true;
        }
    }
} catch (InvalidParameterException $e) {
    elgg_log("Unable to get avatar for user with GUID {$user_guid}", 'ERROR');
}
if (!$success) {
    $url = "_graphics/icons/default/{$size}.png";
    $url = elgg_normalize_url($url);
    forward($url);
}
header("Content-type: image/jpeg", true);
header('Expires: ' . gmdate('D, d M Y H:i:s \\G\\M\\T', strtotime("+6 months")), true);
header("Pragma: public", true);
header("Cache-Control: public", true);
header("Content-Length: " . strlen($contents));
echo $contents;
Ejemplo n.º 21
0
 * Passing an 'icon' with the variables will wrap the listing in an image block. In that case,
 * variables not listed in @uses (e.g. image_alt) will be passed to the image block.
 *
 * @uses $vars['entity']    ElggEntity
 * @uses $vars['title']     Title link (optional) false = no title, '' = default
 * @uses $vars['metadata']  HTML for entity menu and metadata (optional)
 * @uses $vars['subtitle']  HTML for the subtitle (optional)
 * @uses $vars['tags']      HTML for the tags (default is tags on entity, pass false for no tags)
 * @uses $vars['content']   HTML for the entity content (optional)
 * @uses $vars['icon']      Object icon. If set, the listing will be wrapped with an image block
 * @uses $vars['class']     Class selector for the image block
 * @uses $vars['image_block_vars'] Attributes for the image block wrapper
 */
$entity = elgg_extract('entity', $vars);
if (!$entity instanceof ElggEntity) {
    elgg_log("object/elements/summary expects an ElggEntity in \$vars['entity']", 'ERROR');
}
$title = elgg_extract('title', $vars, '');
if ($title === '' && $entity instanceof ElggEntity) {
    $vars['title'] = elgg_view('output/url', ['text' => elgg_get_excerpt($entity->getDisplayName(), 100), 'href' => $entity->getURL()]);
}
$tags = elgg_extract('tags', $vars, '');
if ($tags === '') {
    $tags = elgg_view('output/tags', ['entity' => $entity]);
}
$metadata = elgg_view('object/elements/summary/metadata', $vars);
$title = elgg_view('object/elements/summary/title', $vars);
$subtitle = elgg_view('object/elements/summary/subtitle', $vars);
$extensions = elgg_view('object/summary/extend', $vars);
$content = elgg_view('object/elements/summary/content', $vars);
$summary = $metadata . $title . $subtitle . $tags . $extensions . $content;
Ejemplo n.º 22
0
        if ($result) {
            $row = mysql_fetch_object($result);
            while ($row) {
                if ($row->name == 'dataroot') {
                    $data_root = $row->value;
                }
                $row = mysql_fetch_object($result);
            }
        }
        @mysql_close($mysql_dblink);
        if (isset($data_root)) {
            // this depends on ElggDiskFilestore::makeFileMatrix()
            $user_path = date('Y/m/d/', $join_date) . $owner_guid;
            $filename = "{$data_root}{$user_path}/videolist/{$guid}.jpg";
            $size = @filesize($filename);
            if ($size) {
                header("Content-type: image/jpeg");
                header('Expires: ' . gmdate('D, d M Y H:i:s \\G\\M\\T', strtotime("+6 months")), true);
                header("Pragma: public");
                header("Cache-Control: public");
                header("Content-Length: {$size}");
                readfile($filename);
                exit;
            }
        }
    }
}
// something went wrong so load engine and try to forward to default icon
require_once dirname(dirname(dirname(__FILE__))) . "/engine/start.php";
elgg_log("Profile icon direct failed.", "WARNING");
forward("mod/videolist/graphics/videolist_icon_{$size}.png");
Ejemplo n.º 23
0
Archivo: elgglib.php Proyecto: n8b/VMN
/**
 * Emits a shutdown:system event upon PHP shutdown, but before database connections are dropped.
 *
 * @tip Register for the shutdown:system event to perform functions at the end of page loads.
 *
 * @warning Using this event to perform long-running functions is not very
 * useful.  Servers will hold pages until processing is done before sending
 * them out to the browser.
 *
 * @see http://www.php.net/register-shutdown-function
 *
 * @return void
 * @see register_shutdown_hook()
 * @access private
 */
function _elgg_shutdown_hook()
{
    global $START_MICROTIME;
    try {
        elgg_trigger_event('shutdown', 'system');
        $time = (double) (microtime(true) - $START_MICROTIME);
        $uri = _elgg_services()->request->server->get('REQUEST_URI', 'CLI');
        // demoted to NOTICE from DEBUG so javascript is not corrupted
        elgg_log("Page {$uri} generated in {$time} seconds", 'INFO');
    } catch (Exception $e) {
        $message = 'Error: ' . get_class($e) . ' thrown within the shutdown handler. ';
        $message .= "Message: '{$e->getMessage()}' in file {$e->getFile()} (line {$e->getLine()})";
        error_log($message);
        error_log("Exception trace stack: {$e->getTraceAsString()}");
    }
    // Prevent an APC session bug: https://bugs.php.net/bug.php?id=60657
    session_write_close();
}
Ejemplo n.º 24
0
/**
 * Override the default entity icon for videoslist items
 *
 * @param string $hook
 * @param string $type
 * @param string $returnvalue
 * @param array $params
 * @return string Relative URL
 */
function videolist_icon_url_override($hook, $type, $returnvalue, $params)
{
    // if someone already set this, quit
    if ($return_value) {
        return null;
    }
    $videolist_item = $params['entity'];
    $size = $params['size'];
    if (!elgg_instanceof($videolist_item, 'object', 'videolist_item')) {
        return null;
    }
    // tiny thumbnails are too small to be useful, so give a generic video icon
    try {
        if ($size != 'tiny' && isset($videolist_item->thumbnail)) {
            $owner = $videolist_item->getOwnerEntity();
            $owner_guid = $owner->getGUID();
            $join_date = $owner->getTimeCreated();
            return "mod/videolist/thumbnail.php?joindate={$join_date}&guid={$videolist_item->guid}&owner_guid={$owner_guid}&size={$size}";
        }
    } catch (InvalidParameterException $e) {
        elgg_log("Unable to get videolist icon for video with GUID {$videolist_item->guid}", 'ERROR');
        return "mod/videolist/graphics/videolist_icon_{$size}.png";
    }
    if (in_array($size, array('tiny', 'small', 'medium'))) {
        return "mod/videolist/graphics/videolist_icon_{$size}.png";
    }
    return null;
}
Ejemplo n.º 25
0
/**
 * Emits a shutdown:system event upon PHP shutdown, but before database connections are dropped.
 *
 * @tip Register for the shutdown:system event to perform functions at the end of page loads.
 *
 * @warning Using this event to perform long-running functions is not very
 * useful.  Servers will hold pages until processing is done before sending
 * them out to the browser.
 *
 * @see http://www.php.net/register-shutdown-function
 *
 * @return void
 * @see register_shutdown_hook()
 * @access private
 */
function _elgg_shutdown_hook()
{
    global $START_MICROTIME;
    try {
        elgg_trigger_event('shutdown', 'system');
        $time = (double) (microtime(TRUE) - $START_MICROTIME);
        // demoted to NOTICE from DEBUG so javascript is not corrupted
        elgg_log("Page {$_SERVER['REQUEST_URI']} generated in {$time} seconds", 'NOTICE');
    } catch (Exception $e) {
        $message = 'Error: ' . get_class($e) . ' thrown within the shutdown handler. ';
        $message .= "Message: '{$e->getMessage()}' in file {$e->getFile()} (line {$e->getLine()})";
        error_log($message);
        error_log("Exception trace stack: {$e->getTraceAsString()}");
    }
}
Ejemplo n.º 26
0
/**
 * Register an item for an Elgg menu
 *
 * @warning Generally you should not use this in response to the plugin hook:
 * 'register', 'menu:<menu_name>'. If you do, you may end up with many incorrect
 * links on a dynamic menu.
 *
 * @warning A menu item's name must be unique per menu. If more than one menu
 * item with the same name are registered, the last menu item takes priority.
 *
 * @see elgg_view_menu() for the plugin hooks available for modifying a menu as
 * it is being rendered.
 *
 * @see ElggMenuItem::factory() is used to turn an array value of $menu_item into an
 * ElggMenuItem object.
 *
 * @param string $menu_name The name of the menu: site, page, userhover,
 *                          userprofile, groupprofile, or any custom menu
 * @param mixed  $menu_item A \ElggMenuItem object or an array of options in format:
 *                          name        => STR  Menu item identifier (required)
 *                          text        => STR  Menu item display text as HTML (required)
 *                          href        => STR  Menu item URL (required) (false for non-links.
 *                                              @warning If you disable the href the <a> tag will
 *                                              not appear, so the link_class will not apply. If you
 *                                              put <a> tags in manually through the 'text' option
 *                                              the default CSS selector .elgg-menu-$menu > li > a
 *                                              may affect formatting. Wrap in a <span> if it does.)
 *                          contexts    => ARR  Page context strings
 *                          section     => STR  Menu section identifier
 *                          title       => STR  Menu item tooltip
 *                          selected    => BOOL Is this menu item currently selected
 *                          parent_name => STR  Identifier of the parent menu item
 *                          link_class  => STR  A class or classes for the <a> tag
 *                          item_class  => STR  A class or classes for the <li> tag
 *
 *                          Additional options that the view output/url takes can be
 *							passed in the array. Custom options can be added by using
 *							the 'data' key with the	value being an associative array.
 *
 * @return bool False if the item could not be added
 * @since 1.8.0
 */
function elgg_register_menu_item($menu_name, $menu_item)
{
    global $CONFIG;
    if (is_array($menu_item)) {
        $options = $menu_item;
        $menu_item = \ElggMenuItem::factory($options);
        if (!$menu_item) {
            $menu_item_name = elgg_extract('name', $options, 'MISSING NAME');
            elgg_log("Unable to add menu item '{$menu_item_name}' to '{$menu_name}' menu", 'WARNING');
            return false;
        }
    }
    if (!$menu_item instanceof ElggMenuItem) {
        elgg_log('Second argument of elgg_register_menu_item() must be an instance of ElggMenuItem or an array of menu item factory options', 'ERROR');
        return false;
    }
    if (!isset($CONFIG->menus[$menu_name])) {
        $CONFIG->menus[$menu_name] = array();
    }
    $CONFIG->menus[$menu_name][] = $menu_item;
    return true;
}
Ejemplo n.º 27
0
/**
 * Remove a row from the database.
 *
 * @note Altering the DB invalidates all queries in {@link $DB_QUERY_CACHE}.
 *
 * @param string $query The SQL query to run
 *
 * @return int|false The number of affected rows or false on failure
 * @access private
 */
function delete_data($query)
{
    global $CONFIG, $DB_QUERY_CACHE;
    $query = elgg_format_query($query);
    elgg_log("DB query {$query}", 'NOTICE');
    $dblink = get_db_link('write');
    // Invalidate query cache
    if ($DB_QUERY_CACHE) {
        $DB_QUERY_CACHE->clear();
        elgg_log("Query cache invalidated", 'NOTICE');
    }
    if (execute_query("{$query}", $dblink)) {
        return mysql_affected_rows($dblink);
    }
    return FALSE;
}
Ejemplo n.º 28
0
/**
 * Calculate the HMAC for the http request.
 * This function signs an api request using the information provided. The signature returned
 * has been base64 encoded and then url encoded.
 *
 * @param string $algo          The HMAC algorithm used
 * @param string $time          String representation of unix time
 * @param string $nonce         Nonce
 * @param string $api_key       Your api key
 * @param string $secret_key    Your private key
 * @param string $get_variables URLEncoded string representation of the get variable parameters,
 *                              eg "method=user&guid=2"
 * @param string $post_hash     Optional sha1 hash of the post data.
 *
 * @return string The HMAC signature
 * @access private
 */
function calculate_hmac($algo, $time, $nonce, $api_key, $secret_key, $get_variables, $post_hash = "")
{
    elgg_log("HMAC Parts: {$algo}, {$time}, {$api_key}, {$secret_key}, {$get_variables}, {$post_hash}");
    $ctx = hash_init(map_api_hash($algo), HASH_HMAC, $secret_key);
    hash_update($ctx, trim($time));
    hash_update($ctx, trim($nonce));
    hash_update($ctx, trim($api_key));
    hash_update($ctx, trim($get_variables));
    if (trim($post_hash) != "") {
        hash_update($ctx, trim($post_hash));
    }
    return urlencode(base64_encode(hash_final($ctx, true)));
}
Ejemplo n.º 29
0
$text = get_input("comment");
$emails = get_input("email2invite");
if (empty($emails)) {
    register_error(elgg_echo("zhaohu:emails:empty"));
    forward(REFERER);
}
if (!is_array($emails)) {
    $emails = array($emails);
}
//fordebug register_error("emails ".$emails[0]);
$invited = 0;
// counters
// Invite by e-mail address
if (!empty($emails)) {
    foreach ($emails as $email) {
        //fordebug register_error("$zhaohuid " . $zhaohu->guid . " email " . $email. " text " . $text . ' resend ' . $resend);
        $invite_result = send_invite_email($logged_in_user, $zhaohu, $email, $text);
        //fordebug register_error("invite_result  ".$invite_result );
        if ($invite_result === true) {
            $invited++;
        }
    }
}
// which message to show
if ($invited) {
    system_message(elgg_echo("zhaohu:invite:ok"));
} else {
    register_error(elgg_echo('zhaohu:invite:err') . elgg_echo("zhaohu:sorry"));
    elgg_log("ZHError , zhgroups:invite, error sending invitations, user_id " . elgg_get_logged_in_user_guid() . " , emails " . implode("|", $emails), "ERROR");
}
forward(REFERER);
Ejemplo n.º 30
0
Archivo: table.php Proyecto: elgg/elgg
}
if (!is_array($items) || count($items) == 0) {
    if ($no_results) {
        if ($no_results instanceof Closure) {
            echo $no_results();
            return;
        }
        echo "<p class='elgg-no-results'>{$no_results}</p>";
    }
    return;
}
// render THEAD
$headings = '';
foreach ($columns as $column) {
    if (!$column instanceof TableColumn) {
        elgg_log('$vars["columns"] must be an array of ' . TableColumn::class, 'ERROR');
        return;
    }
    $cell = trim($column->renderHeading());
    if (!preg_match('~^<t[dh]~i', $cell)) {
        $cell = "<th>{$cell}</th>";
    }
    $headings .= $cell;
}
$headings = "<thead><tr>{$headings}</tr></thead>";
$table_classes = ['elgg-list', 'elgg-table'];
if (isset($vars['list_class'])) {
    $table_classes[] = $vars['list_class'];
}
$nav = $pagination ? elgg_view('navigation/pagination', $vars) : '';
$rows = '';