Пример #1
0
/**
 * Worker - performs sending of registration data to mahara.org
 */
function registration_send_data()
{
    $registrationurl = 'http://mahara.org/api/registration.php';
    $data = registration_data();
    $request = array(CURLOPT_URL => $registrationurl, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => $data);
    return mahara_http_request($request);
}
 private static function scrape_url($url)
 {
     $config = array(CURLOPT_URL => $url);
     static $scrape_regex = '#.*?https?://(www\\.)?slideshare\\.net/share/(tweet|facebook|linkedin)/([0-9]+)/.*#';
     $data = mahara_http_request($config);
     if (preg_match($scrape_regex, $data->data, $matches)) {
         $slideid = $matches[3];
         return 'http://www.slideshare.net/slideshow/embed_code/' . $slideid;
     }
     return false;
 }
 private static function scrape_url($url)
 {
     $config = array(CURLOPT_URL => $url);
     $data = mahara_http_request($config);
     if (!empty($data->data)) {
         if (preg_match('#.*var *wgArticleId *= *"?([0-9]+)"?;.*#', $data->data, $matches)) {
             $newurl = self::$base_url . 'index.php?curid=' . $matches[1];
             return $newurl;
         }
     }
     return false;
 }
 private static function scrape_url($url)
 {
     $config = array(CURLOPT_URL => $url);
     $data = mahara_http_request($config);
     if (!empty($data->data)) {
         if (preg_match('#<textarea[^>]*?id="glogiframe"[^>]*>.*?\\bsrc\\s*=\\s*"([^>"]+)"[^<]*</textarea>#m', $data->data, $matches)) {
             $iframe = html_entity_decode($matches[1], ENT_QUOTES);
             return $iframe;
         }
     }
     return false;
 }
Пример #5
0
 public static function render_instance(BlockInstance $instance, $editing = false)
 {
     global $USER;
     // Get site wide Embed.ly API key
     $embedlyapikey = get_config_plugin('blocktype', 'embedly', 'embedlysiteapikey');
     // Get user's Embed.ly API key if site wide key is empty or not set
     if (empty($embedlyapikey) || !isset($embedlyapikey)) {
         $owner = $instance->get('view_obj')->get('owner');
         $embedlyapikey = get_account_preference($owner, 'embedlyapikey');
     }
     $configdata = $instance->get('configdata');
     $width = !empty($configdata['width']) ? hsc($configdata['width']) : null;
     $height = !empty($configdata['height']) ? hsc($configdata['height']) : null;
     $align = !empty($configdata['align']) ? hsc($configdata['align']) : 'left';
     $result = '';
     // To silence warning
     if (isset($configdata['mediaid'])) {
         // IE seems to wait for all elements on the page to load
         // fully before the onload event goes off.  This means the
         // view editor isn't initialised until all videos have
         // finished loading, and an invalid video URL can stop the
         // editor from loading and result in an uneditable view.
         // Therefore, when this block appears on first load of the
         // view editing page, keep the embed code out of the page
         // initially and add it in after the page has loaded.
         $url = 'http://api.embed.ly/1/oembed?key=' . $embedlyapikey . '&url=' . urlencode($configdata['mediaid']) . '&maxwidth=' . $width . '&maxheight=' . $height . '&wmode=transparent';
         $request = array(CURLOPT_URL => $url);
         $result = mahara_http_request($request);
         $data = json_decode($result->data, true);
         $result = '<div class="' . $align . '">';
         $result .= '<p>' . $configdata['mediadesc'] . '</p>';
         switch ($data['type']) {
             case 'photo':
                 $result .= '<img src="' . $data['url'] . '" width="' . $width . '" height="' . $height . '" border="0">';
                 break;
             case 'video':
             case 'rich':
                 $result .= $data['html'];
                 break;
             case 'link':
                 $result .= $configdata['mediaid'];
                 break;
         }
         if (isset($data['description']) && !empty($configdata['showdescription'])) {
             $result .= '<p>' . nl2br($data['description']) . '</p>';
         }
         $result .= '</div>';
     }
     return $result;
 }
Пример #6
0
 /**
  * Single HTTP Request
  *
  * @param string $url The URL to request
  * @param array $options cUrl options
  * @return bool
  */
 protected function request($url, $method = 'get', $data = array(), array $additional_opts = array())
 {
     $curlopts = array(CURLOPT_URL => $url);
     if ($method === 'get') {
         $curlopts[CURLOPT_HTTPGET] = true;
     } else {
         if ($method === 'post') {
             $curlopts[CURLOPT_POST] = true;
             $curlopts[CURLOPT_POSTFIELDS] = $data;
         }
     }
     if (!empty($this->headers)) {
         $headers = [];
         foreach ($this->headers as $k => $v) {
             $headers[] = $k . ': ' . $v;
         }
         $curlopts[CURLOPT_HTTPHEADER] = $headers;
     }
     $result = mahara_http_request($curlopts);
     return $result->data;
 }
Пример #7
0
 /**
  * Parses the RSS feed given by $source. Throws an exception if the feed 
  * isn't able to be parsed
  *
  * @param string $source The URI for the feed
  * @throws XML_Feed_Parser_Exception
  */
 public static function parse_feed($source)
 {
     static $cache;
     if (empty($cache)) {
         $cache = array();
     }
     if (array_key_exists($source, $cache)) {
         return $cache[$source];
     }
     require_once 'XML/Feed/Parser.php';
     $config = array(CURLOPT_URL => $source);
     $result = mahara_http_request($config);
     if ($result->error) {
         throw new XML_Feed_Parser_Exception($result->error);
     }
     if (empty($result->data)) {
         throw new XML_Feed_Parser_Exception('Feed url returned no data');
     }
     try {
         $feed = new XML_Feed_Parser($result->data, false, true, false);
     } catch (XML_Feed_Parser_Exception $e) {
         $cache[$source] = $e;
         throw $e;
         // Don't catch other exceptions, they're an indication something
         // really bad happened
     }
     $data = new StdClass();
     $data->title = $feed->title;
     $data->url = $source;
     $data->link = $feed->link;
     $data->description = $feed->description;
     // Work out the icon for the feed depending on whether it's RSS or ATOM
     $data->image = $feed->image;
     if (!$data->image) {
         // ATOM feed. These are simple strings
         $data->image = $feed->logo ? $feed->logo : null;
     }
     $data->content = array();
     foreach ($feed as $count => $item) {
         if ($count == 20) {
             break;
         }
         $description = $item->content ? $item->content : ($item->description ? $item->description : ($item->summary ? $item->summary : null));
         $data->content[] = (object) array('title' => $item->title, 'link' => $item->link, 'description' => $description);
     }
     $cache[$source] = $data;
     return $data;
 }
Пример #8
0
/**
 * Return a Gravatar URL if one exists for the given user.
 *
 * @param string  $email         Email address of the user
 * @param object  $size          Maximum size of the image
 * @param boolean $notfound      The value to return if the avatar is not found
 *
 * @returns string The URL of the image or $notfound if none was found
 */
function remote_avatar($email, $size, $notfound)
{
    if (!get_config('remoteavatars')) {
        return false;
    }
    require_once 'file.php';
    $md5sum = md5(strtolower($email));
    $s = 100;
    $newsize = image_get_new_dimensions($s, $s, $size);
    if ($newsize) {
        $s = min($newsize['w'], $newsize['h']);
    }
    $baseurl = 'http://www.gravatar.com/avatar/';
    if (is_https() === true) {
        $baseurl = 'https://secure.gravatar.com/avatar/';
    }
    if (get_config('remoteavatarbaseurl')) {
        $baseurl = get_config('remoteavatarbaseurl');
    }
    // Check if it is a valid avatar
    $result = mahara_http_request(array(CURLOPT_URL => "{$baseurl}{$md5sum}.jpg?d=404", CURLOPT_HEADER => true, CURLOPT_NOBODY => true), true);
    if (!$result || $result->error || $result->info['http_code'] == 404) {
        return $notfound;
    }
    return "{$baseurl}{$md5sum}.jpg?r=g&s={$s}";
}
Пример #9
0
 /**
  * Checks if $CFG->behat_wwwroot is available
  *
  * @return bool
  */
 public static function is_server_running()
 {
     global $CFG;
     $request = mahara_http_request(array(CURLOPT_URL => $CFG->behat_wwwroot, CURLOPT_TIMEOUT => 5, CURLOPT_USERAGENT => ''), true);
     return !$request->error;
 }
Пример #10
0
 private static function get_group_opt($host, $uid)
 {
     $opt = array();
     $backpack_url = self::get_backpack_url($host);
     $res = mahara_http_request(array(CURLOPT_URL => $backpack_url . "displayer/{$uid}/groups.json"));
     $res = json_decode($res->data);
     if (!empty($res->groups)) {
         foreach ($res->groups as $g) {
             if ($g->name == 'Public badges' && $g->groupId == 0) {
                 $name = get_string('obppublicbadges', 'blocktype.openbadgedisplayer');
             } else {
                 $name = hsc($g->name);
             }
             $name .= ' (' . get_string('nbadges', 'blocktype.openbadgedisplayer', $g->badges) . ')';
             $cb_id = $host . ':' . $uid . ':' . $g->groupId;
             $cb_name = self::_sanitize_name($cb_id);
             $opt[$cb_name] = array('type' => 'checkbox', 'title' => $name, 'value' => $cb_id);
         }
     }
     return $opt;
 }
Пример #11
0
 /**
  * Parses the RSS feed given by $source. Throws an exception if the feed
  * isn't able to be parsed
  *
  * @param string $source The URI for the feed
  * @param bool $insecuresslmode Skip certificate checking
  * @param string $authuser HTTP basic auth username to use
  * @param string $authpassword HTTP basic auth password to use
  * @throws XML_Feed_Parser_Exception
  */
 public static function parse_feed($source, $insecuresslmode = false, $authuser = '', $authpassword = '')
 {
     static $cache;
     if (empty($cache)) {
         $cache = array();
     }
     if (array_key_exists($source, $cache)) {
         if ($cache[$source] instanceof Exception) {
             throw $cache[$source];
         }
         return $cache[$source];
     }
     $config = array(CURLOPT_URL => $source, CURLOPT_TIMEOUT => 15, CURLOPT_USERAGENT => '');
     if (!empty($authuser) || !empty($authpassword)) {
         $config[CURLOPT_USERPWD] = $authuser . ':' . $authpassword;
     }
     if ($insecuresslmode) {
         $config[CURLOPT_SSL_VERIFYPEER] = false;
     }
     $result = mahara_http_request($config, true);
     if ($result->error) {
         throw new XML_Feed_Parser_Exception($result->error);
     }
     if (empty($result->data)) {
         throw new XML_Feed_Parser_Exception('Feed url returned no data');
     }
     try {
         $feed = new XML_Feed_Parser($result->data, false, true, false);
     } catch (XML_Feed_Parser_Exception $e) {
         $cache[$source] = $e;
         throw $e;
         // Don't catch other exceptions, they're an indication something
         // really bad happened
     }
     $data = new StdClass();
     $data->title = $feed->title;
     $data->url = $source;
     $data->authuser = $authuser;
     $data->authpassword = $authpassword;
     $data->insecuresslmode = (int) $insecuresslmode;
     $data->link = $feed->link;
     $data->description = $feed->description;
     // Work out the icon for the feed depending on whether it's RSS or ATOM
     $data->image = $feed->image;
     if (!$data->image) {
         // ATOM feed. These are simple strings
         $data->image = $feed->logo ? $feed->logo : null;
     }
     $data->content = array();
     foreach ($feed as $count => $item) {
         if ($count == 20) {
             break;
         }
         $description = $item->content ? $item->content : ($item->description ? $item->description : ($item->summary ? $item->summary : null));
         if (!$item->title) {
             if (!empty($description)) {
                 $item->title = substr($description, 0, 60);
             } else {
                 if ($item->link) {
                     $item->title = $item->link;
                 } else {
                     $item->title = get_string('notitle', 'view');
                 }
             }
         }
         if (!($pubdate = $item->pubDate)) {
             if (!($pubdate = $item->date)) {
                 if (!($pubdate = $item->published)) {
                     $pubdate = $item->updated;
                 }
             }
         }
         $data->content[] = (object) array('title' => $item->title, 'link' => $item->link, 'description' => $description, 'pubdate' => $pubdate);
     }
     $cache[$source] = $data;
     return $data;
 }
Пример #12
0
 /**
  * Function to check a BrowserID verifier status
  * @return boolean true if the verifier is available, false otherwise
  */
 public static function is_available()
 {
     // Send a test assertion to the verification service
     $request = array(CURLOPT_URL => self::BROWSERID_VERIFIER_URL, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => 'request=1');
     $response = mahara_http_request($request);
     if (!empty($response->data)) {
         $jsondata = json_decode($response->data);
         return !empty($jsondata);
     }
     return false;
 }
    $SESSION->set('fileformat', '');
    $SESSION->set('photograph', '');
    $SESSION->set('internaldate', '');
    $SESSION->set('externaldate', '');
    // Stop processing the page
    exit;
}
if ($locale != '' and $fileformat != '' and $internaldate != '' and $externaldate != '') {
    if (in_array($fileformat, array('pdf', 'doc', 'odt', 'html'))) {
        $document = generate_europasscv_xml($USER->get('id'), false, $locale, $internaldate, $externaldate, $photograph);
        // Call XML Upgrade service
        $url = 'https://europass.cedefop.europa.eu/rest/v1/document/upgrade';
        $header = array();
        $header[] = 'Content-Type: application/xml';
        $config = array(CURLOPT_URL => $url, CURLOPT_PORT => '443', CURLOPT_HEADER => true, CURLOPT_HTTPHEADER => $header, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $document, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_CAINFO => get_config('docroot') . 'artefact/europass/cert/cacert.crt');
        $result = mahara_http_request($config);
        if ($result->info['http_code'] == 200 && !empty($result->data)) {
            $document_v3 = substr($result->data, $result->info['header_size']);
            // Call the API method
            switch ($fileformat) {
                case 'pdf':
                    $url = 'https://europass.cedefop.europa.eu/rest/v1/document/to/pdf';
                    break;
                case 'doc':
                    $url = 'https://europass.cedefop.europa.eu/rest/v1/document/to/word';
                    break;
                case 'odt':
                    $url = 'https://europass.cedefop.europa.eu/rest/v1/document/to/opendoc';
                    break;
            }
            $header = array();
Пример #14
0
 function send($wwwroot, $use_cached_peer = true)
 {
     $this->peer = get_peer($wwwroot, $use_cached_peer);
     $this->response = '';
     $URL = $this->peer->wwwroot . $this->peer->application->xmlrpcserverurl;
     $this->requesttext = xmlrpc_encode_request($this->method, $this->params, array("encoding" => "utf-8"));
     $this->signedrequest = xmldsig_envelope($this->requesttext);
     $this->encryptedrequest = xmlenc_envelope($this->signedrequest, $this->peer->certificate);
     $config = array(CURLOPT_URL => $URL, CURLOPT_TIMEOUT => $this->timeout, CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_USERAGENT => 'Mahara', CURLOPT_POSTFIELDS => $this->encryptedrequest, CURLOPT_HTTPHEADER => array("Content-Type: text/xml charset=UTF-8", 'Expect: '), CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => 0);
     $result = mahara_http_request($config);
     $timestamp_send = time();
     $this->rawresponse = $result->data;
     $response_code = $result->info['http_code'];
     $response_code_prefix = substr($response_code, 0, 1);
     if ('2' != $response_code_prefix) {
         if ('4' == $response_code_prefix) {
             throw new XmlrpcClientException('Client error code: ' . $response_code);
         } else {
             if ('5' == $response_code_prefix) {
                 throw new XmlrpcClientException('An error occurred at the remote server. Code: ' . $response_code);
             }
         }
     }
     $timestamp_receive = time();
     $remote_timestamp = null;
     $curl_errno = $result->errno;
     if ($curl_errno || $this->rawresponse == false) {
         throw new XmlrpcClientException('Curl error: ' . $curl_errno . ': ' . $result->error);
         return false;
     }
     try {
         $xml = new SimpleXMLElement(trim($this->rawresponse));
     } catch (Exception $e) {
         log_debug($this->rawresponse);
         throw new XmlrpcClientException('Payload is not a valid XML document (payload is above)', 6001);
     }
     try {
         if ($xml->getName() == 'encryptedMessage') {
             $payload_encrypted = true;
             $wwwroot = (string) $xml->wwwroot;
             // Strip encryption, using an older code is OK, because we're the client.
             // The server is able to respond with the correct key, be we're not
             $payload = xmlenc_envelope_strip($xml, true);
         }
         if ($xml->getName() == 'signedMessage') {
             $payload_signed = true;
             $remote_timestamp = $xml->timestamp;
             $payload = xmldsig_envelope_strip($xml);
         }
     } catch (CryptException $e) {
         throw new XmlrpcClientException("An error occurred while decrypting a message sent by {$wwwroot}. Unable to authenticate the user.");
     }
     if ($xml->getName() == 'methodResponse') {
         $this->response = xmlrpc_decode($payload);
         // Margin of error is the time it took the request to complete.
         $margin_of_error = $timestamp_receive - $timestamp_send;
         // Guess the time gap between sending the request and the remote machine
         // executing the time() function. Marginally better than nothing.
         $hysteresis = $margin_of_error / 2;
         if (!empty($remote_timestamp)) {
             $remote_timestamp = $remote_timestamp - $hysteresis;
             $time_offset = $remote_timestamp - $timestamp_send;
             if ($time_offset > self::get_max_server_time_difference()) {
                 throw new XmlrpcClientException('Time drift (' . $margin_of_error . ', ' . $time_offset . ') is too large.');
             }
         }
         if (is_array($this->response) && array_key_exists('faultCode', $this->response)) {
             if ($this->response['faultCode'] == 7025) {
                 log_info('Remote application has sent us a new public key');
                 // The remote application sent back a new public key, the
                 // old one must have expired
                 if (array_key_exists('faultString', $this->response)) {
                     $details = openssl_x509_parse($this->response['faultString']);
                     if (isset($details['validTo_time_t'])) {
                         $updateobj = (object) array('publickey' => $this->response['faultString'], 'publickeyexpires' => $details['validTo_time_t']);
                         $whereobj = (object) array('wwwroot' => $wwwroot);
                         update_record('host', $updateobj, $whereobj);
                         log_info('New key has been imported. Valid until ' . date('Y/m/d h:i:s', $details['validTo_time_t']));
                         // Send request again. But don't use the cached
                         // peer, look it up again now we've changed the
                         // public key
                         $this->send($wwwroot, false);
                     } else {
                         throw new XmlrpcClientException('Could not parse new public key');
                     }
                 } else {
                     throw new XmlrpcClientException('Remote site claims to have sent a public key, but they LIE');
                 }
             }
             throw new XmlrpcClientException('Unknown error occurred: ' . $this->response['faultCode'] . ': ' . $this->response['faultString']);
         }
         // Clean up so object can be re-used.
         $this->requesttext = '';
         $this->signedrequest = '';
         $this->encryptedrequest = '';
         $this->params = array();
         $this->method = '';
         return true;
     } else {
         throw new XmlrpcClientException('Unrecognized XML document form: ' . $payload);
     }
 }
Пример #15
0
/**
 * Cronjob to check Launchpad for the latest Mahara version
 */
function cron_check_for_updates()
{
    $request = array(CURLOPT_URL => 'https://launchpad.net/mahara/+download');
    $result = mahara_http_request($request);
    if (!empty($result->errno)) {
        log_debug('Could not retrieve launchpad download page');
        return;
    }
    $page = new DOMDocument();
    libxml_use_internal_errors(true);
    $success = $page->loadHTML($result->data);
    libxml_use_internal_errors(false);
    if (!$success) {
        log_debug('Error parsing launchpad download page');
        return;
    }
    $xpath = new DOMXPath($page);
    $query = '//div[starts-with(@id,"release-information-")]';
    $elements = $xpath->query($query);
    $versions = array();
    foreach ($elements as $e) {
        if (preg_match('/^release-information-(\\d+)-(\\d+)-(\\d+)$/', $e->getAttribute('id'), $match)) {
            $versions[] = "{$match['1']}.{$match['2']}.{$match['3']}";
        }
    }
    if (!empty($versions)) {
        usort($versions, 'strnatcmp');
        set_config('latest_version', end($versions));
    }
}
Пример #16
0
 public static function render_instance(BlockInstance $instance, $editing = false)
 {
     $configdata = $instance->get('configdata');
     // this will make sure to unserialize it for us
     $configdata['viewid'] = $instance->get('view');
     $style = isset($configdata['style']) ? intval($configdata['style']) : 2;
     $copyright = null;
     // Needed to set Panoramio copyright later...
     $width = !empty($configdata['width']) ? $configdata['width'] : 75;
     switch ($style) {
         case 0:
             // thumbnails
             $template = 'thumbnails';
             break;
         case 1:
             // slideshow
             $template = 'slideshow';
             $width = !empty($configdata['width']) ? $configdata['width'] : 400;
             break;
         case 2:
             // square thumbnails
             $template = 'squarethumbs';
             break;
     }
     $images = array();
     $slimbox2 = get_config_plugin('blocktype', 'gallery', 'useslimbox2');
     if ($slimbox2) {
         $slimbox2attr = 'lightbox_' . $instance->get('id');
     } else {
         $slimbox2attr = null;
     }
     // if we're trying to embed external gallery (thumbnails or slideshow)
     if (isset($configdata['select']) && $configdata['select'] == 2) {
         $gallery = self::make_gallery_url($configdata['external']);
         if (empty($gallery)) {
             return get_string('externalnotsupported', 'blocktype.file/gallery');
         }
         $url = isset($gallery['url']) ? hsc($gallery['url']) : null;
         $type = isset($gallery['type']) ? hsc($gallery['type']) : null;
         $var1 = isset($gallery['var1']) ? hsc($gallery['var1']) : null;
         $var2 = isset($gallery['var2']) ? hsc($gallery['var2']) : null;
         switch ($type) {
             case 'widget':
                 /*****************************
                            Roy Tanck's FLICKR WIDGET
                            for Flickr RSS & Picasa RSS
                    http://www.roytanck.com/get-my-flickr-widget/
                           *****************************/
                 $widget_sizes = array(100, 200, 300);
                 $width = self::find_nearest($widget_sizes, $width);
                 $images = urlencode(str_replace('&amp;', '&', $url));
                 $template = 'imagecloud';
                 break;
             case 'picasa':
                 // Slideshow
                 if ($style == 1) {
                     $picasa_show_sizes = array(144, 288, 400, 600, 800);
                     $width = self::find_nearest($picasa_show_sizes, $width);
                     $height = round($width * 0.75);
                     $images = array('user' => $var1, 'gallery' => $var2);
                     $template = 'picasashow';
                 } else {
                     $picasa_thumbnails = array(32, 48, 64, 72, 104, 144, 150, 160);
                     $width = self::find_nearest($picasa_thumbnails, $width);
                     // If the Thumbnails should be Square...
                     if ($style == 2) {
                         $small = 's' . $width . '-c';
                         $URL = 'http://picasaweb.google.com/data/feed/api/user/' . $var1 . '/album/' . $var2 . '?kind=photo&thumbsize=' . $width . 'c';
                     } else {
                         $small = 's' . $width;
                         $URL = 'http://picasaweb.google.com/data/feed/api/user/' . $var1 . '/album/' . $var2 . '?kind=photo&thumbsize=' . $width;
                     }
                     $big = 's' . get_config_plugin('blocktype', 'gallery', 'previewwidth');
                     $xmlDoc = new DOMDocument('1.0', 'UTF-8');
                     $config = array(CURLOPT_URL => $URL, CURLOPT_RETURNTRANSFER => true);
                     $result = mahara_http_request($config);
                     $xmlDoc->loadXML($result->data);
                     $photos = $xmlDoc->getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'group');
                     foreach ($photos as $photo) {
                         $children = $photo->cloneNode(true);
                         $thumb = $children->getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'thumbnail')->item(0)->getAttribute('url');
                         $description = null;
                         if (isset($children->getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'description')->item(0)->firstChild->nodeValue)) {
                             $description = $children->getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'description')->item(0)->firstChild->nodeValue;
                         }
                         $images[] = array('link' => str_replace($small, $big, $thumb), 'source' => $thumb, 'title' => $description, 'slimbox2' => $slimbox2attr);
                     }
                 }
                 break;
             case 'flickr':
                 // Slideshow
                 if ($style == 1) {
                     $flickr_show_sizes = array(400, 500, 700, 800);
                     $width = self::find_nearest($flickr_show_sizes, $width);
                     $height = round($width * 0.75);
                     $images = array('user' => $var1, 'gallery' => $var2);
                     $template = 'flickrshow';
                 } else {
                     $width = 75;
                     // Currently only thumbnail size, that Flickr supports
                     $api_key = get_config_plugin('blocktype', 'gallery', 'flickrapikey');
                     $URL = 'http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&extras=url_sq,url_t&photoset_id=' . $var2 . '&api_key=' . $api_key;
                     $xmlDoc = new DOMDocument('1.0', 'UTF-8');
                     $config = array(CURLOPT_URL => $URL, CURLOPT_RETURNTRANSFER => true);
                     $result = mahara_http_request($config);
                     $xmlDoc->loadXML($result->data);
                     $photos = $xmlDoc->getElementsByTagName('photo');
                     foreach ($photos as $photo) {
                         // If the Thumbnails should be Square...
                         if ($style == 2) {
                             $thumb = $photo->getAttribute('url_sq');
                             $link = str_replace('_s.jpg', '_b.jpg', $thumb);
                         } else {
                             $thumb = $photo->getAttribute('url_t');
                             $link = str_replace('_t.jpg', '_b.jpg', $thumb);
                         }
                         $description = $photo->getAttribute('title');
                         $images[] = array('link' => $link, 'source' => $thumb, 'title' => $description, 'slimbox2' => $slimbox2attr);
                     }
                 }
                 break;
             case 'panoramio':
                 // Slideshow
                 if ($style == 1) {
                     $height = round($width * 0.75);
                     $images = array('user' => $var1);
                     $template = 'panoramioshow';
                 } else {
                     $copyright = get_string('panoramiocopyright', 'blocktype.file/gallery');
                     $URL = 'http://www.panoramio.com/map/get_panoramas.php?set=' . $var1 . '&from=0&to=50&size=original&mapfilter=true';
                     $config = array(CURLOPT_URL => $URL, CURLOPT_RETURNTRANSFER => true);
                     $result = mahara_http_request($config);
                     $data = json_decode($result->data, true);
                     foreach ($data['photos'] as $photo) {
                         $link = str_replace('/original/', '/large/', $photo['photo_file_url']);
                         // If the Thumbnails should be Square...
                         if ($style == 2) {
                             $thumb = str_replace('/original/', '/square/', $photo['photo_file_url']);
                             $width = 60;
                             // Currently only square thumbnail size, that Panoramio supports
                         } else {
                             $thumb = str_replace('/original/', '/thumbnail/', $photo['photo_file_url']);
                         }
                         $title = !empty($photo['photo_title']) ? $photo['photo_title'] : get_string('Photo', 'blocktype.file/gallery');
                         $description = '<a href="' . $photo['photo_url'] . '" target="_blank">' . $title . '</a>' . '&nbsp;' . get_string('by', 'blocktype.file/gallery') . '&nbsp;' . '<a href="' . $photo['owner_url'] . '" target="_blank">' . $photo['owner_name'] . '</a>';
                         $images[] = array('link' => $link, 'source' => $thumb, 'title' => $description, 'slimbox2' => $slimbox2attr);
                     }
                 }
                 break;
             case 'photobucket':
                 // Slideshow
                 if ($style == 1) {
                     $height = round($width * 0.75);
                     $images = array('url' => $url, 'user' => $var1, 'album' => $var2);
                     $template = 'photobucketshow';
                 } else {
                     $consumer_key = get_config_plugin('blocktype', 'gallery', 'pbapikey');
                     // PhotoBucket API key
                     $consumer_secret = get_config_plugin('blocktype', 'gallery', 'pbapiprivatekey');
                     //PhotoBucket API private key
                     $oauth_signature_method = 'HMAC-SHA1';
                     $oauth_version = '1.0';
                     $oauth_timestamp = time();
                     $mt = microtime();
                     $rand = mt_rand();
                     $oauth_nonce = md5($mt . $rand);
                     $method = 'GET';
                     $albumname = $var1 . '/' . $var2;
                     $api_url = 'http://api.photobucket.com/album/' . urlencode($albumname);
                     $params = null;
                     $paramstring = 'oauth_consumer_key=' . $consumer_key . '&oauth_nonce=' . $oauth_nonce . '&oauth_signature_method=' . $oauth_signature_method . '&oauth_timestamp=' . $oauth_timestamp . '&oauth_version=' . $oauth_version;
                     $base = urlencode($method) . '&' . urlencode($api_url) . '&' . urlencode($paramstring);
                     $oauth_signature = base64_encode(hash_hmac('sha1', $base, $consumer_secret . '&', true));
                     $URL = $api_url . '?' . $paramstring . '&oauth_signature=' . urlencode($oauth_signature);
                     $xmlDoc = new DOMDocument('1.0', 'UTF-8');
                     $config = array(CURLOPT_URL => $URL, CURLOPT_HEADER => false, CURLOPT_RETURNTRANSFER => true);
                     $result = mahara_http_request($config);
                     $xmlDoc->loadXML($result->data);
                     $xmlDoc2 = new DOMDocument('1.0', 'UTF-8');
                     $config2 = array(CURLOPT_URL => $xmlDoc->getElementsByTagName('url')->item(0)->firstChild->nodeValue, CURLOPT_HEADER => false, CURLOPT_RETURNTRANSFER => true);
                     $result2 = mahara_http_request($config2);
                     $xmlDoc2->loadXML($result->data);
                     $photos = $xmlDoc2->getElementsByTagName('media');
                     foreach ($photos as $photo) {
                         $children = $photo->cloneNode(true);
                         $link = $children->getElementsByTagName('url')->item(0)->firstChild->nodeValue;
                         $thumb = $children->getElementsByTagName('thumb')->item(0)->firstChild->nodeValue;
                         $description = null;
                         if (isset($children->getElementsByTagName('description')->item(0)->firstChild->nodeValue)) {
                             $description = $children->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
                         }
                         $images[] = array('link' => $link, 'source' => $thumb, 'title' => $description, 'slimbox2' => $slimbox2attr);
                     }
                 }
                 break;
             case 'windowslive':
                 // Slideshow
                 if ($style == 1) {
                     $images = array('url' => $url, 'user' => $var1, 'album' => $var2);
                     $template = 'windowsliveshow';
                 } else {
                     $config = array(CURLOPT_URL => str_replace(' ', '%20', $url), CURLOPT_HEADER => false, CURLOPT_RETURNTRANSFER => true);
                     $result = mahara_http_request($config);
                     $data = $result->data;
                     // Extract data about images and thumbs from HTML source - hack!
                     preg_match_all("#previewImageUrl: '([a-zA-Z0-9\\_\\-\\.\\\\/]+)'#", $data, $photos);
                     preg_match_all("#thumbnailImageUrl: '([a-zA-Z0-9\\_\\-\\.\\\\/]+)'#", $data, $thumbs);
                     for ($i = 0; $i < sizeof($photos[1]); $i++) {
                         $images[] = array('link' => str_replace(array('\\x3a', '\\x2f', '\\x25', '\\x3fpsid\\x3d1'), array(':', '/', '%', ''), $photos[1][$i]), 'source' => str_replace(array('\\x3a', '\\x2f', '\\x25', '\\x3fpsid\\x3d1'), array(':', '/', '%', ''), $thumbs[1][$i]), 'title' => null, 'slimbox2' => $slimbox2attr);
                     }
                 }
                 break;
         }
     } else {
         safe_require('artefact', 'file');
         $artefactids = array();
         if (isset($configdata['select']) && $configdata['select'] == 1 && is_array($configdata['artefactids'])) {
             $artefactids = $configdata['artefactids'];
         } else {
             if (!empty($configdata['artefactid'])) {
                 // Get descendents of this folder.
                 $artefactids = artefact_get_descendants(array(intval($configdata['artefactid'])));
             }
         }
         // This can be either an image or profileicon. They both implement
         // render_self
         foreach ($artefactids as $artefactid) {
             $image = $instance->get_artefact_instance($artefactid);
             if ($image instanceof ArtefactTypeProfileIcon) {
                 $src = get_config('wwwroot') . 'thumb.php?type=profileiconbyid&id=' . $artefactid;
                 $description = $image->get('title');
             } else {
                 if ($image instanceof ArtefactTypeImage) {
                     $src = get_config('wwwroot') . 'artefact/file/download.php?file=' . $artefactid;
                     $src .= '&view=' . $instance->get('view');
                     $description = $image->get('description');
                 } else {
                     continue;
                 }
             }
             if ($slimbox2) {
                 $link = $src . '&maxwidth=' . get_config_plugin('blocktype', 'gallery', 'previewwidth');
             } else {
                 $link = get_config('wwwroot') . 'artefact/artefact.php?artefact=' . $artefactid . '&view=' . $instance->get('view');
             }
             // If the Thumbnails are Square or not...
             if ($style == 2) {
                 $src .= '&size=' . $width . 'x' . $width;
                 $height = $width;
             } else {
                 $src .= '&maxwidth=' . $width;
                 $imgwidth = $image->get('width');
                 $imgheight = $image->get('height');
                 $height = $imgwidth > $width ? intval($width / $imgwidth * $imgheight) : $imgheight;
             }
             $images[] = array('link' => $link, 'source' => $src, 'height' => $height, 'title' => $image->get('description'), 'slimbox2' => $slimbox2attr);
         }
     }
     $smarty = smarty_core();
     $smarty->assign('instanceid', $instance->get('id'));
     $smarty->assign('count', count($images));
     $smarty->assign('images', $images);
     $smarty->assign('showdescription', !empty($configdata['showdescription']) ? $configdata['showdescription'] : false);
     $smarty->assign('width', $width);
     $smarty->assign('captionwidth', get_config_plugin('blocktype', 'gallery', 'photoframe') ? $width + 8 : $width);
     if (isset($height)) {
         $smarty->assign('height', $height);
     }
     if (isset($needsapikey)) {
         $smarty->assign('needsapikey', $needsapikey);
     }
     $smarty->assign('frame', get_config_plugin('blocktype', 'gallery', 'photoframe'));
     $smarty->assign('copyright', $copyright);
     return $smarty->fetch('blocktype:gallery:' . $template . '.tpl');
 }
Пример #17
0
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
 *
 */
define('INTERNAL', 1);
define('PUBLIC', 1);
require '../../init.php';
safe_require('auth', 'browserid');
if (empty($_SESSION['browseridexpires']) || time() >= $_SESSION['browseridexpires']) {
    $assertion = param_variable('assertion', null);
    if (!$assertion) {
        throw new AuthInstanceException(get_string('missingassertion', 'auth.browserid'));
    }
    // Send the assertion to the verification service
    $request = array(CURLOPT_URL => PluginAuthBrowserid::BROWSERID_VERIFIER_URL, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => 'assertion=' . urlencode($assertion) . '&audience=' . get_audience());
    $response = mahara_http_request($request);
    if (empty($response->data)) {
        throw new AuthInstanceException(get_string('badverification', 'auth.browserid'));
    }
    $jsondata = json_decode($response->data);
    if (empty($jsondata)) {
        throw new AuthInstanceException(get_string('badverification', 'auth.browserid'));
    }
    if ($jsondata->status != 'okay') {
        throw new AuthInstanceException(get_string('badassertion', 'auth.browserid', htmlspecialchars($jsondata->reason)));
    }
    $SESSION->set('browseridexpires', $jsondata->expires / 1000);
    $SESSION->set('browseridemail', $jsondata->email);
}
// Not using $USER->get('sesskey') for this because when we printed the browserid setup stuff
// in auth/browserid/lib.php, $USER isn't set up yet.
Пример #18
0
function get_public_key($uri, $application = null)
{
    static $keyarray = array();
    if (isset($keyarray[$uri])) {
        return $keyarray[$uri];
    }
    $openssl = OpenSslRepo::singleton();
    if (empty($application)) {
        $application = 'moodle';
    }
    $xmlrpcserverurl = get_field('application', 'xmlrpcserverurl', 'name', $application);
    if (empty($xmlrpcserverurl)) {
        throw new XmlrpcClientException('Unknown application');
    }
    $wwwroot = dropslash(get_config('wwwroot'));
    $rq = xmlrpc_encode_request('system/keyswap', array($wwwroot, $openssl->certificate), array("encoding" => "utf-8"));
    $config = array(CURLOPT_URL => $uri . $xmlrpcserverurl, CURLOPT_POST => true, CURLOPT_USERAGENT => 'Moodle', CURLOPT_POSTFIELDS => $rq, CURLOPT_HTTPHEADER => array("Content-Type: text/xml charset=UTF-8", 'Expect: '));
    $result = mahara_http_request($config);
    if (!empty($result->errno)) {
        throw new XmlrpcClientException('Curl error: ' . $result->errno . ': ' . $result->error);
    }
    if (empty($result->data)) {
        throw new XmlrpcClientException('CURL connection failed');
    }
    $response_code = $result->info['http_code'];
    $response_code_prefix = substr($response_code, 0, 1);
    if ('2' != $response_code_prefix) {
        if ('4' == $response_code_prefix) {
            throw new XmlrpcClientException('Client error code: ', $response_code);
        } elseif ('5' == $response_code_prefix) {
            throw new XmlrpcClientException('An error occurred at the remote server. Code: ', $response_code);
        }
    }
    $res = xmlrpc_decode($result->data);
    // XMLRPC error messages are returned as an array
    // We are expecting a string
    if (!is_array($res)) {
        $keyarray[$uri] = $res;
        $credentials = array();
        if (strlen(trim($keyarray[$uri]))) {
            $credentials = openssl_x509_parse($keyarray[$uri]);
            $host = $credentials['subject']['CN'];
            if (strpos($uri, $host) !== false) {
                return $keyarray[$uri];
            }
            throw new XmlrpcClientException('The remote site sent us a key that is valid for ' . $host . ' instead of their hostname (' . $uri . ')', 500);
        }
    } else {
        throw new XmlrpcClientException($res['faultString'], $res['faultCode']);
    }
    return false;
}
 public function get_user_profile($type = 'basicprofile', $owner = null)
 {
     global $USER, $SESSION;
     $referring_page = basename($_SERVER['SCRIPT_NAME']) . '?' . $_SERVER['QUERY_STRING'];
     // TODO: check if that really works
     self::check_access_token($referring_page);
     $consumer = self::get_service_consumer();
     if (!$owner) {
         $owner = $USER->get('id');
     }
     if (!empty($consumer->key) && !empty($consumer->secret)) {
         $data = get_record('usr_account_preference', 'usr', $owner, 'field', 'linkedinprofile');
         if ($data) {
             $token = unserialize($data->value);
             switch ($type) {
                 case 'fullprofile':
                     //$fields = ':(first-name,last-name,formatted-name,headline,location:(name),picture-url,picture-urls::(original),public-profile-url,member-url-resources,num-connections,three-current-positions,three-past-positions,summary,specialties,positions,languages,educations,skills,group-memberships)';
                     // SEE: https://developer.linkedin.com/support/developer-program-transition#hero-par_longformtext_longform-text-content-par_resourceparagraph_5
                     $fields = ':(first-name,last-name,formatted-name,headline,location:(name),picture-url,picture-urls::(original),public-profile-url,num-connections,three-current-positions,three-past-positions,summary,specialties,positions,languages,educations,skills,group-memberships)';
                     break;
                 case 'contactinfo':
                     //$fields = ':(first-name,last-name,formatted-name,headline,location:(name),picture-url,picture-urls::(original),public-profile-url,member-url-resources,email-address,phone-numbers,main-address,primary-twitter-account)';
                     // SEE: https://developer.linkedin.com/support/developer-program-transition#hero-par_longformtext_longform-text-content-par_resourceparagraph_5
                     $fields = ':(first-name,last-name,formatted-name,headline,location:(name),picture-url,picture-urls::(original),public-profile-url,email-address)';
                     break;
                 case 'basicprofile':
                 default:
                     $fields = ':(first-name,last-name,formatted-name,headline,location:(name),picture-url,public-profile-url)';
                     break;
             }
             $url = $consumer->apiurl . 'people/~' . $fields;
             $method = 'POST';
             $port = $consumer->ssl ? '443' : '80';
             $params = array('oauth2_access_token' => $token['access_token']);
             $config = array(CURLOPT_URL => $url . '?' . oauth_http_build_query($params), CURLOPT_PORT => $port, CURLOPT_POST => false, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_CAINFO => dirname(__FILE__) . '/cert/cacert.crt');
             $result = mahara_http_request($config);
             if (isset($result->data) && !empty($result->data) && isset($result->info) && !empty($result->info) && $result->info['http_code'] == 200) {
                 $data = oauth_parse_xml($result->data);
                 return $data;
             } else {
                 $SESSION->add_error_msg(get_string('httprequesterror', 'blocktype.linkedinprofile') . ' ' . $result->info['http_code']);
             }
         } else {
             $SESSION->add_error_msg(get_string('notconnectedtolinkedin', 'blocktype.linkedinprofile'));
         }
     } else {
         throw new ConfigException('Can\'t find LinkedIn api key and/or secret key.');
     }
 }