Example #1
0
 protected function _getTagString()
 {
     if (isset($this->_properties['tag_string'])) {
         return $this->_properties['tag_string'];
     }
     return implode(', ', collection($this->tags ?: [])->extract('title')->toArray());
 }
Example #2
0
 /**
  * Get format permission data.
  *
  * @param $acos
  * @param array $aros
  * @param array $options
  * @return array
  * @SuppressWarnings("unused")
  */
 public function format($acos, array $aros, array $options = [])
 {
     $options = Hash::merge(['perms' => true, 'model' => 'Roles'], $options);
     $permissions = [];
     /** @var \Acl\Model\Entity\Aco $aco */
     foreach ($acos as $aco) {
         $acoId = $aco->get('id');
         $acoAlias = $aco->get('alias');
         $path = $this->Acos->find('path', ['for' => $acoId]);
         $path = join('/', collection($path)->extract('alias')->toArray());
         $data = ['path' => $path, 'alias' => $acoAlias, 'depth' => substr_count($path, '/')];
         foreach ($aros as $key => $aroId) {
             $role = ['foreign_key' => $key, 'model' => $options['model']];
             if ($options['perms']) {
                 $isCheck = $this->check($role, $path);
                 if ($key == Role::ADMIN_ID || $isCheck) {
                     $data['roles'][$key] = 1;
                 } else {
                     $data['roles'][$key] = (int) $isCheck;
                 }
             }
             $permissions[$acoId] = new Data($data);
         }
     }
     return $permissions;
 }
 /**
  * Loads ll permissions rules for this content type.
  *
  * @return void
  */
 protected function _loadPermissions()
 {
     if (empty($this->_permissions)) {
         $permissions = TableRegistry::get('Content.ContentTypePermissions')->find()->where(['content_type_id' => $this->get('id')])->toArray();
         $this->_permissions = collection($permissions);
     }
 }
Example #4
0
 /**
  * Get aros role ids.
  *
  * @param array $roles
  * @return array
  * @SuppressWarnings("unused")
  */
 public function getRole(array $roles = [])
 {
     $aros = $this->find()->where(['model' => 'Roles'])->where(function ($exp, $q) use($roles) {
         /** @var \Cake\Database\Expression\QueryExpression $exp */
         return $exp->in('foreign_key', array_keys($roles));
     });
     return collection($aros)->combine('foreign_key', 'id')->toArray();
 }
Example #5
0
 /**
  * setUp.
  *
  * @return void
  */
 public function setUp()
 {
     parent::setUp();
     $View = new View();
     $View->theme(option('front_theme'));
     $options = ['fixMissing' => false];
     $this->regions = [new Region($View, 'left-sidebar', $options), new Region($View, 'right-sidebar', $options), new Region($View, 'footer', $options)];
     $this->regions[0]->blocks(collection([new Entity(['region' => new Entity(['region' => 'left-sidebar'])]), new Entity(['region' => new Entity(['region' => 'left-sidebar'])]), new Entity(['region' => new Entity(['region' => 'left-sidebar'])])]));
     $this->regions[1]->blocks(collection([new Entity(['region' => new Entity(['region' => 'right-sidebar'])]), new Entity(['region' => new Entity(['region' => 'right-sidebar'])])]));
     $this->regions[2]->blocks(collection([new Entity(['region' => new Entity(['region' => 'footer'])]), new Entity(['region' => new Entity(['region' => 'footer'])]), new Entity(['region' => new Entity(['region' => 'footer'])]), new Entity(['region' => new Entity(['region' => 'footer'])]), new Entity(['region' => new Entity(['region' => 'footer'])])]));
 }
Example #6
0
 public static function getAgencies()
 {
     $posts = [];
     $items = collection("Agencies")->find()->toArray();
     foreach ($items as $key => $value) {
         //var_dump($value);
         if (stripos($value["Name"], $_POST["query"]) !== false) {
             array_push($posts, $value);
         }
     }
     echo json_encode($posts);
 }
 protected function fieldIsKey($field, $type)
 {
     $associations = collection($this->helper->associations())->filter(function ($association, $key) use($field) {
         return $association['foreign_key'] === $field;
     });
     foreach ($associations as $association) {
         if (isset($this->helper->foreignKeys()[$field]) && !$association['owner'] && $association['association_type'] === $type) {
             return $association;
         }
     }
     return false;
 }
Example #8
0
 /**
  * Handle an incoming request.
  *
  * @param \Illuminate\Http\Request $request
  * @param Closure $next
  * @param $options
  * @return mixed
  */
 public function handle($request, Closure $next, $options)
 {
     $parsedOptions = $this->parseOptions($options);
     $permissions = array_keys($parsedOptions);
     if ($this->getGuard()->guest()) {
         return $this->handleUnauthorized();
     }
     $roles = $this->getGuard()->user()->roles->pluck('slug')->toArray();
     if (!collection($permissions)->anyIn($roles)) {
         return $this->handleUnauthorized();
     }
     return $next($request);
 }
Example #9
0
 /**
  * test method which converts a collection to a flat array
  */
 public function testPrepareCollectionData()
 {
     $articles = $this->Articles->find('all');
     $data = collection($articles->toArray());
     $result = $this->Excel->prepareCollectionData($data);
     $this->assertEquals(count($result), 4);
     $headers = $result[0];
     $first = $result[1];
     $last = $result[3];
     $this->assertEquals($headers, ['id', 'author_id', 'title', 'body', 'published']);
     $this->assertEquals($first, [1, 1, 'First Article', 'First Article Body', 'Y']);
     $this->assertEquals($last, [3, 1, 'Third Article', 'Third Article Body', 'Y']);
 }
 /**
  * Tests that using the subquery strategy in a deep association returns the right results
  *
  * @see https://github.com/cakephp/cakephp/issues/5769
  * @return void
  */
 public function testDeepBelongsToManySubqueryStrategy2()
 {
     $table = TableRegistry::get('Authors');
     $table->hasMany('Articles');
     $table->Articles->belongsToMany('Tags', ['strategy' => 'subquery']);
     $table->belongsToMany('Tags', ['strategy' => 'subquery']);
     $table->Articles->belongsTo('Authors');
     $result = $table->Articles->find()->where(['Authors.id >' => 1])->contain(['Authors' => ['Tags' => function ($q) {
         return $q->order(['name']);
     }]])->toArray();
     $this->assertEquals(['tag1', 'tag2'], collection($result[0]->author->tags)->extract('name')->toArray());
     $this->assertEquals(3, $result[0]->author->id);
 }
Example #11
0
function getBlogPosts($filter, $page)
{
    global $blogPostsPerPage;
    $collection = collection('Blog Posts');
    $count = $collection->count($filter);
    $pages = ceil($count / $blogPostsPerPage);
    if ($page > $pages && $page != 1) {
        return null;
    }
    $posts = $collection->find($filter);
    $posts->limit($blogPostsPerPage)->skip(($page - 1) * $blogPostsPerPage);
    $posts->sort(["posted_date" => -1]);
    return ['posts' => $posts->toArray(), 'page' => $page, 'pages' => $pages];
}
Example #12
0
 /**
  * Maps raw data using mapFields
  *
  * @return mixed
  */
 protected function _map()
 {
     $result = [];
     collection($this->_mapFields)->each(function ($mappedField, $field) use(&$result) {
         $value = Hash::get($this->_rawData, $mappedField);
         $function = '_' . $field;
         if (method_exists($this, $function)) {
             $value = $this->{$function}();
         }
         $result[$field] = $value;
     });
     $token = Hash::get($this->_rawData, 'token');
     $result['credentials'] = ['token' => is_array($token) ? Hash::get($token, 'accessToken') : $token->getToken(), 'secret' => is_array($token) ? Hash::get($token, 'tokenSecret') : null, 'expires' => is_array($token) ? Hash::get($token, 'expires') : $token->getExpires()];
     $result['raw'] = $this->_rawData;
     return $result;
 }
 /**
  * Sends queued emails.
  */
 public function main()
 {
     if ($this->params['stagger']) {
         sleep(rand(0, $this->params['stagger']));
     }
     Configure::write('App.baseUrl', '/');
     $emailQueue = TableRegistry::get('EmailQueue', ['className' => EmailQueueTable::class]);
     $emails = $emailQueue->getBatch($this->params['limit']);
     $count = count($emails);
     foreach ($emails as $e) {
         $configName = $e->config === 'default' ? $this->params['config'] : $e->config;
         $template = $e->template === 'default' ? $this->params['template'] : $e->template;
         $layout = $e->layout === 'default' ? $this->params['layout'] : $e->layout;
         $headers = empty($e->headers) ? array() : (array) $e->headers;
         $theme = empty($e->theme) ? '' : (string) $e->theme;
         try {
             $email = $this->_newEmail($configName);
             if (!empty($e->from_email) && !empty($e->from_name)) {
                 $email->from($e->from_email, $e->from_name);
             }
             $transport = $email->transport();
             if ($transport && $transport->config('additionalParameters')) {
                 $from = key($email->from());
                 $transport->config(['additionalParameters' => "-f {$from}"]);
             }
             if (!empty($e->attachments)) {
                 $email->attachments($e->attachments);
             }
             $sent = $email->to($e->email)->subject($e->subject)->template($template, $layout)->emailFormat($e->format)->addHeaders($headers)->theme($theme)->viewVars($e->template_vars)->messageId(false)->returnPath($email->from())->send();
         } catch (SocketException $exception) {
             $this->err($exception->getMessage());
             $sent = false;
         }
         if ($sent) {
             $emailQueue->success($e->id);
             $this->out('<success>Email ' . $e->id . ' was sent</success>');
         } else {
             $emailQueue->fail($e->id);
             $this->out('<error>Email ' . $e->id . ' was not sent</error>');
         }
     }
     if ($count > 0) {
         $emailQueue->releaseLocks(collection($emails)->extract('id')->toList());
     }
 }
 /**
  * Loads the featured image (if any)
  *
  * @return void
  */
 public function getFeaturedImage(Event $event, Entity $entity)
 {
     $featuredImage = Hash::extract($entity->meta, '{n}[key=featured_image]');
     if (empty($featuredImage)) {
         return;
     }
     $featuredImage = end($featuredImage);
     $entity->featured_image_meta_id = $featuredImage->id;
     $entity->featured_image_id = $featuredImage->value;
     try {
         $entity->featured_image = TableRegistry::get('Croogo/FileManager.Attachments')->get($entity->featured_image_id);
     } catch (RecordNotFoundException $e) {
         //Image does not exist
         unset($entity->featured_image_id);
     }
     $entity->meta = collection($entity->meta)->reject(function ($item) {
         return $item->key === 'featured_image';
     })->toList();
 }
 /**
  * Stores a new email message in the queue.
  *
  * @param mixed $to      email or array of emails as recipients
  * @param array $data    associative array of variables to be passed to the email template
  * @param array $options list of options for email sending. Possible keys:
  *
  * - subject : Email's subject
  * - send_at : date time sting representing the time this email should be sent at (in UTC)
  * - template :  the name of the element to use as template for the email message
  * - layout : the name of the layout to be used to wrap email message
  * - format: Type of template to use (html, text or both)
  * - config : the name of the email config to be used for sending
  *
  * @return bool
  */
 public function enqueue($to, array $data, array $options = [])
 {
     $defaults = ['subject' => '', 'send_at' => new FrozenTime('now'), 'template' => 'default', 'layout' => 'default', 'theme' => '', 'format' => 'both', 'headers' => [], 'template_vars' => $data, 'config' => 'default', 'attachments' => []];
     $email = $options + $defaults;
     if (!is_array($to)) {
         $to = [$to];
     }
     $emails = [];
     foreach ($to as $t) {
         $emails[] = ['email' => $t] + $email;
     }
     $emails = $this->newEntities($emails);
     return $this->connection()->transactional(function () use($emails) {
         $failure = collection($emails)->map(function ($email) {
             return $this->save($email);
         })->contains(false);
         return !$failure;
     });
 }
Example #16
0
 public function testNav()
 {
     $client = $this->createClient();
     $crawler = $client->request('GET', '/');
     $nav = collection("Pages")->find(["navigation" => true])->toArray();
     //Test if top-nav exists
     $this->assertCount(1, $crawler->filter('nav.top-nav'));
     //Test Homepage & lower nav
     $homeurl = $crawler->filter('nav.navbar-lower')->selectLink('Home');
     $this->assertCount(1, $crawler->filter('nav.navbar-lower')->selectLink('Home'));
     $client->click($homeurl->link());
     $this->assertTrue($client->getResponse()->isOk());
     //Test all navigation urls
     foreach ($nav as $item) {
         if (!isset($item['Title_slug']) || $item['Title_slug'] !== 'home') {
             $url = $crawler->filter('nav.navbar-lower')->selectLink($item['Title'])->link();
             $client->click($url);
             $this->assertTrue($client->getResponse()->isOk());
         }
     }
 }
Example #17
0
 /**
  * Get the given plugin as an object, or a collection of objects if not
  * specified.
  *
  * @param string $plugin Plugin name to get, or null to get a collection of
  *  all plugin objects
  * @return \CMS\Core\Package\PluginPackage|\Cake\Collection\Collection
  * @throws \Cake\Error\FatalErrorException When requested plugin was not found
  */
 public static function get($plugin = null)
 {
     $cacheKey = "get({$plugin})";
     $cache = static::cache($cacheKey);
     if ($cache !== null) {
         return $cache;
     }
     if ($plugin === null) {
         $collection = [];
         foreach ((array) quickapps('plugins') as $plugin) {
             $plugin = PackageFactory::create($plugin['name']);
             if ($plugin instanceof PluginPackage) {
                 $collection[] = $plugin;
             }
         }
         return static::cache($cacheKey, collection($collection));
     }
     $package = PackageFactory::create($plugin);
     if ($package instanceof PluginPackage) {
         return static::cache($cacheKey, $package);
     }
     throw new FatalErrorException(__d('cms', 'Plugin "{0}" was not found', $plugin));
 }
Example #18
0
 /**
  * Gets a collection of information of every registered field in the system, or
  * information for a particular field.
  *
  * Some fields may register themselves as hidden when they are intended to be
  * used exclusively by plugins. So users can not `attach` them to entities using
  * Field UI.
  *
  * ### Usage:
  *
  * ```php
  * $visibleOnly = fieldsInfo()->filter(function ($info) {
  *     return !$info['hidden'];
  * });
  * ```
  *
  * @param string|null $field Field for which get its information as an array, or
  *  null (default) to get all of them as a collection. e.g.
  *  `Field\Field\TextField`
  * @return \Cake\Collection\Collection|array A collection of fields information
  */
 function fieldsInfo($field = null)
 {
     $fields = [];
     $plugins = plugin()->filter(function ($plugin) {
         return $plugin->status;
     });
     foreach ($plugins as $plugin) {
         foreach ($plugin->fields as $className) {
             if (class_exists($className)) {
                 $handler = new $className();
                 $result = array_merge(['type' => 'varchar', 'name' => null, 'description' => null, 'hidden' => false, 'handler' => $className, 'maxInstances' => 0, 'searchable' => true], (array) $handler->info());
                 $fields[$className] = $result;
             }
         }
     }
     if ($field === null) {
         return collection(array_values($fields));
     }
     if (isset($fields[$field])) {
         return $fields[$field];
     }
     throw new \Exception(__d('field', 'The field handler "{0}" was not found.', $field));
 }
Example #19
0
 /**
  * Checks if event is in fired array
  *
  * @param mixed $other Constraint check
  * @return bool
  */
 public function matches($other)
 {
     $firedEvents = [];
     $list = $this->_eventManager->getEventList();
     $totalEvents = count($list);
     for ($e = 0; $e < $totalEvents; $e++) {
         $firedEvents[] = $list[$e];
     }
     $eventGroup = collection($firedEvents)->groupBy(function (Event $event) {
         return $event->name();
     })->toArray();
     if (!array_key_exists($other, $eventGroup)) {
         return false;
     }
     $events = $eventGroup[$other];
     if (count($events) > 1) {
         throw new PHPUnit_Framework_AssertionFailedError(sprintf('Event "%s" was fired %d times, cannot make data assertion', $other, count($events)));
     }
     $event = $events[0];
     if (array_key_exists($this->_dataKey, $event->data) === false) {
         return false;
     }
     return $event->data[$this->_dataKey] === $this->_dataValue;
 }
 /**
  * Sets the sorting options for the result set.
  *
  * The accepted format for the $order parameter is:
  *
  * - [['name' => ['order'=> 'asc', ...]], ['price' => ['order'=> 'asc', ...]]]
  * - ['name' => 'asc', 'price' => 'desc']
  * - 'field1' (defaults to order => 'desc')
  *
  * @param string|array $order The sorting order to use.
  * @param bool $overwrite Whether or not to replace previous sorting.
  * @return $this
  */
 public function order($order, $overwrite = false)
 {
     // [['field' => [...]], ['field2' => [...]]]
     if (is_array($order) && is_numeric(key($order))) {
         if ($overwrite) {
             $this->_parts['order'] = $order;
             return $this;
         }
         $this->_parts['order'] = array_merge($order, $this->_parts['order']);
         return $this;
     }
     if (is_string($order)) {
         $order = [$order => ['order' => 'desc']];
     }
     $normalizer = function ($order, $key) {
         // ['field' => 'asc|desc']
         if (is_string($order)) {
             return [$key => ['order' => $order]];
         }
         return [$key => $order];
     };
     $order = collection($order)->map($normalizer)->toList();
     if (!$overwrite) {
         $order = array_merge($this->_parts['order'], $order);
     }
     $this->_parts['order'] = $order;
     return $this;
 }
Example #21
0
 * @since         0.1.0
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
use Cake\Utility\Inflector;
$associations += ['BelongsTo' => [], 'HasOne' => [], 'HasMany' => [], 'BelongsToMany' => []];
$immediateAssociations = $associations['BelongsTo'] + $associations['HasOne'];
$associationFields = collection($fields)->map(function ($field) use($immediateAssociations) {
    foreach ($immediateAssociations as $alias => $details) {
        if ($field === $details['foreignKey']) {
            return [$field => $details];
        }
    }
})->filter()->reduce(function ($fields, $value) {
    return $fields + $value;
}, []);
$groupedFields = collection($fields)->filter(function ($field) use($schema) {
    return $schema->columnType($field) !== 'binary';
})->groupBy(function ($field) use($schema, $associationFields) {
    $type = $schema->columnType($field);
    if (isset($associationFields[$field])) {
        return 'string';
    }
    if (in_array($type, ['integer', 'float', 'decimal', 'biginteger'])) {
        return 'number';
    }
    if (in_array($type, ['date', 'time', 'datetime', 'timestamp'])) {
        return 'date';
    }
    return in_array($type, ['text', 'boolean']) ? $type : 'string';
})->toArray();
$groupedFields += ['number' => [], 'string' => [], 'boolean' => [], 'date' => [], 'text' => []];
Example #22
0
 /**
  * Tests that the sortBy method does not die when something that is not a
  * collection is passed
  *
  * @return void
  */
 public function testComplexSortBy()
 {
     $results = collection([3, 7])->unfold(function ($value) {
         return [['sorting' => $value * 2], ['sorting' => $value * 2]];
     })->sortBy('sorting')->extract('sorting')->toList();
     $this->assertEquals([14, 14, 6, 6], $results);
 }
 /**
  * testClearLocks method.
  */
 public function testClearLocks()
 {
     $batch = $this->EmailQueue->getBatch();
     $this->assertNotEmpty($batch);
     $this->assertEmpty($this->EmailQueue->getBatch());
     $this->EmailQueue->clearLocks();
     $batch = $this->EmailQueue->getBatch();
     $this->assertEquals(array('email-1', 'email-2', 'email-3', 'email-5'), collection($batch)->extract('id')->toList());
 }
Example #24
0
 /**
  * Update user by username
  *
  * @param string $username username
  * @param array $data data
  * @return bool
  */
 protected function _updateUser($username, $data)
 {
     $user = $this->Users->find()->where(['Users.username' => $username])->first();
     if (empty($user)) {
         $this->error(__d('Users', 'The user was not found.'));
     }
     $user = $this->Users->patchEntity($user, $data);
     collection($data)->filter(function ($value, $field) use($user) {
         return !$user->accessible($field);
     })->each(function ($value, $field) use(&$user) {
         $user->{$field} = $value;
     });
     $savedUser = $this->Users->save($user);
     return $savedUser;
 }
Example #25
0
<?php

date_default_timezone_set('Europe/Brussels');
define('TWIG_CONFIG', serialize(array('twig.path' => __DIR__ . '/../assets/views', 'twig.options' => array('strict_variables' => false))));
define('TWITTER_CONFIG', serialize(array("API_key" => get_registry('twitter_api_key', ""), "API_secret" => get_registry('twitter_api_secret', ""), "token" => get_registry('twitter_token', ""), "secret" => get_registry('twitter_secret', ""))));
define('EMBEDLY_CONFIG', get_registry('embedly_key', ""));
define('TWIG_GLOBALS', serialize(array("telephone" => get_registry('Telephone', ""), "email" => get_registry('Email', ""), "nav" => collection("Pages")->find(["navigation" => true])->toArray(), "embedly" => EMBEDLY_CONFIG)));
define('CV_URL', get_registry('cv_url', ""));
Example #26
0
 /**
  * main() method.
  *
  * @return void
  */
 public function main()
 {
     if ($this->params['stagger']) {
         sleep(rand(0, $this->params['stagger']));
     }
     Configure::write('App.baseUrl', '/');
     $emailQueue = TableRegistry::get('EmailQueue', ['className' => EmailQueueTable::class]);
     $emails = $emailQueue->getBatch($this->params['limit']);
     $count = count($emails);
     foreach ($emails as $e) {
         $configName = $e->config === 'default' ? $this->params['config'] : $e->config;
         $template = $e->template === 'default' ? $this->params['template'] : $e->template;
         $layout = $e->layout === 'default' ? $this->params['layout'] : $e->layout;
         $headers = empty($e->headers) ? [] : (array) $e->headers;
         $theme = empty($e->theme) ? '' : (string) $e->theme;
         $helpers = ['Html', 'Text', 'Number', 'Url'];
         $fromEmail = null;
         $fromName = null;
         try {
             $email = $this->_newEmail($configName);
             if (!empty($e->from_email) && !empty($e->from_name)) {
                 $email->from($e->from_email, $e->from_name);
             }
             $transport = $email->transport();
             if ($transport && $transport->config('additionalParameters')) {
                 $from = key($email->from());
                 $transport->config(['additionalParameters' => "-f {$from}"]);
             }
             $sent = $email->to($e->email_to)->subject($e->subject)->template($template, $layout)->emailFormat($e->format)->addHeaders($headers)->theme($theme)->helpers($helpers)->viewVars($e->template_vars)->messageId(false)->returnPath($email->from());
             if ($e->email_cc) {
                 $sent->addCc(explode(',', $e->email_cc));
             }
             if ($e->email_bcc) {
                 $sent->addBcc(explode(',', $e->email_bcc));
             }
             if (get_class($transport) === 'Cake\\Mailer\\Transport\\SmtpTransport') {
                 $fromEmail = $fromName = $transport->config()['username'];
             } else {
                 foreach ($sent->from() as $k => $v) {
                     $fromEmail = $k;
                     $fromName = $v;
                 }
             }
             if ($e->email_reply_to) {
                 $sent->replyTo(explode(',', $e->email_reply_to));
             } else {
                 $sent->replyTo($fromEmail, $fromName);
             }
             $sent = $sent->send();
         } catch (SocketException $exception) {
             $this->err($exception->getMessage());
             $sent = false;
         }
         if ($sent) {
             $emailQueue->success($e->id, $fromEmail, $fromEmail);
             Log::info("Email {$e->id} was sent");
         } else {
             $emailQueue->fail($e->id, $fromEmail, $fromEmail);
             Log::info("Email {$e->id} was NOT sent");
         }
     }
     if ($count > 0) {
         $emailQueue->releaseLocks(collection($emails)->extract('id')->toList());
     }
 }
Example #27
0
 /**
  * Tests that it is possible to select distinct rows, even filtering by one column
  * this is testing that there is a specific implementation for DISTINCT ON
  *
  * @return void
  */
 public function testSelectDistinctON()
 {
     $query = new Query($this->connection);
     $result = $query->select(['id', 'author_id'])->distinct(['author_id'])->from(['a' => 'articles'])->order(['author_id' => 'ASC'])->execute();
     $this->assertCount(2, $result);
     $results = $result->fetchAll('assoc');
     $this->assertEquals(['id', 'author_id'], array_keys($results[0]));
     $this->assertEquals([3, 1], collection($results)->sortBy('author_id')->extract('author_id')->toList());
 }
Example #28
0
 public function enqueueBatch(array $jobs)
 {
     if (!$this->getDatasource()->persistJobs($jobs)) {
         throw new EnqueueException('Job batch could not be persisted');
     }
     $sequenceMap = [];
     collection($jobs)->filter(function (Job $job) use(&$sequenceMap) {
         $jobSequence = $job->getSequence();
         if (!$jobSequence) {
             return true;
         }
         if (isset($sequenceMap[$jobSequence])) {
             return false;
         }
         $currentlySequenced = $this->getDatasource()->currentlySequenced($job);
         $sequenceMap[$jobSequence] = $currentlySequenced;
         return !$currentlySequenced;
     })->each(function (Job $job) {
         $this->_pushToBroker($job);
     });
     return true;
 }
Example #29
0
// Get All Needs
if (@$_POST["Action"] == "GetNeeds") {
    $items = collection("needs")->find()->toArray();
    for ($i = 0; $i < sizeof($items); $i++) {
        $item = $items[$i];
        $organization = collection("organizations")->find(["_id" => $item["organization"]])->toArray();
        $items[$i]["organization"] = $organization[0];
    }
    echo json_encode($items);
}
// Get A Collection
if (@$_POST["collection"] && @$_POST["collection"] != "users") {
    if ($_POST["limit"] && $_POST["skip"]) {
        $items = collection($_POST["collection"])->find()->limit($_POST["limit"])->skip($_POST["skip"])->toArray();
    } else {
        $items = collection($_POST["collection"])->find()->toArray();
    }
    echo json_encode($items);
}
// Get organization needs
if ($_POST["organizationNeeds"]) {
    if (@$_POST["_id"]) {
        $needs = cockpit('collections:find', 'needs', ['organization' => $_POST["_id"]]);
        echo json_encode($needs);
    } else {
        echo '
      {"status":false,"message":"Provide organization _id!"}
    ';
    }
}
// Get Organization
Example #30
0
<?php

require_once '../../configuration.php';
$categoryId = $_POST['categoryid'];
header('Content-Type: application/json');
$items = array();
foreach (collection("Item")->find() as $item) {
    $test = 0;
    if ($item['Category'] == $categoryId) {
        $test++;
        $imagePath = substr($item['Image'], 5);
        array_push($items, array('id' => $item['_id'], 'name' => $item['Name'], 'image' => $imagePath));
    }
}
echo json_encode($items);