/** * Generate url based on $name and $parameters * * @param string $name Name of the route to use. * @param array $parameters Parameters for the route * @param bool $absolute * @return string */ public function generate($name, $parameters = array(), $absolute = false) { asort($parameters); $key = $this->context->getHost() . '#' . $this->context->getBaseUrl() . $name . json_encode($parameters) . intval($absolute); if ($this->cache->hasKey($key)) { return $this->cache->get($key); } else { $url = parent::generate($name, $parameters, $absolute); $this->cache->set($key, $url, 3600); return $url; } }
/** * Discover the actual data and do some naive caching to ensure that the data * is not requested multiple times. * * If no valid discovery data is found the ownCloud defaults are returned. * * @param string $remote * @return array */ private function discover($remote) { // Check if something is in the cache if ($cacheData = $this->cache->get($remote)) { return json_decode($cacheData, true); } // Default response body $discoveredServices = ['webdav' => '/public.php/webdav', 'share' => '/ocs/v1.php/cloud/shares']; // Read the data from the response body try { $response = $this->client->get($remote . '/ocs-provider/'); if ($response->getStatusCode() === 200) { $decodedService = json_decode($response->getBody(), true); if (is_array($decodedService)) { $endpoints = ['webdav', 'share']; foreach ($endpoints as $endpoint) { if (isset($decodedService['services']['FEDERATED_SHARING']['endpoints'][$endpoint])) { $endpointUrl = (string) $decodedService['services']['FEDERATED_SHARING']['endpoints'][$endpoint]; if ($this->isSafeUrl($endpointUrl)) { $discoveredServices[$endpoint] = $endpointUrl; } } } } } } catch (ClientException $e) { // Don't throw any exception since exceptions are handled before } catch (ConnectException $e) { // Don't throw any exception since exceptions are handled before } // Write into cache $this->cache->set($remote, json_encode($discoveredServices)); return $discoveredServices; }
/** * @param ISubscription $subscription * @return string */ protected function getData(ISubscription $subscription) { $id = $subscription->getId(); $url = $subscription->getUrl(); $cacheId = implode('::', [$id, $url]); if ($this->cache->hasKey($cacheId)) { return $this->cache->get($cacheId); } else { $curl = curl_init(); $data = null; $this->prepareRequest($curl, $url); $this->getRequestData($curl, $data); $this->validateRequest($curl); $this->cache->set($cacheId, $data, 60 * 60 * 2); return $data; } }
/** * @param string $key * @param mixed $value */ public function writeToCache($key, $value) { if (is_null($this->cache)) { return; } $key = $this->getCacheKey($key); $value = base64_encode(json_encode($value)); $this->cache->set($key, $value, '2592000'); }
/** * Stores the results in the app config as well as cache * * @param string $scope * @param array $result */ private function storeResults($scope, array $result) { $resultArray = $this->getResults(); unset($resultArray[$scope]); if (!empty($result)) { $resultArray[$scope] = $result; } $this->config->setAppValue('core', self::CACHE_KEY, json_encode($resultArray)); $this->cache->set(self::CACHE_KEY, json_encode($resultArray)); }
/** * Save image data to cache and return the key * * @return string */ private function cachePhoto() { if ($this->cached) { return; } if (!$this->image instanceof Image) { $this->processImage(); } $this->normalizePhoto(); $data = $this->image->data(); $this->key = uniqid('photo-'); $this->cache->set($this->key, $data, 600); }
/** * Retrieve the facebook friends list * @var bool Ignore cache and force reload * @return Array Friends with FBID and Names */ public function getfriends($ignoreCache = false) { // try cache if defined if ($this->cache) { $cachedFriends = json_decode($this->cache->get($this->cacheKey), true); if (!empty($cachedFriends) && is_array($cachedFriends) && !$ignoreCache) { return $cachedFriends; } } if ($this->islogged()) { $friends = array(); $page = 0; $friendLinkFilter = "[href^=/friends/hovercard]"; $url = 'https://m.facebook.com/friends/center/friends/?ppk='; $getdata = $this->dorequest($url . $page); $html = str_get_html($getdata[1]); if (empty($html)) { return false; } $main = $html->find('div[id=friends_center_main]', 0); if (is_null($main)) { return false; } // 10 per page. Break when next page empty! while (count($main->find('a' . $friendLinkFilter)) != 0) { foreach ($main->find('a' . $friendLinkFilter) as $friend) { // FB ID $re = "/uid=([0-9]{1,20})/"; preg_match($re, $friend->href, $matches); // $friends[fbid]=name $friends[$matches[1]] = html_entity_decode($friend->innertext, ENT_QUOTES); } $page++; $getdata = $this->dorequest($url . $page); $html = str_get_html($getdata[1]); $main = $html->find('div[id=friends_center_main]', 0); } // Alphabetical order asort($friends); // To cache if defined if ($this->cache) { $this->cache->set($this->cacheKey, json_encode($friends)); \OCP\Util::writeLog('fbsync', count($friends) . " friends cached", \OCP\Util::INFO); } return $friends; } else { return false; } }
/** * @NoAdminRequired * * @param string $path * @return DataResponse */ public function postAvatar($path) { $userId = $this->userSession->getUser()->getUID(); $files = $this->request->getUploadedFile('files'); if (isset($path)) { $path = stripslashes($path); $view = new \OC\Files\View('/' . $userId . '/files'); $fileName = $view->getLocalFile($path); } elseif (!is_null($files)) { if ($files['error'][0] === 0 && is_uploaded_file($files['tmp_name'][0]) && !\OC\Files\Filesystem::isFileBlacklisted($files['tmp_name'][0])) { $this->cache->set('avatar_upload', file_get_contents($files['tmp_name'][0]), 7200); $view = new \OC\Files\View('/' . $userId . '/cache'); $fileName = $view->getLocalFile('avatar_upload'); unlink($files['tmp_name'][0]); } else { return new DataResponse(['data' => ['message' => $this->l->t('Invalid file provided')]], Http::STATUS_BAD_REQUEST); } } else { //Add imgfile return new DataResponse(['data' => ['message' => $this->l->t('No image or file provided')]], Http::STATUS_BAD_REQUEST); } try { $image = new \OC_Image(); $image->loadFromFile($fileName); $image->fixOrientation(); if ($image->valid()) { $mimeType = $image->mimeType(); if ($mimeType !== 'image/jpeg' && $mimeType !== 'image/png') { return new DataResponse(['data' => ['message' => $this->l->t('Unknown filetype')]]); } $this->cache->set('tmpAvatar', $image->data(), 7200); return new DataResponse(['data' => 'notsquare']); } else { return new DataResponse(['data' => ['message' => $this->l->t('Invalid image')]]); } } catch (\Exception $e) { return new DataResponse(['data' => ['message' => $e->getMessage()]]); } }
/** * Fetches an object from the API. * If the object is cached already or a * failed "doesn't exist" response was cached, * that one will be returned. * * @param string $path * @return \OpenCloud\OpenStack\ObjectStorage\Resource\DataObject|bool object * or false if the object did not exist */ private function fetchObject($path) { if ($this->objectCache->hasKey($path)) { // might be "false" if object did not exist from last check return $this->objectCache->get($path); } try { $object = $this->getContainer()->getPartialObject($path); $this->objectCache->set($path, $object); return $object; } catch (ClientErrorResponseException $e) { // this exception happens when the object does not exist, which // is expected in most cases $this->objectCache->set($path, false); return false; } catch (ClientErrorResponseException $e) { // Expected response is "404 Not Found", so only log if it isn't if ($e->getResponse()->getStatusCode() !== 404) { \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR); } return false; } }
/** * Updates the cache. */ public function save() { $lifetime = $this->_params['lifetime']; foreach ($this->_update as $mbox => $val) { $s =& $this->_slicemap[$mbox]; if (!empty($val['add'])) { if ($s['c'] <= $this->_params['slicesize']) { $val['slice'][] = $s['i']; $this->_loadSlice($mbox, $s['i']); } $val['slicemap'] = true; foreach (array_keys(array_flip($val['add'])) as $uid) { if ($s['c']++ > $this->_params['slicesize']) { $s['c'] = 0; $val['slice'][] = ++$s['i']; $this->_loadSlice($mbox, $s['i']); } $s['s'][$uid] = $s['i']; } } if (!empty($val['slice'])) { $d =& $this->_data[$mbox]; $val['slicemap'] = true; foreach (array_keys(array_flip($val['slice'])) as $slice) { $data = array(); foreach (array_keys($s['s'], $slice) as $uid) { $data[$uid] = is_array($d[$uid]) ? serialize($d[$uid]) : $d[$uid]; } $this->_cache->set($this->_getCid($mbox, $slice), serialize($data), $lifetime); } } if (!empty($val['slicemap'])) { $this->_cache->set($this->_getCid($mbox, 'slicemap'), serialize($s), $lifetime); } } $this->_update = array(); }
/** * Get all available apps in a category * * @param string $category * @param bool $includeUpdateInfo Should we check whether there is an update * in the app store? * @return array */ public function listApps($category = '', $includeUpdateInfo = true) { $category = $this->getCategory($category); $cacheName = 'listApps-' . $category . '-' . (int) $includeUpdateInfo; if (!is_null($this->cache->get($cacheName))) { $apps = $this->cache->get($cacheName); } else { switch ($category) { // installed apps case 0: $apps = $this->getInstalledApps($includeUpdateInfo); usort($apps, function ($a, $b) { $a = (string) $a['name']; $b = (string) $b['name']; if ($a === $b) { return 0; } return $a < $b ? -1 : 1; }); $version = \OCP\Util::getVersion(); foreach ($apps as $key => $app) { if (!array_key_exists('level', $app) && array_key_exists('ocsid', $app)) { $remoteAppEntry = $this->ocsClient->getApplication($app['ocsid'], $version); if (is_array($remoteAppEntry) && array_key_exists('level', $remoteAppEntry)) { $apps[$key]['level'] = $remoteAppEntry['level']; } } } break; // not-installed apps // not-installed apps case 1: $apps = \OC_App::listAllApps(true, $includeUpdateInfo, $this->ocsClient); $apps = array_filter($apps, function ($app) { return !$app['active']; }); $version = \OCP\Util::getVersion(); foreach ($apps as $key => $app) { if (!array_key_exists('level', $app) && array_key_exists('ocsid', $app)) { $remoteAppEntry = $this->ocsClient->getApplication($app['ocsid'], $version); if (is_array($remoteAppEntry) && array_key_exists('level', $remoteAppEntry)) { $apps[$key]['level'] = $remoteAppEntry['level']; } } } usort($apps, function ($a, $b) { $a = (string) $a['name']; $b = (string) $b['name']; if ($a === $b) { return 0; } return $a < $b ? -1 : 1; }); break; default: $filter = $this->config->getSystemValue('appstore.experimental.enabled', false) ? 'all' : 'approved'; $apps = \OC_App::getAppstoreApps($filter, $category, $this->ocsClient); if (!$apps) { $apps = array(); } else { // don't list installed apps $installedApps = $this->getInstalledApps(false); $installedApps = array_map(function ($app) { if (isset($app['ocsid'])) { return $app['ocsid']; } return $app['id']; }, $installedApps); $apps = array_filter($apps, function ($app) use($installedApps) { return !in_array($app['id'], $installedApps); }); // show tooltip if app is downloaded from remote server $inactiveApps = $this->getInactiveApps(); foreach ($apps as &$app) { $app['needsDownload'] = !in_array($app['id'], $inactiveApps); } } // sort by score usort($apps, function ($a, $b) { $a = (int) $a['score']; $b = (int) $b['score']; if ($a === $b) { return 0; } return $a > $b ? -1 : 1; }); break; } } // fix groups to be an array $dependencyAnalyzer = new DependencyAnalyzer(new Platform($this->config), $this->l10n); $apps = array_map(function ($app) use($dependencyAnalyzer) { // fix groups $groups = array(); if (is_string($app['groups'])) { $groups = json_decode($app['groups']); } $app['groups'] = $groups; $app['canUnInstall'] = !$app['active'] && $app['removable']; // fix licence vs license if (isset($app['license']) && !isset($app['licence'])) { $app['licence'] = $app['license']; } // analyse dependencies $missing = $dependencyAnalyzer->analyze($app); $app['canInstall'] = empty($missing); $app['missingDependencies'] = $missing; $app['missingMinOwnCloudVersion'] = !isset($app['dependencies']['owncloud']['@attributes']['min-version']); $app['missingMaxOwnCloudVersion'] = !isset($app['dependencies']['owncloud']['@attributes']['max-version']); return $app; }, $apps); $this->cache->set($cacheName, $apps, 300); return ['apps' => $apps, 'status' => 'success']; }
/** * Get all available apps in a category * * @param int $category * @return array */ public function listApps($category = 0) { if (!is_null($this->cache->get('listApps-' . $category))) { $apps = $this->cache->get('listApps-' . $category); } else { switch ($category) { // installed apps case 0: $apps = $this->getInstalledApps(); usort($apps, function ($a, $b) { $a = (string) $a['name']; $b = (string) $b['name']; if ($a === $b) { return 0; } return $a < $b ? -1 : 1; }); break; // not-installed apps // not-installed apps case 1: $apps = \OC_App::listAllApps(true); $apps = array_filter($apps, function ($app) { return !$app['active']; }); usort($apps, function ($a, $b) { $a = (string) $a['name']; $b = (string) $b['name']; if ($a === $b) { return 0; } return $a < $b ? -1 : 1; }); break; default: $filter = $this->config->getSystemValue('appstore.experimental.enabled', false) ? 'all' : 'approved'; $apps = \OC_App::getAppstoreApps($filter, $category); if (!$apps) { $apps = array(); } else { // don't list installed apps $installedApps = $this->getInstalledApps(); $installedApps = array_map(function ($app) { if (isset($app['ocsid'])) { return $app['ocsid']; } return $app['id']; }, $installedApps); $apps = array_filter($apps, function ($app) use($installedApps) { return !in_array($app['id'], $installedApps); }); } // sort by score usort($apps, function ($a, $b) { $a = (int) $a['score']; $b = (int) $b['score']; if ($a === $b) { return 0; } return $a > $b ? -1 : 1; }); break; } } // fix groups to be an array $dependencyAnalyzer = new DependencyAnalyzer(new Platform($this->config), $this->l10n); $apps = array_map(function ($app) use($dependencyAnalyzer) { // fix groups $groups = array(); if (is_string($app['groups'])) { $groups = json_decode($app['groups']); } $app['groups'] = $groups; $app['canUnInstall'] = !$app['active'] && $app['removable']; // fix licence vs license if (isset($app['license']) && !isset($app['licence'])) { $app['licence'] = $app['license']; } // analyse dependencies $missing = $dependencyAnalyzer->analyze($app); $app['canInstall'] = empty($missing); $app['missingDependencies'] = $missing; return $app; }, $apps); $this->cache->set('listApps-' . $category, $apps, 300); return ['apps' => $apps, 'status' => 'success']; }
/** * Get all available categories * @param int $category * @return array */ public function listApps($category = 0) { if (!is_null($this->cache->get('listApps-' . $category))) { $apps = $this->cache->get('listApps-' . $category); } else { switch ($category) { // installed apps case 0: $apps = \OC_App::listAllApps(true); $apps = array_filter($apps, function ($app) { return $app['active']; }); break; // not-installed apps // not-installed apps case 1: $apps = \OC_App::listAllApps(true); $apps = array_filter($apps, function ($app) { return !$app['active']; }); break; default: if ($category === 2) { $apps = \OC_App::getAppstoreApps('approved'); $apps = array_filter($apps, function ($app) { return isset($app['internalclass']) && $app['internalclass'] === 'recommendedapp'; }); } else { $apps = \OC_App::getAppstoreApps('approved', $category); } if (!$apps) { $apps = array(); } usort($apps, function ($a, $b) { $a = (int) $a['score']; $b = (int) $b['score']; if ($a === $b) { return 0; } return $a > $b ? -1 : 1; }); break; } } // fix groups to be an array $dependencyAnalyzer = new DependencyAnalyzer(new Platform($this->config), $this->l10n); $apps = array_map(function ($app) use($dependencyAnalyzer) { // fix groups $groups = array(); if (is_string($app['groups'])) { $groups = json_decode($app['groups']); } $app['groups'] = $groups; $app['canUnInstall'] = !$app['active'] && $app['removable']; // fix licence vs license if (isset($app['license']) && !isset($app['licence'])) { $app['licence'] = $app['license']; } // analyse dependencies $missing = $dependencyAnalyzer->analyze($app); $app['canInstall'] = empty($missing); $app['missingDependencies'] = $missing; return $app; }, $apps); $this->cache->set('listApps-' . $category, $apps, 300); return ['apps' => $apps, 'status' => 'success']; }