/** * Authorize API with credentials * * @param \Google_Auth_AssertionCredentials $cred */ public function authenticate(\Google_Auth_AssertionCredentials $cred) { $this->client = $client = new \Google_Client(); $sitename = $this->app['config']->get('general/sitename'); // @todo url::slugify() will be deprecated in 2.1 $this->client->setApplicationName(\utilphp\util::slugify($sitename)); if (isset($_SESSION['token_gapps'])) { $client->setAccessToken($_SESSION['token_gapps']); } $client->setClientId($this->config['ClientID']); $client->setAssertionCredentials($cred); if ($client->getAuth()->isAccessTokenExpired()) { $client->getAuth()->refreshTokenWithAssertion($cred); } $_SESSION[$this->getServiceSessionTk($cred->scopes)] = $client->getAccessToken(); return $this->client; }
private function loadLinks() { if ($this->linksLoaded) { return; } // TODO: in new Bolt version use getContenttypeTablename instead of getTablename. $tableStructures = $this->app['storage']->getTablename('structures'); $structures = $this->app['db']->fetchAll("SELECT id FROM {$tableStructures} WHERE status = 'published'"); $availableStructures = util::array_pluck($structures, 'id'); $contenttypes = $this->app['config']->get('contenttypes'); foreach ($contenttypes as $contenttype) { if (isset($contenttype['fields']['structure_parent'])) { $contenttypeslug = $contenttype['slug']; $tablename = $this->app['storage']->getTablename($contenttypeslug); $stmt = $this->app['db']->prepare("SELECT id, structure_parent FROM {$tablename}"); $res = $stmt->execute(); while ($row = $stmt->fetch()) { $id = intval($row['id']); $parent = intval($row['structure_parent']); // The $parent is only relevant if it exists and is published. if (in_array($parent, $availableStructures)) { $this->treeParents[$contenttypeslug][$id] = $parent; $this->treeChildren[$parent][] = "{$contenttypeslug}/{$id}"; } } } } $this->linksLoaded = true; }
public function addInitializerConfig($args) { if ($args) { $this->repository = util::array_get($args['repository'], $this->repository); $this->id = util::array_get($args['id'], $this->id); $this->value = util::array_get($args['value'], $this->value); } }
public function handle($path) { $files = []; $folders = []; $list = $this->filesystem->listContents($path); $ignored = ['.', '..', '.DS_Store', '.gitignore', '.htaccess']; foreach ($list as $entry) { if (in_array($entry['basename'], $ignored)) { continue; } if (!$this->filesystem->authorized($entry['path'])) { continue; } if ($entry['type'] === 'file') { try { $url = $this->filesystem->url($entry['path']); } catch (\Exception $e) { $url = $entry['path']; } // Ugh, for some reason the foldername for the theme is included twice. Why? // For now we 'fix' this with an ugly hack, replacing it. :-/ // TODO: dig into Filesystem and figure out why this happens. $pathsegments = explode('/', $entry['path']); if (!empty($pathsegments[0])) { $url = str_replace('/' . $pathsegments[0] . '/' . $pathsegments[0] . '/', '/' . $pathsegments[0] . '/', $url); } $files[$entry['path']] = ['path' => $entry['dirname'], 'filename' => $entry['basename'], 'newpath' => $entry['path'], 'relativepath' => $entry['path'], 'writable' => true, 'readable' => false, 'type' => isset($entry['extension']) ? $entry['extension'] : '', 'filesize' => Lib::formatFilesize($entry['size']), 'modified' => date("Y/m/d H:i:s", $entry['timestamp']), 'permissions' => 'public', 'url' => $url]; /* **** Extra checks for files that can be resolved via PHP urlopen functions **** */ try { $files[$entry['path']]['permissions'] = $this->filesystem->getVisibility($entry['path']); } catch (\Exception $e) { // Computer says "No!" } $fullfilename = $this->filesystem->getAdapter()->applyPathPrefix($entry['path']); if (is_readable($fullfilename)) { $files[$entry['path']]['readable'] = true; if (!empty($entry['extension']) && in_array($entry['extension'], ['gif', 'jpg', 'png', 'jpeg'])) { $size = getimagesize($fullfilename); $files[$entry['path']]['imagesize'] = sprintf("%s × %s", $size[0], $size[1]); } $files[$entry['path']]['permissions'] = util::full_permissions($fullfilename); } } if ($entry['type'] == 'dir') { $folders[$entry['path']] = ['path' => $entry['dirname'], 'foldername' => $entry['basename'], 'newpath' => $entry['path'], 'modified' => date("Y/m/d H:i:s", $entry['timestamp']), 'writable' => true]; $fullfilename = $this->filesystem->getAdapter()->applyPathPrefix($entry['path']); /* **** Extra checks for files that can be resolved via PHP urlopen functions **** */ if (is_readable($fullfilename)) { if (!is_writable($fullfilename)) { $folders[$entry['path']]['writable'] = false; } } } } ksort($files); ksort($folders); return [$files, $folders]; }
public function __construct($id, $args, AutoTablesGlobalConfiguration $globalConf) { $this->id = $id; $this->serviceId = util::array_get($args['service'], null); $this->repositoryId = util::array_get($args['repository'], null); $this->transScope = util::array_get($args['trans_scope'], $globalConf->getTransScope()); $this->dataTablesOptions = util::array_get($args['datatables_options'], $globalConf->getDataTablesOptions()); $this->views = util::array_get($args['views'], ''); $this->frontendFramework = $globalConf->getFrontendFramework(); $this->columns = util::array_get($args['columns'], array()); $this->updateRoute = util::array_get($args['updateRoute'], 'twentysteps_auto_tables_update'); $this->addRoute = util::array_get($args['addRoute'], 'twentysteps_auto_tables_add'); $this->deleteRoute = util::array_get($args['deleteRoute'], 'twentysteps_auto_tables_remove'); }
public function menu($identifier = null, $resolved = true) { $menus = $this->app['config']->get('menu'); if (!empty($identifier) && isset($menus[$identifier])) { $name = strtolower($identifier); $menu = $menus[$identifier]; } else { $name = strtolower(\utilphp\util::array_first_key($menus)); $menu = \utilphp\util::array_first($menus); } if (!is_array($menu)) { $menu = array(); } if (!$resolved) { return new Menu($name, $menu); } return new Menu($name, $this->resolve($menu), true); }
function dump($varVal, $isExit = FALSE, $linestack = 0) { if (config('app')[Constants::DEBUG]) { $debuginfo = debug_backtrace(); $debuginfo = $debuginfo[$linestack]; echo $debuginfo["file"] . ":" . $debuginfo['line'] . '<br>'; if (self::RICH_HTML) { util::var_dump($varVal, false, -1); } else { ob_start(); var_dump($varVal); $varVal = ob_get_clean(); $varVal = preg_replace("/\\]\\=\\>\n(\\s+)/m", "] => ", $varVal); echo '<pre>' . $varVal . '</pre>'; } $isExit && exit; } }
/** * @Route("/user/list", name="chat.user.list") */ public function userListAction() { $run = function () { $em = $this->get('doctrine.orm.entity_manager'); $userClass = $this->container->get('fos_user.user_manager')->getClass(); $query = $em->getRepository($userClass)->createQueryBuilder('u')->select('u.id, u.username, u.email')->andWhere('u.enabled = true')->andWhere('u.username NOT IN (:excluded)')->setParameters(['excluded' => ['system', $this->getUser()->getUsername()]])->getQuery(); $data = $query->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY); $ids = $this->getActiveUsersIds(); $data = array_map(function ($e) use($ids) { $e['online'] = in_array($e['id'], $ids); $e['image'] = util::get_gravatar($e['email']); return $e; }, $data); usort($data, function ($a, $b) { return $a['online'] < $b['online']; }); return $this->getFrame()->getDataFrame('Users', $data); }; return $this->handleJsonAction($run); }
/** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('services.yml'); $tables = util::array_get($config['tables']); if ($tables) { foreach ($tables as $tableDef) { $id = util::array_get($tableDef['id']); Ensure::isNotEmpty($id, "Missing [id] option in twentysteps_auto_tables table definition"); $json = util::array_get($tableDef['dataTablesOptions']) ?: '{}'; Ensure::isTrue($this->isValidJson($json), 'Encountered illegal JSON for twentysteps_auto_tables table with id [%s] in config: %s', $id, $json); $container->setParameter('twentysteps_auto_tables.config.' . $id, $tableDef); } } $defaultOpts = util::array_get($config['default_datatables_options']) ?: '{}'; Ensure::isTrue($this->isValidJson($defaultOpts), 'Encountered illegal JSON in config: %s', $defaultOpts); $container->setParameter('twentysteps_auto_tables.default_datatables_options', $defaultOpts); $container->setParameter('twentysteps_auto_tables.config', $config); }
/** * The taxonomy listing page controller. * * @param Request $request The Symfony Request * @param string $taxonomytype The taxonomy type slug * @param string $slug The taxonomy slug * * @return BoltResponse|false */ public function taxonomy(Request $request, $taxonomytype, $slug) { $taxonomy = $this->storage()->getTaxonomyType($taxonomytype); // No taxonomytype, no possible content. if (empty($taxonomy)) { return false; } else { $taxonomyslug = $taxonomy['slug']; } // First, get some content $context = $taxonomy['singular_slug'] . '_' . $slug; $pagerid = Pager::makeParameterId($context); /* @var $query \Symfony\Component\HttpFoundation\ParameterBag */ $query = $request->query; $page = $query->get($pagerid, $query->get('page', 1)); // Theme value takes precedence over default config @see https://github.com/bolt/bolt/issues/3951 $amount = $this->getOption('theme/listing_records', false) ?: $this->getOption('general/listing_records'); $order = $this->getOption('theme/listing_sort', false) ?: $this->getOption('general/listing_sort'); $content = $this->storage()->getContentByTaxonomy($taxonomytype, $slug, ['limit' => $amount, 'order' => $order, 'page' => $page]); if (!$this->isTaxonomyValid($content, $slug, $taxonomy)) { $this->abort(Response::HTTP_NOT_FOUND, "No slug '{$slug}' in taxonomy '{$taxonomyslug}'"); return; } $template = $this->templateChooser()->taxonomy($taxonomyslug); $name = $slug; // Look in taxonomies in 'content', to get a display value for '$slug', perhaps. foreach ($content as $record) { $flat = util::array_flatten($record->taxonomy); $key = $this->app['resources']->getUrl('root') . $taxonomy['slug'] . '/' . $slug; if (isset($flat[$key])) { $name = $flat[$key]; } $key = $this->app['resources']->getUrl('root') . $taxonomy['singular_slug'] . '/' . $slug; if (isset($flat[$key])) { $name = $flat[$key]; } } $globals = ['records' => $content, 'slug' => $name, 'taxonomy' => $this->getOption('taxonomy/' . $taxonomyslug), 'taxonomytype' => $taxonomyslug]; return $this->render($template, [], $globals); }
/** * Return a list with the current stacked items. Add some relevant info to each item, * and also check if the item is present and readable. * * @param int $count * @param string $typefilter * @return array */ public function listitems($count = 100, $typefilter = "") { // Make sure typefilter is an array, if passed something like "image, document" if (!empty($typefilter)) { $typefilter = array_map("trim", explode(",", $typefilter)); } // Our basepaths for all files that can be on the stack: 'files' and 'theme'. $filespath = $this->app['paths']['filespath']; $themepath = $this->app['paths']['themebasepath']; $items = $this->items; $list = array(); foreach ($items as $item) { $extension = strtolower(getExtension($item)); if (in_array($extension, $this->imagetypes)) { $type = "image"; } elseif (in_array($extension, $this->documenttypes)) { $type = "document"; } else { $type = "other"; } // Skip this one, if it doesn't match the type. if (!empty($typefilter) && !in_array($type, $typefilter)) { continue; } // Figure out the full path, based on the two possible locations. $fullpath = ''; if (is_readable(str_replace("files/files/", "files/", $filespath . "/" . $item))) { $fullpath = str_replace("files/files/", "files/", $filespath . "/" . $item); } elseif (is_readable($themepath . "/" . $item)) { $fullpath = $themepath . "/" . $item; } // No dice! skip this one. if (empty($fullpath)) { continue; } $thisitem = array('basename' => basename($item), 'extension' => $extension, 'filepath' => str_replace("files/", "", $item), 'type' => $type, 'writable' => is_writable($fullpath), 'readable' => is_readable($fullpath), 'filesize' => formatFilesize(filesize($fullpath)), 'modified' => date("Y/m/d H:i:s", filemtime($fullpath)), 'permissions' => \utilphp\util::full_permissions($fullpath)); $thisitem['info'] = sprintf("%s: <code>%s</code><br>%s: %s<br>%s: %s<br>%s: <code>%s</code>", __('Path'), $thisitem['filepath'], __('Filesize'), $thisitem['filesize'], __('Modified'), $thisitem['modified'], __('Permissions'), $thisitem['permissions']); if ($type == "image") { $size = getimagesize($fullpath); $thisitem['imagesize'] = sprintf("%s × %s", $size[0], $size[1]); $thisitem['info'] .= sprintf("<br>%s: %s × %s px", __("Size"), $size[0], $size[1]); } //add it to our list.. $list[] = $thisitem; } $list = array_slice($list, 0, $count); return $list; }
public function getRepeaters($content) { $ids = util::array_pluck($content, 'id'); if (empty($ids)) { return; } // Get the contenttype from first $content $contenttypeslug = $content[util::array_first_key($content)]->contenttype['slug']; $contenttype = $this->getContentType($contenttypeslug); $repo = $this->app['storage']->getRepository('Bolt\\Storage\\Entity\\FieldValue'); foreach ($ids as $id) { foreach ($contenttype['fields'] as $fieldkey => $field) { if ($field['type'] == 'repeater') { $collection = new RepeatingFieldCollection($this->app['storage'], $field); $existingFields = $repo->getExistingFields($id, $contenttypeslug, $fieldkey) ?: []; foreach ($existingFields as $group => $ids) { $collection->addFromReferences($ids, $group); } $content[$id]->setValue($fieldkey, $collection); } } } }
/** * Return a list with the current stacked items. Add some relevant info to each item, * and also check if the item is present and readable. * * @param integer $count * @param string $typefilter * * @return array */ public function listitems($count = 100, $typefilter = '') { $this->initialize(); // Make sure typefilter is an array, if passed something like "image, document" if (!empty($typefilter)) { $typefilter = array_map('trim', explode(',', $typefilter)); } // Our basepaths for all files that can be on the stack: 'files' and 'theme'. $filespath = $this->app['resources']->getPath('filespath'); $themepath = $this->app['resources']->getPath('themebasepath'); $items = $this->items; $list = []; foreach ($items as $item) { $extension = strtolower(Lib::getExtension($item)); if (in_array($extension, $this->imageTypes)) { $type = 'image'; } elseif (in_array($extension, $this->documentTypes)) { $type = 'document'; } else { $type = 'other'; } // Skip this one, if it doesn't match the type. if (!empty($typefilter) && !in_array($type, $typefilter)) { continue; } // Figure out the full path, based on the two possible locations. $fullpath = ''; if (is_readable(str_replace('files/files/', 'files/', $filespath . '/' . $item))) { $fullpath = str_replace('files/files/', 'files/', $filespath . '/' . $item); } elseif (is_readable($themepath . '/' . $item)) { $fullpath = $themepath . '/' . $item; } // No dice! skip this one. if (empty($fullpath)) { continue; } $thisitem = ['basename' => basename($item), 'extension' => $extension, 'filepath' => str_replace('files/', '', $item), 'type' => $type, 'writable' => is_writable($fullpath), 'readable' => is_readable($fullpath), 'filesize' => Lib::formatFilesize(filesize($fullpath)), 'modified' => date('Y/m/d H:i:s', filemtime($fullpath)), 'permissions' => util::full_permissions($fullpath)]; $thisitem['info'] = sprintf('%s: <code>%s</code><br>%s: %s<br>%s: %s<br>%s: <code>%s</code>', Trans::__('Path'), $thisitem['filepath'], Trans::__('Filesize'), $thisitem['filesize'], Trans::__('Modified'), $thisitem['modified'], Trans::__('Permissions'), $thisitem['permissions']); if ($type == 'image') { $size = getimagesize($fullpath); $thisitem['imagesize'] = sprintf('%s × %s', $size[0], $size[1]); $thisitem['info'] .= sprintf('<br>%s: %s × %s px', Trans::__('Size'), $size[0], $size[1]); } //add it to our list. $list[] = $thisitem; } $list = array_slice($list, 0, $count); return $list; }
// $output = json_decode ( gzuncompress ( base64_decode ( $data ) ) ); $returnmessages = \hellaEngine\Supports\Common\Util\CommonUtilMessage::decodeMessage($output); // _dump ( $returnmessages ); foreach ($returnmessages as $value) { // _dump ( $value ); $command = \hellaEngine\Supports\Common\Util\CommonUtilMessage::Message_getCommand($value); // _dump ( $command ); util::var_dump($command, false, -1); } // _dump ( $_SERVER ); echo "<<<<<<<<<<<<<<<<<<<<<< function return <<<<<<<<<<<<<<<<<<<<<<<br>"; // echo (">>>>return messagelenSRC:" . strlen ( $uncompressString ) . "<br>"); echo ">>>>return messagelenQQ:" . strlen($output) . "<br>"; echo ">>>>return message:" . $output . "<br>"; if (C(configure_constants::DEBUG_DB)) { echo ">>>>>>>>>>>>>>>>>>>>>>>dbinfo>>>>>>>>>>>>>>>>>>>>>>><br>"; if (isset($GLOBALS[configure_constants::DEBUG_DB_DIRTY_KEY])) { $debugdbarray = $GLOBALS[configure_constants::DEBUG_DB_DIRTY_KEY]; if (!is_null($debugdbarray)) { // _dump ( $debugdbarray ); util::var_dump($debugdbarray, false, -1); } } } } else { echo $_GET['backurl']; $url = "Location:" . $_GET['backurl']; header($url); exit; // echo "here"; }
<b>Invalid format:</b><br> <ul> <?php foreach ($d->getDecodingExceptions() as $e) { echo '<li>' . $e->getMessage(); echo ', on chunk "' . $e->getChunk() . '"</li>'; } $d->resetDecodingExceptions(); ?> </ul> </div> <?php } ?> <div><?php $raw_dump = util::var_dump($d, true, 2); $to_delete = array('private:MetarDecoder\\Entity\\DecodedMetar:', 'private:MetarDecoder\\Entity\\', 'MetarDecoder\\Entity\\', 'Value:'); $clean_dump = str_replace($to_delete, '', $raw_dump); echo $clean_dump; ?> </div> </div> <?php } else { ?> </div> <br> <div class="alert alert-info"> Need inspiration ? What about: <ul> <li><a href="./index.php?metar=CYFB+271515Z+32017KT+3SM+DRSN+BKN040+M29%2FM34+A2957+RMK+SC7+SLP019">CYFB 271515Z 32017KT 3SM DRSN BKN040 M29/M34 A2957 RMK SC7 SLP019</a></li>
public static function taxonomy(Silex\Application $app, $taxonomytype, $slug) { // First, get some content $page = $app['request']->query->get('page', 1); $amount = $app['config']->get('general/listing_records'); $order = $app['config']->get('general/listing_sort'); $content = $app['storage']->getContentByTaxonomy($taxonomytype, $slug, array('limit' => $amount, 'order' => $order, 'page' => $page)); $taxonomytype = $app['storage']->getTaxonomyType($taxonomytype); // No taxonomytype, no possible content.. if (empty($taxonomytype)) { return false; } else { $taxonomyslug = $taxonomytype['slug']; } if (!$content) { $app->abort(404, "Content for '{$taxonomyslug}/{$slug}' not found."); } $chosen = 'taxonomy'; // Set the template based on the (optional) setting in taxonomy.yml, or fall back to default listing template if ($app['config']->get('taxonomy/' . $taxonomyslug . '/listing_template')) { $template = $app['config']->get('taxonomy/' . $taxonomyslug . '/listing_template'); } else { $template = $app['config']->get('general/listing_template'); } $app['log']->setValue('templatechosen', $app['config']->get('general/theme') . "/{$template} ({$chosen})"); // Fallback: If file is not OK, show an error page $filename = $app['paths']['themepath'] . "/" . $template; if (!file_exists($filename) || !is_readable($filename)) { $error = sprintf("No template for '%s'-listing defined. Tried to use '%s/%s'.", $taxonomyslug, basename($app['config']->get('general/theme')), $template); $app['log']->setValue('templateerror', $error); $app->abort(404, $error); } $name = $slug; // Look in taxonomies in 'content', to get a display value for '$slug', perhaps. foreach ($content as $record) { $flat = \utilphp\util::array_flatten($record->taxonomy); $key = $app['paths']['root'] . $taxonomytype['slug'] . '/' . $slug; if (isset($flat[$key])) { $name = $flat[$key]; } $key = $app['paths']['root'] . $taxonomytype['singular_slug'] . '/' . $slug; if (isset($flat[$key])) { $name = $flat[$key]; } } $app['twig']->addGlobal('records', $content); $app['twig']->addGlobal('slug', $name); $app['twig']->addGlobal('taxonomy', $app['config']->get('taxonomy/' . $taxonomyslug)); $app['twig']->addGlobal('taxonomytype', $taxonomyslug); return $app['render']->render($template); }
public function test_directory_contents() { $dirname = dirname(__FILE__); $dir = $dirname . DIRECTORY_SEPARATOR . 'dir1'; mkdir($dir); $file1 = $dir . DIRECTORY_SEPARATOR . 'file1'; touch($file1); $this->assertEquals(array($file1), util::directory_contents($dir)); util::rmdir($dir); }
/** * @author Xiao-Hu Tai * @param \Bolt\Content $record The record to search similar content for. * @param array $options Options for custom queries. * * @return array Returns an array with the elements sorted by similarity. */ function relatedContentByTags($record, $options = array()) { $app = $this->app; $limit = isset($options['limit']) ? $options['limit'] : $this->config['limit']; $tablePrefix = $app['config']->get('general/database/prefix', 'bolt_'); $taxonomyTable = sprintf('%staxonomy', $tablePrefix); $contenttypes = $app['config']->get('contenttypes'); $filter = isset($options['contenttypes']) ? $options['contenttypes'] : false; // if set, filter contenttypes if ($filter) { $filterContenttypes = array(); foreach ($filter as $contenttypeName) { if (isset($contenttypes[$contenttypeName])) { $filterContenttypes[$contenttypeName] = $contenttypes[$contenttypeName]; } } if ($filterContenttypes) { $contenttypes = $filterContenttypes; } } // Get all taxonomies that behave like tags and their values from $record. $tagsValues = array(); $tagsTaxonomies = array(); // If no taxonomies exist, then no matching items exist if (!isset($record->contenttype['taxonomy'])) { return array(); } foreach ($record->contenttype['taxonomy'] as $key) { if ($app['config']->get('taxonomy/' . $key . '/behaves_like') == 'tags') { // only useful if values exist, otherwise just skip this taxonomy if ($record->taxonomy[$key]) { $tagsValues[$key] = array_values($record->taxonomy[$key]); $tagsTaxonomies[] = $key; } } } // Make the basic WHERE query for all behaves-like-tags values in $record. $queryWhere = array(); foreach ($tagsValues as $tagName => $values) { $subqueryWhere = array(); foreach ($values as $word) { $subqueryWhere[] = sprintf('%s.slug = "%s"', $taxonomyTable, $word); } $temp = sprintf('%s.taxonomytype = "%s"', $taxonomyTable, $tagName); $temp .= sprintf(' AND (%s)', implode(' OR ', $subqueryWhere)); $queryWhere[] = $temp; } $queryWhere = implode(' OR ', $queryWhere); // Get all contenttypes (database tables) that have a similar behaves-like-tags taxonomies like $record $tables = array(); foreach ($contenttypes as $key => $contenttype) { foreach ($contenttype['taxonomy'] as $taxonomyKey) { if (in_array($taxonomyKey, $tagsTaxonomies)) { $tables[] = $contenttype['slug']; break; } } } // Fetch results for every proper contenttype $results = array(); foreach ($tables as $name) { $table = sprintf('%s%s', $tablePrefix, $name); $querySelect = ''; $querySelect .= sprintf('SELECT %s.id FROM %s', $table, $table); $querySelect .= sprintf(' LEFT JOIN %s', $taxonomyTable); $querySelect .= sprintf(' ON %s.id = %s.content_id', $table, $taxonomyTable); $querySelect .= sprintf(' WHERE %s.status = "published"', $table); if ($name == $record->contenttype['slug']) { $querySelect .= sprintf('AND %s.id != ' . $record->id, $table); } $querySelect .= sprintf(' AND %s.contenttype = "%s"', $taxonomyTable, $name); $querySelect .= sprintf(' AND (%s)', $queryWhere); $queryResults = $app['db']->fetchAll($querySelect); if (!empty($queryResults)) { $ids = implode(' || ', \utilphp\util::array_pluck($queryResults, 'id')); $contents = $app['storage']->getContent($name, array('id' => $ids, 'returnsingle' => false)); $results = array_merge($results, $contents); } } // Add similarities by tags and difference in publication dates. foreach ($results as $result) { $similarity = $this->calculateTaxonomySimilarity($record, $result, $tagsTaxonomies, $tagsValues, $options); $diff = $this->calculatePublicationDiff($record, $result); $result->similarity = $similarity; $result->diff = $diff; } // Sort results usort($results, array($this, 'compareSimilarity')); // Limit results $results = array_slice($results, 0, $limit); return $results; }
/** * The taxonomy listing page controller. * * @param \Silex\Application $app The application/container * @param string $taxonomytype The taxonomy type slug * @param string $slug The taxonomy slug * * @return \Twig_Markup */ public function taxonomy(Silex\Application $app, $taxonomytype, $slug) { $taxonomy = $app['storage']->getTaxonomyType($taxonomytype); // No taxonomytype, no possible content. if (empty($taxonomy)) { return false; } else { $taxonomyslug = $taxonomy['slug']; } // First, get some content $context = $taxonomy['singular_slug'] . '_' . $slug; $pagerid = Pager::makeParameterId($context); /* @var $query \Symfony\Component\HttpFoundation\ParameterBag */ $query = $app['request']->query; $page = $query->get($pagerid, $query->get('page', 1)); $amount = $app['config']->get('general/listing_records'); $order = $app['config']->get('general/listing_sort'); $content = $app['storage']->getContentByTaxonomy($taxonomytype, $slug, array('limit' => $amount, 'order' => $order, 'page' => $page)); // Handle case where listing records has been override for specific taxonomy if (array_key_exists('listing_records', $taxonomy) && is_int($taxonomy['listing_records'])) { $amount = $taxonomy['listing_records']; } // See https://github.com/bolt/bolt/pull/2310 if ($taxonomy['behaves_like'] === 'tags' && !$content || in_array($taxonomy['behaves_like'], array('categories', 'grouping')) && !in_array($slug, isset($taxonomy['options']) ? array_keys($taxonomy['options']) : array())) { return $app->abort(Response::HTTP_NOT_FOUND, "No slug '{$slug}' in taxonomy '{$taxonomyslug}'"); } $template = $app['templatechooser']->taxonomy($taxonomyslug); $name = $slug; // Look in taxonomies in 'content', to get a display value for '$slug', perhaps. foreach ($content as $record) { $flat = util::array_flatten($record->taxonomy); $key = $app['paths']['root'] . $taxonomy['slug'] . '/' . $slug; if (isset($flat[$key])) { $name = $flat[$key]; } $key = $app['paths']['root'] . $taxonomy['singular_slug'] . '/' . $slug; if (isset($flat[$key])) { $name = $flat[$key]; } } $app['twig']->addGlobal('records', $content); $app['twig']->addGlobal('slug', $name); $app['twig']->addGlobal('taxonomy', $app['config']->get('taxonomy/' . $taxonomyslug)); $app['twig']->addGlobal('taxonomytype', $taxonomyslug); return $this->render($app, $template, $taxonomyslug); }
private function getColumnDescriptor($entity, $columnDescriptorId, AutoTablesConfiguration $config) { $columnDescriptor = util::array_get($this->columnDescriptorMap[$columnDescriptorId]); if (!$columnDescriptor) { $this->initDescriptors(new \ReflectionClass($entity), $config); $columnDescriptor = util::array_get($this->columnDescriptorMap[$columnDescriptorId]); Ensure::isNotNull($columnDescriptor, 'Failed to load column [%s] for entity of type [%s]', $columnDescriptorId, get_class($entity)); } return $columnDescriptor; }
public function __construct($args) { $this->transScope = util::array_get($args['trans_scope'], 'messages'); $this->dataTablesOptions = util::array_get($args['datatables_options'], '{}'); $this->frontendFramework = FrontendFramework::fromString(util::array_get($args['frontend_framework'], FrontendFramework::toString(FrontendFramework::JQUERY_UI))); }
/** * generate an url-friendly string from Node::name * @param Node $node * @return string */ public function slugify(Node $node) { return util::slugify($node->getName()); }
/** * Get the relations for one or more units of content, return the array with the taxonomy attached. * * @param array $content * * @return array $content */ protected function getRelation($content) { $tablename = $this->getTablename("relations"); $ids = util::array_pluck($content, 'id'); if (empty($ids)) { return; } // Get the contenttype from first $content $contenttype = $content[util::array_first_key($content)]->contenttype['slug']; $query = sprintf("SELECT * FROM %s WHERE from_contenttype=? AND from_id IN (?) ORDER BY id", $tablename); $params = array($contenttype, $ids); $paramTypes = array(\PDO::PARAM_STR, DoctrineConn::PARAM_INT_ARRAY); $rows = $this->app['db']->executeQuery($query, $params, $paramTypes)->fetchAll(); foreach ($rows as $row) { $content[$row['from_id']]->setRelation($row['to_contenttype'], $row['to_id']); } // switch it, flip it and reverse it. wop wop wop. $query = sprintf("SELECT * FROM %s WHERE to_contenttype=? AND to_id IN (?) ORDER BY id", $tablename); $params = array($contenttype, $ids); $paramTypes = array(\PDO::PARAM_STR, DoctrineConn::PARAM_INT_ARRAY); $rows = $this->app['db']->executeQuery($query, $params, $paramTypes)->fetchAll(); foreach ($rows as $row) { $content[$row['to_id']]->setRelation($row['from_contenttype'], $row['from_id']); } }
public function addAutoTablesConfig(AutoTablesConfiguration $config, $selector) { $columnOverwrite = util::array_get($config->getColumns()[$selector]); if ($columnOverwrite) { $this->readOnly = util::array_get($columnOverwrite['readOnly'], $this->readOnly); $this->name = util::array_get($columnOverwrite['name'], $this->name); $this->type = util::array_get($columnOverwrite['type'], $this->type); $this->order = util::array_get($columnOverwrite['order'], $this->order); $this->ignore = util::array_get($columnOverwrite['ignore'], $this->ignore); $this->visible = util::array_get($columnOverwrite['visible'], $this->visible); $this->viewType = util::array_get($columnOverwrite['viewType'], $this->viewType); $this->values = util::array_get($columnOverwrite['values'], $this->values); $initializer = util::array_get($columnOverwrite['initializer'], null); if ($initializer) { if (!$this->initializer) { $this->initializer = new InitializerInfo(); } $this->initializer->addInitializerConfig($initializer); } } }
/** * Tries to find the optional parameter $key in the $args array and returns the $defaultValue if * not found. */ protected function getParameter($args, $key, $defaultValue = NULL) { $value = util::array_get($args[$key]); return is_null($value) ? $defaultValue : $value; }
/** * Output a menu. * * @param \Twig_Environment $env * @param string $identifier Identifier for a particular menu * @param string $template The template to use. * @param array $params Extra parameters to pass on to the menu template. * * @return null */ public function menu(\Twig_Environment $env, $identifier = '', $template = '_sub_menu.twig', $params = array()) { if ($this->safe) { return null; } $menus = $this->app['config']->get('menu'); if (!empty($identifier) && isset($menus[$identifier])) { $name = strtolower($identifier); $menu = $menus[$identifier]; } else { $name = strtolower(\utilphp\util::array_first_key($menus)); $menu = \utilphp\util::array_first($menus); } // If the menu loaded is null, replace it with an empty array instead of // throwing an error. if (!is_array($menu)) { $menu = array(); } $menu = $this->menuBuilder($menu); $twigvars = array('name' => $name, 'menu' => $menu); // If $params is not empty, merge it with twigvars. if (!empty($params) && is_array($params)) { $twigvars = $twigvars + $params; } return $env->render($template, $twigvars); }
/** * The taxonomy listing page controller. * * @param Request $request The Symfony Request * @param string $taxonomytype The taxonomy type slug * @param string $slug The taxonomy slug * * @return BoltResponse|false */ public function taxonomy($request, $taxonomytype, $slug) { $taxonomy = $this->app['storage']->getTaxonomyType($taxonomytype); // No taxonomytype, no possible content. if (empty($taxonomy)) { return false; } else { $taxonomyslug = $taxonomy['slug']; } // First, get some content $context = $taxonomy['singular_slug'] . '_' . $slug; $pagerid = Pager::makeParameterId($context); /* @var $query \Symfony\Component\HttpFoundation\ParameterBag */ $query = $request->query; $page = $query->get($pagerid, $query->get('page', 1)); $amount = $this->getOption('general/listing_records'); $order = $this->getOption('general/listing_sort'); $content = $this->app['storage']->getContentByTaxonomy($taxonomytype, $slug, ['limit' => $amount, 'order' => $order, 'page' => $page]); // See https://github.com/bolt/bolt/pull/2310 if ($taxonomy['behaves_like'] === 'tags' && !$content || in_array($taxonomy['behaves_like'], ['categories', 'grouping']) && !in_array($slug, isset($taxonomy['options']) ? array_keys($taxonomy['options']) : [])) { $this->abort(Response::HTTP_NOT_FOUND, "No slug '{$slug}' in taxonomy '{$taxonomyslug}'"); return null; } $template = $this->templateChooser()->taxonomy($taxonomyslug); $name = $slug; // Look in taxonomies in 'content', to get a display value for '$slug', perhaps. foreach ($content as $record) { $flat = util::array_flatten($record->taxonomy); $key = $this->app['resources']->getUrl('root') . $taxonomy['slug'] . '/' . $slug; if (isset($flat[$key])) { $name = $flat[$key]; } $key = $this->app['resources']->getUrl('root') . $taxonomy['singular_slug'] . '/' . $slug; if (isset($flat[$key])) { $name = $flat[$key]; } } $globals = ['records' => $content, 'slug' => $name, 'taxonomy' => $this->getOption('taxonomy/' . $taxonomyslug), 'taxonomytype' => $taxonomyslug]; return $this->render($template, [], $globals); }
/** * Search through a single contenttype. * * Search, weigh and return the results. * * @param $query * @param $contenttype * @param $fields * @param array $filter * * @return \Bolt\Legacy\Content */ private function searchSingleContentType($query, $contenttype, $fields, array $filter = null) { // This could be even more configurable // (see also Content->getFieldWeights) $searchableTypes = ['text', 'textarea', 'html', 'markdown']; $table = $this->getContentTypeCollection($contenttype); // Build fields 'WHERE' $fieldsWhere = []; foreach ($fields as $field => $fieldconfig) { if (in_array($fieldconfig['type'], $searchableTypes)) { foreach ($query['words'] as $word) { $fieldsWhere[] = sprintf('%s.%s LIKE %s', $table, $field, $this->app['db']->quote('%' . $word . '%')); } } } // make taxonomies work $taxonomytable = $this->getTablename('taxonomy'); $taxonomies = $this->getContentTypeTaxonomy($contenttype); $tagsWhere = []; $tagsQuery = ''; foreach ($taxonomies as $taxonomy) { if ($taxonomy['behaves_like'] == 'tags') { foreach ($query['words'] as $word) { $tagsWhere[] = sprintf('%s.slug LIKE %s', $taxonomytable, $this->app['db']->quote('%' . $word . '%')); } } } // only add taxonomies if they exist if (!empty($taxonomies) && !empty($tagsWhere)) { $tagsQueryA = sprintf("%s.contenttype = '%s'", $taxonomytable, $contenttype); $tagsQueryB = implode(' OR ', $tagsWhere); $tagsQuery = sprintf(' OR (%s AND (%s))', $tagsQueryA, $tagsQueryB); } // Build filter 'WHERE" // @todo make relations work as well $filterWhere = []; if (!is_null($filter)) { foreach ($fields as $field => $fieldconfig) { if (isset($filter[$field])) { $this->parseWhereParameter($table . '.' . $field, $filter[$field], $filterWhere); } } } // Build actual where $where = []; $where[] = sprintf("%s.status = 'published'", $table); $where[] = '(( ' . implode(' OR ', $fieldsWhere) . ' ) ' . $tagsQuery . ' )'; $where = array_merge($where, $filterWhere); // Build SQL query $select = sprintf('SELECT %s.id FROM %s LEFT JOIN %s ON %s.id = %s.content_id WHERE %s GROUP BY %s.id', $table, $table, $taxonomytable, $table, $taxonomytable, implode(' AND ', $where), $table); // Run Query $results = $this->app['db']->fetchAll($select); if (!empty($results)) { $ids = implode(' || ', util::array_pluck($results, 'id')); $results = $this->getContent($contenttype, ['id' => $ids, 'returnsingle' => false]); // Convert and weight foreach ($results as $result) { $result->weighSearchResult($query); } } return $results; }
/** * The taxonomy listing page controller. * * @param Request $request The Symfony Request * @param string $taxonomytype The taxonomy type slug * @param string $slug The taxonomy slug * * @return BoltResponse|false */ public function taxonomy(Request $request, $taxonomytype, $slug) { $taxonomy = $this->storage()->getTaxonomyType($taxonomytype); // No taxonomytype, no possible content. if (empty($taxonomy)) { return false; } else { $taxonomyslug = $taxonomy['slug']; } // First, get some content $context = $taxonomy['singular_slug'] . '_' . $slug; $page = $this->app['pager']->getCurrentPage($context); // Theme value takes precedence over default config @see https://github.com/bolt/bolt/issues/3951 $amount = $this->getOption('theme/listing_records', false) ?: $this->getOption('general/listing_records'); // Handle case where listing records has been override for specific taxonomy if (array_key_exists('listing_records', $taxonomy) && is_int($taxonomy['listing_records'])) { $amount = $taxonomy['listing_records']; } $order = $this->getOption('theme/listing_sort', false) ?: $this->getOption('general/listing_sort'); $content = $this->storage()->getContentByTaxonomy($taxonomytype, $slug, ['limit' => $amount, 'order' => $order, 'page' => $page]); if (!$this->isTaxonomyValid($content, $slug, $taxonomy)) { $this->abort(Response::HTTP_NOT_FOUND, "No slug '{$slug}' in taxonomy '{$taxonomyslug}'"); return; } $template = $this->templateChooser()->taxonomy($taxonomyslug); $name = $slug; // Look in taxonomies in 'content', to get a display value for '$slug', perhaps. foreach ($content as $record) { $flat = util::array_flatten($record->taxonomy); $key = $this->app['resources']->getUrl('root') . $taxonomy['slug'] . '/' . $slug; if (isset($flat[$key])) { $name = $flat[$key]; } $key = $this->app['resources']->getUrl('root') . $taxonomy['singular_slug'] . '/' . $slug; if (isset($flat[$key])) { $name = $flat[$key]; } } $globals = ['records' => $content, 'slug' => $name, 'taxonomy' => $this->getOption('taxonomy/' . $taxonomyslug), 'taxonomytype' => $taxonomyslug]; return $this->render($template, [], $globals); }
function d($v) { \utilphp\util::var_dump($v); }