Example #1
4
 /**
  * Constructs a book dialog
  * $action - GET or POST action to take.
  * $inclusions - NULL (in which case it does nothing), or an array of book IDs to include.
  * $exclusions - NULL (in which case it does nothing), or an array of book IDs to exclude.
  */
 public function __construct($header, $info_top, $info_bottom, $action, $inclusions, $exclusions)
 {
     $this->view = new Assets_View(__FILE__);
     $caller = $_SERVER["PHP_SELF"] . "?" . http_build_query(array());
     $this->view->view->caller = $caller;
     $this->view->view->header = $header;
     $this->view->view->info_top = $info_top;
     $this->view->view->info_bottom = $info_bottom;
     $this->view->view->action = $action;
     $database_books = Database_Books::getInstance();
     $book_ids = $database_books->getIDs();
     if (is_array($inclusions)) {
         $book_ids = $inclusions;
     }
     if (is_array($exclusions)) {
         $book_ids = array_diff($book_ids, $exclusions);
         $book_ids = array_values($book_ids);
     }
     foreach ($book_ids as $id) {
         $book_names[] = $database_books->getEnglishFromId($id);
     }
     $this->view->view->book_ids = $book_ids;
     $this->view->view->book_names = $book_names;
     $this->view->render("books2.php");
     Assets_Page::footer();
     die;
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $path = $input->getArgument('path');
     if (!file_exists($path)) {
         $output->writeln("{$path} is not a file or a path");
     }
     $filePaths = [];
     if (is_file($path)) {
         $filePaths = [realpath($path)];
     } elseif (is_dir($path)) {
         $filePaths = array_diff(scandir($path), array('..', '.'));
     } else {
         $output->writeln("{$path} is not known.");
     }
     $generator = new StopwordGenerator($filePaths);
     if ($input->getArgument('type') === 'json') {
         echo json_encode($this->toArray($generator->getStopwords()), JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE);
         echo json_last_error_msg();
         die;
         $output->write(json_encode($this->toArray($generator->getStopwords())));
     } else {
         $stopwords = $generator->getStopwords();
         $stdout = fopen('php://stdout', 'w');
         echo 'token,freq' . PHP_EOL;
         foreach ($stopwords as $token => $freq) {
             fputcsv($stdout, [utf8_encode($token), $freq]) . PHP_EOL;
         }
         fclose($stdout);
     }
 }
Example #3
0
 /**
  * List users.
  *
  * ## OPTIONS
  *
  * [--role=<role>]
  * : Only display users with a certain role.
  *
  * [--<field>=<value>]
  * : Control output by one or more arguments of get_users().
  *
  * [--network]
  * : List all users in the network for multisite.
  *
  * [--field=<field>]
  * : Prints the value of a single field for each user.
  *
  * [--fields=<fields>]
  * : Limit the output to specific object fields.
  *
  * [--format=<format>]
  * : Accepted values: table, csv, json, count. Default: table
  *
  * ## AVAILABLE FIELDS
  *
  * These fields will be displayed by default for each user:
  *
  * * ID
  * * user_login
  * * display_name
  * * user_email
  * * user_registered
  * * roles
  *
  * These fields are optionally available:
  *
  * * user_pass
  * * user_nicename
  * * user_url
  * * user_activation_key
  * * user_status
  * * spam
  * * deleted
  * * caps
  * * cap_key
  * * allcaps
  * * filter
  *
  * ## EXAMPLES
  *
  *     wp user list --field=ID
  *
  *     wp user list --role=administrator --format=csv
  *
  *     wp user list --fields=display_name,user_email --format=json
  *
  * @subcommand list
  */
 public function list_($args, $assoc_args)
 {
     if (\WP_CLI\Utils\get_flag_value($assoc_args, 'network')) {
         if (!is_multisite()) {
             WP_CLI::error('This is not a multisite install.');
         }
         $assoc_args['blog_id'] = 0;
         if (isset($assoc_args['fields'])) {
             $fields = explode(',', $assoc_args['fields']);
             $assoc_args['fields'] = array_diff($fields, array('roles'));
         } else {
             $assoc_args['fields'] = array_diff($this->obj_fields, array('roles'));
         }
     }
     $formatter = $this->get_formatter($assoc_args);
     if ('ids' == $formatter->format) {
         $assoc_args['fields'] = 'ids';
     } else {
         $assoc_args['fields'] = 'all_with_meta';
     }
     $users = get_users($assoc_args);
     if ('ids' == $formatter->format) {
         echo implode(' ', $users);
     } else {
         $it = WP_CLI\Utils\iterator_map($users, function ($user) {
             if (!is_object($user)) {
                 return $user;
             }
             $user->roles = implode(',', $user->roles);
             return $user;
         });
         $formatter->display_items($it);
     }
 }
Example #4
0
 /**
  * Display a listing of the resource.
  *
  * @param Store $store
  *
  * @return Response
  */
 public function index(Store $store)
 {
     // ImportedProduct::truncate();
     // ErrorProduct::truncate();
     JavaScript::put(['url' => '/products', 'os_total' => OsProduct::count(), 'imported_total' => ImportedProduct::count(), 'resource' => array_values(array_diff(OsProduct::orderBy('products_id', 'desc')->lists('products_id')->toArray(), ImportedProduct::orderBy('os_id', 'desc')->lists('os_id')->toArray(), ErrorProduct::orderBy('os_id', 'desc')->lists('os_id')->toArray()))]);
     return view('importer.index', ['resource' => 'Products']);
 }
Example #5
0
 public function getTransportMock($args = 'testuri', $changeMethods = array())
 {
     //Array XOR
     $defaultMockMethods = array('getDomFromBackend', 'getJsonFromBackend', 'checkLogin', 'initConnection', '__destruct', '__construct');
     $mockMethods = array_merge(array_diff($defaultMockMethods, $changeMethods), array_diff($changeMethods, $defaultMockMethods));
     return $this->getMock('jackalope_transport_DavexClient_Mock', $mockMethods, array($args));
 }
Example #6
0
 /**
  * Sends a request to the REST API service and does initial processing
  * on the response.
  *
  * @param  string $op    Name of the operation for the request
  * @param  array  $query Query data for the request (optional)
  * @throws Zend_Service_Exception
  * @return DOMDocument Parsed XML response
  */
 protected function _makeRequest($op, $query = null)
 {
     if ($query != null) {
         $query = array_diff($query, array_filter($query, 'is_null'));
         $query = '?' . http_build_query($query);
     }
     $this->_http->setUri($this->_baseUri . $op . '.do' . $query);
     $response = $this->_http->request('GET');
     if ($response->isSuccessful()) {
         $doc = new DOMDocument();
         $doc->loadXML($response->getBody());
         $xpath = new DOMXPath($doc);
         $list = $xpath->query('/status/code');
         if ($list->length > 0) {
             $code = $list->item(0)->nodeValue;
             if ($code != 0) {
                 $list = $xpath->query('/status/message');
                 $message = $list->item(0)->nodeValue;
                 /**
                  * @see Zend_Service_Exception
                  */
                 require_once 'Zend/Service/Exception.php';
                 throw new Zend_Service_Exception($message, $code);
             }
         }
         return $doc;
     }
     /**
      * @see Zend_Service_Exception
      */
     require_once 'Zend/Service/Exception.php';
     throw new Zend_Service_Exception($response->getMessage(), $response->getStatus());
 }
Example #7
0
 /**
  * Fetches hashed data from db and put into instance
  */
 private function __save()
 {
     $class = $this->class;
     $database = new database($class::$database);
     if ($this->get_attributes()) {
         $columns = "(`{$class::$entity_id_column}`, `{$class::$key_column}`, `{$class::$value_column}`, `date_added`, `date_updated`)";
         $placeholders = $values = $duplicate_keys = array();
         foreach ($this->get_attributes() as $key => $value) {
             $placeholders[] = "(%d, %s, %s, NOW(), NOW())";
             $values[] = $this->entity_id;
             $values[] = $key;
             $values[] = $value;
             $duplicate_keys[] = "`{$class::$value_column}` = VALUES(`{$class::$value_column}`)";
         }
         $duplicate_keys[] = '`date_updated` = VALUES(`date_updated`)';
         $database->query("INSERT INTO {$class::$table} {$columns} VALUES " . implode(', ', $placeholders) . " ON DUPLICATE KEY UPDATE " . implode(', ', $duplicate_keys), $values);
     }
     if ($unset_keys = array_diff($this->original_keys, array_keys($this->get_attributes()))) {
         // we unset something
         print_r(array($this->entity_id, $unset_keys));
         database::enable_log();
         $database->query("DELETE FROM {$class::$table} WHERE `{$class::$entity_id_column}` = %d AND `{$class::$key_column}` IN (%s)", array($this->entity_id, $unset_keys));
     }
     return true;
 }
Example #8
0
 /**
  * Get Global Application CMS accessibility scope.
  *
  * @access public
  * @static
  * @uses   Core\Config()
  *
  * @return array
  */
 public static function getAccessibilityScope()
 {
     $scope = glob(Core\Config()->paths('mode') . 'controllers' . DIRECTORY_SEPARATOR . '*.php');
     $builtin_scope = array('CMS\\Controllers\\CMS');
     $builtin_actions = array();
     $accessibility_scope = array();
     foreach ($builtin_scope as $resource) {
         $builtin_actions = array_merge($builtin_actions, get_class_methods($resource));
     }
     $builtin_actions = array_filter($builtin_actions, function ($action) {
         return !in_array($action, array('create', 'show', 'edit', 'delete', 'export'), true);
     });
     foreach ($scope as $resource) {
         $resource = basename(str_replace('.php', '', $resource));
         if ($resource !== 'cms') {
             $controller_name = '\\CMS\\Controllers\\' . $resource;
             $controller_class = new \ReflectionClass($controller_name);
             if (!$controller_class->isInstantiable()) {
                 continue;
             }
             /* Create instance only if the controller class is instantiable */
             $controller_object = new $controller_name();
             if ($controller_object instanceof CMS\Controllers\CMS) {
                 $accessibility_scope[$resource] = array_diff(get_class_methods($controller_name), $builtin_actions);
                 array_push($accessibility_scope[$resource], 'index');
                 foreach ($accessibility_scope[$resource] as $key => $action_with_acl) {
                     if (in_array($action_with_acl, $controller_object->skipAclFor, true)) {
                         unset($accessibility_scope[$resource][$key]);
                     }
                 }
             }
         }
     }
     return $accessibility_scope;
 }
 /**
  * Perform actions after object save
  *
  * @param Mage_Widget_Model_Widget_Instance $object
  * @return Mage_Widget_Model_Mysql4_Widget_Instance
  */
 protected function _afterSave(Mage_Core_Model_Abstract $object)
 {
     $pageTable = $this->getTable('widget/widget_instance_page');
     $pageLayoutTable = $this->getTable('widget/widget_instance_page_layout');
     $layoutUpdateTable = $this->getTable('core/layout_update');
     $layoutLinkTable = $this->getTable('core/layout_link');
     $write = $this->_getWriteAdapter();
     $select = $write->select()->from($pageTable, array('page_id'))->where('instance_id = ?', $object->getId());
     $pageIds = $write->fetchCol($select);
     $removePageIds = array_diff($pageIds, $object->getData('page_group_ids'));
     $select = $write->select()->from($pageLayoutTable, array('layout_update_id'))->where('page_id in (?)', $pageIds);
     $removeLayoutUpdateIds = $write->fetchCol($select);
     $this->_deleteWidgetInstancePages($removePageIds);
     $write->delete($pageLayoutTable, $write->quoteInto('page_id in (?)', $pageIds));
     $this->_deleteLayoutUpdates($removeLayoutUpdateIds);
     foreach ($object->getData('page_groups') as $pageGroup) {
         $pageLayoutUpdateIds = $this->_saveLayoutUpdates($object, $pageGroup);
         $data = array('group' => $pageGroup['group'], 'layout_handle' => $pageGroup['layout_handle'], 'block_reference' => $pageGroup['block_reference'], 'for' => $pageGroup['for'], 'entities' => $pageGroup['entities'], 'template' => $pageGroup['template']);
         $pageId = $pageGroup['page_id'];
         if (in_array($pageGroup['page_id'], $pageIds)) {
             $write->update($pageTable, $data, $write->quoteInto('page_id = ?', $pageId));
         } else {
             $write->insert($pageTable, array_merge(array('instance_id' => $object->getId()), $data));
             $pageId = $write->lastInsertId();
         }
         foreach ($pageLayoutUpdateIds as $layoutUpdateId) {
             $write->insert($pageLayoutTable, array('page_id' => $pageId, 'layout_update_id' => $layoutUpdateId));
         }
     }
     return parent::_afterSave($object);
 }
 public function test_certificate_get_teachers()
 {
     global $DB;
     $certificate = $this->generator->create_instance(array('course' => $this->course->id));
     $coursemodule = get_coursemodule_from_instance('certificate', $certificate->id);
     $studentroleid = $DB->get_record('role', array('shortname' => 'student'), 'id')->id;
     $teacherroleid = $DB->get_record('role', array('shortname' => 'editingteacher'), 'id')->id;
     $teacheruserarray = array();
     for ($i = 0; $i < 10; $i++) {
         $teacheruserarray[] = $this->getDataGenerator()->create_user(array('email' => "teacherdoge{$i}@dogeversity.doge", 'username' => "Dr. doge{$i}"));
         // Enrol the user as a teacher.
         $this->getDataGenerator()->enrol_user(end($teacheruserarray)->id, $this->course->id, $teacherroleid);
     }
     // Enrol a single student and issue his/her a certificate.
     $studentuser = $this->getDataGenerator()->create_user(array('email' => "*****@*****.**", 'username' => "dogemanorwomen"));
     $this->getDataGenerator()->enrol_user($studentuser->id, $this->course->id, $studentroleid);
     certificate_get_issue($this->course, $studentuser, $certificate, $coursemodule);
     $certificateteacherarray = certificate_get_teachers(null, $studentuser, $coursemodule, $coursemodule);
     // Acquire the ids (not all attributes are equal considering db transaction can have auto values).
     $teacheruserids = array_map(create_function('$t', 'return $t->id;'), $teacheruserarray);
     $certificateteacherids = array_map(create_function('$c', 'return $c->id;'), $certificateteacherarray);
     /**
      * Ensure that two arrays have one-to-one correspondence, that is each
      * is a subset of each other.
      */
     $emptyarray = array();
     $this->assertEquals(array_diff($teacheruserids, $certificateteacherids), $emptyarray);
 }
 /**
  * {@inheritdoc}
  */
 public function normalize($product, $format = null, array $context = [])
 {
     if (!$this->serializer instanceof NormalizerInterface) {
         throw new \LogicException('Serializer must be a normalizer');
     }
     $context['entity'] = 'product';
     $data = [];
     if ($product->getGroupCodes()) {
         $groups = explode(',', $product->getGroupCodes());
         if ($product->getVariantGroup()) {
             $variantGroup = $product->getVariantGroup()->getCode();
             $groups = array_diff($groups, [$variantGroup]);
         }
     } else {
         $groups = [];
     }
     $data[self::FIELD_FAMILY] = $product->getFamily() ? $product->getFamily()->getCode() : null;
     $data[self::FIELD_GROUPS] = $groups;
     $data[self::FIELD_VARIANT_GROUP] = $product->getVariantGroup() ? $product->getVariantGroup()->getCode() : null;
     $data[self::FIELD_CATEGORY] = $product->getCategoryCodes() ? explode(',', $product->getCategoryCodes()) : [];
     $data[self::FIELD_ENABLED] = $product->isEnabled();
     $data[self::FIELD_ASSOCIATIONS] = $this->normalizeAssociations($product->getAssociations());
     $data[self::FIELD_VALUES] = $this->normalizeValues($product->getValues(), $format, $context);
     if (isset($context['resource'])) {
         $data['resource'] = $context['resource'];
     }
     return $data;
 }
Example #12
0
 public function passMenu()
 {
     // return if no Itemid or selection is set
     if (!$this->request->Itemid || empty($this->selection)) {
         return $this->pass($this->params->inc_noitemid);
     }
     $menutype = 'type.' . self::getMenuType();
     // return true if menu type is in selection
     if (in_array($menutype, $this->selection)) {
         return $this->pass(true);
     }
     // return true if menu is in selection
     if (in_array($this->request->Itemid, $this->selection)) {
         return $this->pass($this->params->inc_children != 2);
     }
     if (!$this->params->inc_children) {
         return $this->pass(false);
     }
     $parent_ids = $this->getMenuParentIds($this->request->Itemid);
     $parent_ids = array_diff($parent_ids, array('1'));
     foreach ($parent_ids as $id) {
         if (!in_array($id, $this->selection)) {
             continue;
         }
         return $this->pass(true);
     }
     return $this->pass(false);
 }
Example #13
0
 public function testNormalizeToArray()
 {
     $normalized = ArrayUtil::normalizeToArray($this->arrayTemplate, $this->arrayOld);
     $tmplKeys = array_keys($this->arrayTemplate);
     $oldKeys = array_keys($this->arrayOld);
     $keepKeys = array_intersect($tmplKeys, $oldKeys);
     $newKeys = array_diff($tmplKeys, $oldKeys);
     $deleteKeys = array_diff($oldKeys, $tmplKeys);
     // All keys in the template must be present:
     foreach ($tmplKeys as $key) {
         $this->assertArrayHasKey($key, $normalized, "Array lost a key!");
     }
     // All fields not specified must be removed:
     foreach ($deleteKeys as $key) {
         $this->assertArrayNotHasKey($key, $normalized);
     }
     // All new fields must inherit specified default values:
     foreach ($newKeys as $key) {
         $this->assertEquals($this->arrayTemplate[$key], $normalized[$key], "Didn't inherit default value!");
     }
     // All fields must retain their original values, if they didn't need to
     // be initialized with default values:
     foreach ($keepKeys as $key) {
         $this->assertEquals($this->arrayOld[$key], $normalized[$key], "Array value changed when it shouldn't have!");
     }
 }
Example #14
0
 /**
  * @param  \ReflectionClass|string
  * @return self
  */
 public static function from($from)
 {
     $from = new \ReflectionClass($from instanceof \ReflectionClass ? $from->getName() : $from);
     if (PHP_VERSION_ID >= 70000 && $from->isAnonymous()) {
         $class = new static('anonymous');
     } else {
         $class = new static($from->getShortName(), new PhpNamespace($from->getNamespaceName()));
     }
     $class->type = $from->isInterface() ? 'interface' : (PHP_VERSION_ID >= 50400 && $from->isTrait() ? 'trait' : 'class');
     $class->final = $from->isFinal() && $class->type === 'class';
     $class->abstract = $from->isAbstract() && $class->type === 'class';
     $class->implements = $from->getInterfaceNames();
     $class->documents = $from->getDocComment() ? array(preg_replace('#^\\s*\\* ?#m', '', trim($from->getDocComment(), "/* \r\n\t"))) : array();
     if ($from->getParentClass()) {
         $class->extends = $from->getParentClass()->getName();
         $class->implements = array_diff($class->implements, $from->getParentClass()->getInterfaceNames());
     }
     foreach ($from->getProperties() as $prop) {
         if ($prop->getDeclaringClass()->getName() === $from->getName()) {
             $class->properties[$prop->getName()] = Property::from($prop);
         }
     }
     foreach ($from->getMethods() as $method) {
         if ($method->getDeclaringClass()->getName() === $from->getName()) {
             $class->methods[$method->getName()] = Method::from($method)->setNamespace($class->namespace);
         }
     }
     return $class;
 }
 public function saveLangueList($con = null)
 {
     if (!$this->isValid()) {
         throw $this->getErrorSchema();
     }
     if (!isset($this->widgetSchema['langue_list'])) {
         // somebody has unset this widget
         return;
     }
     if (null === $con) {
         $con = $this->getConnection();
     }
     $existing = $this->object->Langue->getPrimaryKeys();
     $values = $this->getValue('langue_list');
     if (!is_array($values)) {
         $values = array();
     }
     $unlink = array_diff($existing, $values);
     if (count($unlink)) {
         $this->object->unlink('Langue', array_values($unlink));
         $delete_log = new DeleteLog();
         $delete_log->setGuid(Guid::generate());
         $delete_log->setExtra('exposition_visiteurneeds_id: "' . $this->getObject()->getGuid() . '"|langue_id: "' . implode('", "', array_values($unlink)) . '"');
         $delete_log->setModelName('LangueExpositionVisiteurNeeds');
         $delete_log->save();
     }
     $link = array_diff($values, $existing);
     if (count($link)) {
         $this->object->link('Langue', array_values($link));
     }
 }
 /**
  * Restores all static attributes in user-defined classes from this snapshot.
  *
  * @param Snapshot $snapshot
  */
 public function restoreStaticAttributes(Snapshot $snapshot)
 {
     $current = new Snapshot($snapshot->blacklist(), false, false, false, false, true, false, false, false, false);
     $newClasses = array_diff($current->classes(), $snapshot->classes());
     unset($current);
     foreach ($snapshot->staticAttributes() as $className => $staticAttributes) {
         foreach ($staticAttributes as $name => $value) {
             $reflector = new ReflectionProperty($className, $name);
             $reflector->setAccessible(true);
             $reflector->setValue($value);
         }
     }
     foreach ($newClasses as $className) {
         $class = new \ReflectionClass($className);
         $defaults = $class->getDefaultProperties();
         foreach ($class->getProperties() as $attribute) {
             if (!$attribute->isStatic()) {
                 continue;
             }
             $name = $attribute->getName();
             if ($snapshot->blacklist()->isStaticAttributeBlacklisted($className, $name)) {
                 continue;
             }
             if (!isset($defaults[$name])) {
                 continue;
             }
             $attribute->setAccessible(true);
             $attribute->setValue($defaults[$name]);
         }
     }
 }
Example #17
0
 public function add()
 {
     $tabelas = array_intersect(parent::$dev['tabelas'], parent::$homolog['tabelas']);
     $string = $stringResult = "";
     if (!empty($tabelas)) {
         $propriedade = new PropriedadeBO();
         parent::$fase = FaseQuery::ADD;
         foreach ($tabelas as $tabelaInput) {
             list(parent::$schema, parent::$tabela) = explode(".", $tabelaInput);
             $schema = parent::$schema;
             $tabela = parent::$tabela;
             if (isset(parent::$dev['schema'][$schema]['tabela'][$tabela]['coluna'])) {
                 $dev = array_keys(parent::$dev['schema'][$schema]['tabela'][$tabela]['coluna']);
             }
             if (isset(parent::$homolog['schema'][$schema]['tabela'][$tabela]['coluna'])) {
                 $homolog = array_keys(parent::$homolog['schema'][$schema]['tabela'][$tabela]['coluna']);
             }
             $colunas = array_diff($dev, $homolog);
             if (!empty($colunas)) {
                 $stringResult = "\n\n\n" . str_pad(" ADD COLUMN ", 100, "-", STR_PAD_BOTH);
                 foreach ($colunas as $coluna) {
                     parent::$coluna = $coluna;
                     $string .= "\n\nALTER TABLE {$schema}.{$tabela} ADD COLUMN {$coluna} ";
                     $string .= $propriedade->construct() . ";";
                 }
             }
         }
     }
     return $stringResult . $string;
 }
Example #18
0
 /** Update the labels given a projectid and userid */
 public function UpdateLabels($labels)
 {
     if (!$this->ProjectId) {
         echo 'LabelEmail UpdateLabels(): ProjectId not set';
         return false;
     }
     if (!$this->UserId) {
         echo 'LabelEmail UpdateLabels(): UserId not set';
         return false;
     }
     if (!$labels) {
         $labels = array();
     }
     $existinglabels = $this->GetLabels();
     $toremove = array_diff($existinglabels, $labels);
     $toadd = array_diff($labels, $existinglabels);
     foreach ($toremove as $id) {
         $this->LabelId = $id;
         $this->Remove();
     }
     foreach ($toadd as $id) {
         $this->LabelId = $id;
         $this->Insert();
     }
     return true;
 }
Example #19
0
 protected function loadAll()
 {
     $files = array_diff(scandir(JS_PATH . 'classes/'), array('..', '.'));
     foreach ($files as $file) {
         $this->template .= file_get_contents(JS_PATH . 'classes/' . $file);
     }
 }
 /**
  * Saves the edited stop word list to Solr
  *
  * @return void
  */
 public function saveStopWordsAction()
 {
     $solrConnection = $this->getSelectedCoreSolrConnection();
     $postParameters = GeneralUtility::_POST('tx_solr_tools_solradministration');
     // lowercase stopword before saving because terms get lowercased before stopword filtering
     $newStopWords = $this->stringUtility->toLower($postParameters['stopWords']);
     $newStopWords = GeneralUtility::trimExplode("\n", $newStopWords, true);
     $oldStopWords = $solrConnection->getStopWords();
     $wordsRemoved = true;
     $removedStopWords = array_diff($oldStopWords, $newStopWords);
     foreach ($removedStopWords as $word) {
         $response = $solrConnection->deleteStopWord($word);
         if ($response->getHttpStatus() != 200) {
             $wordsRemoved = false;
             $this->addFlashMessage('Failed to remove stop word "' . $word . '".', 'An error occurred', FlashMessage::ERROR);
             break;
         }
     }
     $wordsAdded = true;
     $addedStopWords = array_diff($newStopWords, $oldStopWords);
     if (!empty($addedStopWords)) {
         $wordsAddedResponse = $solrConnection->addStopWords($addedStopWords);
         $wordsAdded = $wordsAddedResponse->getHttpStatus() == 200;
     }
     $reloadResponse = $solrConnection->reloadCore();
     if ($wordsRemoved && $wordsAdded && $reloadResponse->getHttpStatus() == 200) {
         $this->addFlashMessage('Stop Words Updated.');
     }
     $this->forwardToIndex();
 }
 public function getValueForTransaction()
 {
     $new = parent::getValueForTransaction();
     if (!$this->getUseEdgeTransactions()) {
         return $new;
     }
     $old = $this->getInitialValue();
     if ($old === null) {
         return array('=' => array_fuse($new));
     }
     // If we're building an edge transaction and the request has data about the
     // original value the user saw when they loaded the form, interpret the
     // edit as a mixture of "+" and "-" operations instead of a single "="
     // operation. This limits our exposure to race conditions by making most
     // concurrent edits merge correctly.
     $add = array_diff($new, $old);
     $rem = array_diff($old, $new);
     $value = array();
     if ($add) {
         $value['+'] = array_fuse($add);
     }
     if ($rem) {
         $value['-'] = array_fuse($rem);
     }
     return $value;
 }
Example #22
0
 /**
  * Determine whether or not the request is cacheable.
  * @param $request PKPRequest
  * @param $testOnly boolean required for unit test to
  *  bypass session check.
  * @return boolean
  */
 function isCacheable($request, $testOnly = false)
 {
     if (defined('SESSION_DISABLE_INIT') && !$testOnly) {
         return false;
     }
     if (!Config::getVar('general', 'installed')) {
         return false;
     }
     if (!empty($_POST) || Validation::isLoggedIn()) {
         return false;
     }
     if ($request->isPathInfoEnabled()) {
         if (!empty($_GET)) {
             return false;
         }
     } else {
         $application = $this->getApplication();
         $ok = array_merge($application->getContextList(), array('page', 'op', 'path'));
         if (!empty($_GET) && count(array_diff(array_keys($_GET), $ok)) != 0) {
             return false;
         }
     }
     if (in_array($this->getRequestedPage($request), $this->getCacheablePages())) {
         return true;
     }
     return false;
 }
 public function getApiForTesting()
 {
     $dateTime = self::$fixture->dateTime;
     $idSite1 = self::$fixture->idSite1;
     // NOTE: copied from TwoVisitors_TwoWebsites_DifferentDays (including the test or inheriting means
     // the test will get run by phpunit, even when we only want to run this one. should be put into
     // non-test class later.)
     $apiToCall = $this->getApiToCall();
     $singlePeriodApi = array('VisitsSummary.get', 'Goals.get');
     $periods = array('day', 'week', 'month', 'year');
     $result = array();
     // Live output for a quick visualisation if some other API test break
     $result[] = array('Live.getLastVisitsDetails', array('idSite' => self::$fixture->idSite1, 'date' => $dateTime, 'periods' => 'year', 'keepLiveDates' => true, 'otherRequestParameters' => array('showColumns' => 'lastActionDateTime,referrerType,referrerName,actions,events,visitConverted')));
     // Request data for the last 6 periods and idSite=all
     $result[] = array($apiToCall, array('idSite' => 'all', 'date' => $dateTime, 'periods' => $periods, 'setDateLastN' => true));
     // Request data for the last 6 periods and idSite=1
     $result[] = array($apiToCall, array('idSite' => $idSite1, 'date' => $dateTime, 'periods' => $periods, 'setDateLastN' => true, 'testSuffix' => '_idSiteOne_'));
     // We also test a single period to check that this use case (Reports per idSite in the response) works
     $result[] = array($singlePeriodApi, array('idSite' => 'all', 'date' => $dateTime, 'periods' => array('day', 'month'), 'setDateLastN' => false, 'testSuffix' => '_NotLastNPeriods'));
     // testing metadata API for multiple periods
     $apiToCall = array_diff($apiToCall, array('Actions.getPageTitle', 'Actions.getPageUrl'));
     foreach ($apiToCall as $api) {
         list($apiModule, $apiAction) = explode(".", $api);
         $result[] = array('API.getProcessedReport', array('idSite' => $idSite1, 'date' => $dateTime, 'periods' => array('day'), 'setDateLastN' => true, 'apiModule' => $apiModule, 'apiAction' => $apiAction, 'testSuffix' => '_' . $api . '_firstSite_lastN'));
     }
     // Tests that getting a visits summary metric (nb_visits) & a Goal's metric (Goal_revenue)
     // at the same time works.
     $dateTimeRange = '2010-01-03,2010-01-06';
     $columns = 'nb_visits,' . Archiver::getRecordName('conversion_rate');
     $result[] = array('VisitsSummary.get', array('idSite' => 'all', 'date' => $dateTimeRange, 'periods' => 'range', 'otherRequestParameters' => array('columns' => $columns), 'testSuffix' => '_getMetricsFromDifferentReports'));
     return $result;
 }
Example #24
0
 /**
  * @param $type
  * @return array
  */
 public function getPluginIds($type)
 {
     $pluginsDirs = false;
     $config = \code_review::getConfig();
     switch ($type) {
         case self::T_PLUGINS_INACTIVE:
             $pluginsDirs = $this->getPluginIds(self::T_PLUGINS_ALL);
             $actives = call_user_func($config['plugins_getter'], 'active');
             foreach ($actives as $plugin) {
                 if ($plugin instanceof \ElggPlugin) {
                     $pluginsDirs = array_diff($pluginsDirs, array($plugin->getID()));
                 } else {
                     $pluginsDirs = array_diff($pluginsDirs, array($plugin));
                 }
             }
             break;
         case self::T_PLUGINS_ACTIVE:
             $pluginsDirs = call_user_func($config['plugins_getter'], 'active');
             foreach ($pluginsDirs as $key => $plugin) {
                 if ($plugin instanceof \ElggPlugin) {
                     $pluginsDirs[$key] = $plugin->getID();
                 }
             }
             break;
         case self::T_PLUGINS_ALL:
             $pluginsDirs = \code_review::getPluginDirsInDir($config['pluginspath']);
             break;
     }
     return $pluginsDirs;
 }
 public function saveRelIdentPerspectivesList($con = null)
 {
     if (!$this->isValid()) {
         throw $this->getErrorSchema();
     }
     if (!isset($this->widgetSchema['rel_ident_perspectives_list'])) {
         // somebody has unset this widget
         return;
     }
     if (is_null($con)) {
         $con = $this->getConnection();
     }
     $existing = $this->object->RelIdentPerspectives->getPrimaryKeys();
     $values = $this->getValue('rel_ident_perspectives_list');
     if (!is_array($values)) {
         $values = array();
     }
     $unlink = array_diff($existing, $values);
     if (count($unlink)) {
         $this->object->unlink('RelIdentPerspectives', array_values($unlink));
     }
     $link = array_diff($values, $existing);
     if (count($link)) {
         $this->object->link('RelIdentPerspectives', array_values($link));
     }
 }
Example #26
0
 /**
  * Attempt to quickly set the specified customer activation status
  *
  * @param array $customerIds
  * @param int $value
  * @return $this
  */
 public function massSetActivationStatus(array $customerIds, $value)
 {
     $customerIds = $this->_getValidCustomerIds($customerIds);
     $changeIds = array();
     if ($customerIds) {
         $attribute = $this->getAttribute('customer_activated');
         $table = $attribute->getBackend()->getTable();
         $select = $this->getReadConnection()->select()->from($table, 'entity_id')->where('entity_id IN (?)', $customerIds)->where('attribute_id = ?', $attribute->getId())->where('value = ?', $value);
         $noChangeIds = $this->_getReadAdapter()->fetchCol($select);
         $changeIds = array_diff($customerIds, $noChangeIds);
         $select = $this->_getReadAdapter()->select()->from($table, 'entity_id')->where('entity_id IN (?)', $changeIds)->where('attribute_id = ?', $attribute->getId());
         $updateIds = $this->_getReadAdapter()->fetchCol($select);
         $insertIds = array_diff($changeIds, $updateIds);
         if ($updateIds) {
             $cond = $this->_getWriteAdapter()->quoteInto('entity_type_id = ?', $this->getEntityType()->getId());
             $cond .= $this->_getWriteAdapter()->quoteInto(' AND attribute_id = ?', $attribute->getId());
             $cond .= $this->_getWriteAdapter()->quoteInto(' AND entity_id IN (?)', $updateIds);
             $this->_getWriteAdapter()->update($table, array('value' => $value), $cond);
         }
         if ($insertIds) {
             $rows = array();
             foreach ($insertIds as $customerId) {
                 $rows[] = array('entity_type_id' => $this->getEntityType()->getId(), 'attribute_id' => $attribute->getId(), 'entity_id' => $customerId, 'value' => $value);
             }
             $this->_getWriteAdapter()->insertMultiple($table, $rows);
         }
     }
     return $changeIds;
 }
 /**
  * Executes parent method parent::render(), creates deliveryset category tree,
  * passes data to Smarty engine and returns name of template file "deliveryset_main.tpl".
  *
  * @return string
  */
 public function render()
 {
     $myConfig = $this->getConfig();
     parent::render();
     $soxId = $this->_aViewData["oxid"] = $this->getEditObjectId();
     if ($soxId != "-1" && isset($soxId)) {
         // load object
         $odeliveryset = oxNew("oxdeliveryset");
         $odeliveryset->loadInLang($this->_iEditLang, $soxId);
         $oOtherLang = $odeliveryset->getAvailableInLangs();
         if (!isset($oOtherLang[$this->_iEditLang])) {
             // echo "language entry doesn't exist! using: ".key($oOtherLang);
             $odeliveryset->loadInLang(key($oOtherLang), $soxId);
         }
         $this->_aViewData["edit"] = $odeliveryset;
         // remove already created languages
         $aLang = array_diff(oxLang::getInstance()->getLanguageNames(), $oOtherLang);
         if (count($aLang)) {
             $this->_aViewData["posslang"] = $aLang;
         }
         foreach ($oOtherLang as $id => $language) {
             $oLang = new oxStdClass();
             $oLang->sLangDesc = $language;
             $oLang->selected = $id == $this->_iEditLang;
             $this->_aViewData["otherlang"][$id] = clone $oLang;
         }
     }
     if (oxConfig::getParameter("aoc")) {
         $aColumns = array();
         include_once 'inc/' . strtolower(__CLASS__) . '.inc.php';
         $this->_aViewData['oxajax'] = $aColumns;
         return "popups/deliveryset_main.tpl";
     }
     return "deliveryset_main.tpl";
 }
Example #28
0
 public function saveNoticeType()
 {
     $postdata = input::get('notice');
     foreach ($postdata as $key => $value) {
         if ($value == '') {
             $msg = app::get('sysshop')->_('通知类型不能为空!');
             return $this->splash('error', null, $msg);
         }
     }
     $noticetype = app::get('sysshop')->getConf('shopnoticetype');
     if (count($noticetype) > count($postdata)) {
         $minustype = array_diff($noticetype, $postdata);
         $shopNoticeMdl = app::get('sysshop')->model('shop_notice');
         $minusTypeList = $shopNoticeMdl->getList('notice_id', array('notice_type' => $minustype));
         if ($minusTypeList) {
             $msg = app::get('sysshop')->_('该类型下面含有通知,请先删除通知再进行操作!');
             return $this->splash('error', null, $msg);
         }
         //echo '<pre>';print_r($minusTypeList);exit();
     }
     $result = app::get('sysshop')->setConf('shopnoticetype', $postdata);
     if ($result) {
         $msg = app::get('sysshop')->_('商家通知类型添加成功!');
         return $this->splash('success', null, $msg);
     } else {
         $msg = app::get('sysshop')->_('商家通知类型添加失败!');
         return $this->splash('error', null, $msg);
     }
 }
Example #29
0
 public function getTableData()
 {
     $colMap = array('id' => 'product_id', 'name' => 'pd.name', 'status' => 'mp.product_status', 'seller' => 'ms.nickname', 'date_created' => 'p.date_created', 'date_modified' => 'p.date_modified');
     $sorts = array('name', 'seller', 'date_created', 'date_modified', 'status');
     $filters = array_diff($sorts, array('status'));
     list($sortCol, $sortDir) = $this->MsLoader->MsHelper->getSortParams($sorts, $colMap);
     $filterParams = $this->MsLoader->MsHelper->getFilterParams($filters, $colMap);
     $sellers = $this->MsLoader->MsSeller->getSellers(array('seller_status' => array(MsSeller::STATUS_ACTIVE, MsSeller::STATUS_INACTIVE)), array('order_by' => 'ms.nickname', 'order_way' => 'ASC'));
     $results = $this->MsLoader->MsProduct->getProducts(array(), array('order_by' => $sortCol, 'order_way' => $sortDir, 'filters' => $filterParams, 'offset' => $this->request->get['iDisplayStart'], 'limit' => $this->request->get['iDisplayLength']));
     $total = isset($results[0]) ? $results[0]['total_rows'] : 0;
     $columns = array();
     foreach ($results as $result) {
         // image
         if ($result['p.image'] && file_exists(DIR_IMAGE . $result['p.image'])) {
             $image = $this->MsLoader->MsFile->resizeImage($result['p.image'], 40, 40);
         } else {
             $image = $this->MsLoader->MsFile->resizeImage('no_image.jpg', 40, 40);
         }
         // actions
         $actions = "";
         $actions .= "<a class='ms-button ms-button-edit' href='" . $this->url->link('catalog/product/update', 'token=' . $this->session->data['token'] . '&product_id=' . $result['product_id'], 'SSL') . "' title='" . $this->language->get('text_edit') . "'></a>";
         $actions .= "<a class='ms-button ms-button-delete' href='" . $this->url->link('multiseller/product/delete', 'token=' . $this->session->data['token'] . '&product_id=' . $result['product_id'], 'SSL') . "' title='" . $this->language->get('ms_delete') . "'></a>";
         // seller select
         $sellerselect = "";
         $sellerselect .= "\r\n\t\t\t<select>\r\n\t\t\t\t<option value='0'>" . $this->language->get('ms_catalog_products_noseller') . "</option>";
         foreach ($sellers as $s) {
             $sellerselect .= "<option value='{$s['seller_id']}'" . ($s['seller_id'] == $result['seller_id'] ? " selected='selected'" : "") . ">{$s['ms.nickname']}</option>";
         }
         $sellerselect .= "\r\n\t\t\t</select>\r\n\t\t\t<span class='ms-assign-seller' style='background-image: url(view/image/success.png); width: 16px; height: 16px; display: inline-block; cursor: pointer; vertical-align: middle' title='Save' />\r\n\t\t\t";
         $columns[] = array_merge($result, array('checkbox' => "<input type='checkbox' name='selected[]' value='{$result['product_id']}' />", 'image' => "<img src='{$image}' style='padding: 1px; border: 1px solid #DDDDDD' />", 'name' => $result['pd.name'], 'seller' => $sellerselect, 'status' => $result['mp.product_status'] ? $this->language->get('ms_product_status_' . $result['mp.product_status']) : '', 'date_created' => date($this->language->get('date_format_short'), strtotime($result['p.date_created'])), 'date_modified' => date($this->language->get('date_format_short'), strtotime($result['p.date_modified'])), 'actions' => $actions));
     }
     $this->response->setOutput(json_encode(array('iTotalRecords' => $total, 'iTotalDisplayRecords' => $total, 'aaData' => $columns)));
 }
 protected function doSave($con = null)
 {
     parent::doSave();
     $newOptions = $this->getValue('option');
     $newOptions = preg_split('/[\\s ]+/u', $newOptions, -1, PREG_SPLIT_NO_EMPTY);
     $voteQuestion = $this->getObject();
     // 過去の選択肢の抽出
     $oldOptions = $voteQuestion->getVoteQuestionOptions();
     $oldOptions = $oldOptions->toKeyValueArray('id', 'body');
     // 削除された選択肢の抽出
     $deletedOptions = array_diff($oldOptions, $newOptions);
     foreach ($deletedOptions as $id => $body) {
         // 削除
         $object = Doctrine::getTable('VoteQuestionOption')->find($id);
         $object->delete();
     }
     // 新規の選択肢
     $insertOptions = array_diff($newOptions, $oldOptions);
     foreach ($insertOptions as $body) {
         // 追加
         $object = new VoteQuestionOption();
         $object->setVoteQuestion($voteQuestion);
         $object->setBody($body);
         $object->save();
     }
 }