/** * @param string $file Absolut path to template file * @param array $params Variables for template */ public function __construct($file, $params) { $prefix = "main-"; $file = basename($file, '.php'); $file = self::$templatesDir . "/%s{$file}.php"; if (is_file(sprintf($file, $prefix))) { $file = sprintf($file, $prefix); } else { $prefix = ""; $file = sprintf($file, $prefix); } parent::__construct($file); $params['site'] = WpLatteSiteEntity::getInstance(); if (file_exists(self::$templatesDir . '/main-layout.php')) { $params['layout'] = 'main-layout.php'; } elseif (file_exists(self::$templatesDir . '/layout.php')) { $params['layout'] = 'layout.php'; } else { $params['layout'] = '@layout.php'; } $params['headerNotCalled'] = did_action('get_header') == 0; $params['footerNotCalled'] = did_action('get_footer') == 0; $params['sidebarNotCalled'] = did_action('get_sidebar') == 0; $this->setParams($params); $this->registerHelperLoader('NTemplateHelpers::loader'); $this->registerHelper("printf", "sprintf"); $this->setCacheStorage(new NPhpFileStorage(realpath(self::$cacheDir))); $this->onPrepareFilters[] = create_function('$template', ' $engine = new NLatteFilter(); WpLatteMacros::install($engine->parser); $template->registerFilter($engine); '); }
function scoper_mu_site_menu() { if (!is_option_administrator_rs()) { return; } $path = SCOPER_ABSPATH; $name = awp_ver('3.1') ? 'sites' : 'ms-admin'; // RS Site Options add_submenu_page("{$name}.php", __('Role Scoper Options', 'scoper'), __('Role Options', 'scoper'), 'read', 'rs-site_options'); $func = "include_once('{$path}' . '/admin/options.php');scoper_options( true );"; add_action("{$name}_page_rs-site_options", create_function('', $func)); global $scoper_default_options, $scoper_options_sitewide; // omit Option Defaults menu item if all options are controlled sitewide if (empty($scoper_default_options)) { scoper_refresh_default_options(); } if (count($scoper_options_sitewide) != count($scoper_default_options)) { // RS Default Options (for per-blog settings) add_submenu_page("{$name}.php", __('Role Scoper Option Defaults', 'scoper'), __('Role Defaults', 'scoper'), 'read', 'rs-default_options'); $func = "include_once('{$path}' . '/admin/options.php');scoper_options( false, true );"; add_action("{$name}_page_rs-default_options", create_function('', $func)); } // satisfy WordPress' demand that all admin links be properly defined in menu if ('rs-attachments_utility' == $GLOBALS['plugin_page_cr']) { add_submenu_page("{$name}.php", __('Attachment Utility', 'scoper'), __('Attachment Utility', 'scoper'), 'read', 'rs-attachments_utility', array($GLOBALS['scoper_admin'], 'menu_handler')); } }
/** * Checks if query allowed. * * Perform testing if table exist for DROP TABLE query * to avoid stoping execution while try to drop not existent table. * * @param ezcDbHandler $db * @param string $query * * @return boolean false if query should not be executed. */ public function isQueryAllowed(ezcDbHandler $db, $query) { if (strstr($query, 'AUTO_INCREMENT')) { return false; } if (substr($query, 0, 10) == 'DROP TABLE') { $tableName = substr($query, strlen('DROP TABLE "'), -1); // get table name without quotes $result = $db->query("SELECT count( table_name ) AS count FROM user_tables WHERE table_name='{$tableName}'")->fetchAll(); if ($result[0]['count'] == 1) { $sequences = $db->query("SELECT sequence_name FROM user_sequences")->fetchAll(); array_walk($sequences, create_function('&$item,$key', '$item = $item[0];')); foreach ($sequences as $sequenceName) { // try to drop sequences related to dropped table. if (substr($sequenceName, 0, strlen($tableName)) == $tableName) { $db->query("DROP SEQUENCE \"{$sequenceName}\""); } } return true; } else { return false; } } return true; }
/** * Constructor. */ function CreateReviewerForm($sectionId) { parent::Form('sectionEditor/createReviewerForm.tpl'); $this->addCheck(new FormValidatorPost($this)); $site =& Request::getSite(); $this->sectionId = $sectionId; // Validation checks for this form $this->addCheck(new FormValidator($this, 'username', 'required', 'user.profile.form.usernameRequired')); $this->addCheck(new FormValidatorCustom($this, 'username', 'required', 'user.register.form.usernameExists', array(DAORegistry::getDAO('UserDAO'), 'userExistsByUsername'), array(null, true), true)); $this->addCheck(new FormValidatorAlphaNum($this, 'username', 'required', 'user.register.form.usernameAlphaNumeric')); $this->addCheck(new FormValidator($this, 'firstName', 'required', 'user.profile.form.firstNameRequired')); $this->addCheck(new FormValidator($this, 'lastName', 'required', 'user.profile.form.lastNameRequired')); $this->addCheck(new FormValidatorUrl($this, 'userUrl', 'optional', 'user.profile.form.urlInvalid')); $this->addCheck(new FormValidatorEmail($this, 'email', 'required', 'user.profile.form.emailRequired')); $this->addCheck(new FormValidatorCustom($this, 'email', 'required', 'user.register.form.emailExists', array(DAORegistry::getDAO('UserDAO'), 'userExistsByEmail'), array(null, true), true)); $this->addCheck(new FormValidator($this, 'ercStatus', 'required', 'user.profile.form.ercStatusRequired')); $this->addCheck(new FormValidatorCustom($this, 'ercStatus', 'required', 'user.register.form.tooManyMembers', create_function('$ercStatus, $sectionId', ' $journal =& Request::getJournal(); if ($ercStatus == "Secretary"){ $sectionEditorsDao =& DAORegistry::getDAO(\'SectionEditorsDAO\'); $secretaries =& $sectionEditorsDao->getEditorsBySectionId($journal->getId(), $sectionId); if (count($secretaries)>4) return true; else return false;} else { $ercReviewersDao =& DAORegistry::getDAO(\'ErcReviewersDAO\'); if ($ercStatus == "Chair") { $chairs =& $ercReviewersDao->getReviewersBySectionIdByStatus($journal->getId(), $sectionId, 1); if (count($chairs) != 0) return true; else return false;} elseif ($ercStatus == "Vice-Chair"){ $vicechairs =& $ercReviewersDao->getReviewersBySectionIdByStatus($journal->getId(), $sectionId, 2); if (count($vicechairs) != 0) return true; else return false;} elseif ($ercStatus == "Member"){ $members =& $ercReviewersDao->getReviewersBySectionId($journal->getId(), $sectionId); if (count($members) > 19) return true; else return false;} return false;}'), array($this->sectionId), true)); // Provide a default for sendNotify: If we're using one-click // reviewer access or email-based reviews, it's not necessary; // otherwise, it should default to on. $journal =& Request::getJournal(); $reviewerAccessKeysEnabled = $journal->getSetting('reviewerAccessKeysEnabled'); $isEmailBasedReview = $journal->getSetting('mailSubmissionsToReviewers') == 1 ? true : false; $this->setData('sendNotify', $reviewerAccessKeysEnabled || $isEmailBasedReview ? false : true); }
/** * Deque test method. * * @param object IDeque $deque The deque to test. */ public static function test(IDeque $deque) { printf("AbstractDeque test program.\n"); for ($i = 0; $i <= 5; ++$i) { if (!$deque->isFull()) { $deque->enqueueHead(box($i)); } if (!$deque->isFull()) { $deque->enqueueTail(box($i)); } } printf("%s\n", str($deque)); printf("getHead = %s\n", str($deque->getHead())); printf("getTail = %s\n", str($deque->getTail())); printf("Using reduce\n"); $deque->reduce(create_function('$sum,$obj', 'printf("%s\\n", str($obj));'), ''); printf("Using foreach\n"); foreach ($deque as $obj) { printf("%s\n", str($obj)); } printf("Dequeueing\n"); while (!$deque->isEmpty()) { printf("%s\n", str($deque->dequeueHead())); if ($deque->isEmpty()) { break; } printf("%s\n", str($deque->dequeueTail())); } }
/** * Constructor */ public function __construct() { $remove = array_diff(array_keys($_GET), $this->baseUrlParamNames); if ($remove) { $this->baseUrl = remove_query_arg($remove); } else { $this->baseUrl = $_SERVER['REQUEST_URI']; } parent::__construct(); // add special filter for url fields $this->input->addFilter(create_function('$str', 'return "http://" == $str || "ftp://" == $str ? "" : $str;')); // enqueue required sripts and styles global $wp_styles; if (!is_a($wp_styles, 'WP_Styles')) { $wp_styles = new WP_Styles(); } wp_enqueue_style('pmwi-admin-style', PMWI_ROOT_URL . '/static/css/admin.css', array(), PMWI_VERSION); if (version_compare(get_bloginfo('version'), '3.8-RC1') >= 0) { wp_enqueue_style('pmwi-admin-style-wp-3.8', PMWI_ROOT_URL . '/static/css/admin-wp-3.8.css'); } wp_enqueue_script('pmwi-script', PMWI_ROOT_URL . '/static/js/pmwi.js', array('jquery')); wp_enqueue_script('pmwi-admin-script', PMWI_ROOT_URL . '/static/js/admin.js', array('jquery', 'jquery-ui-core', 'jquery-ui-resizable', 'jquery-ui-dialog', 'jquery-ui-datepicker', 'jquery-ui-draggable', 'jquery-ui-droppable', 'pmxi-admin-script'), PMWI_VERSION); global $woocommerce; $woocommerce_witepanel_params = array('remove_item_notice' => __("Remove this item? If you have previously reduced this item's stock, or this order was submitted by a customer, will need to manually restore the item's stock.", 'wpai_woocommerce_addon_plugin'), 'remove_attribute' => __('Remove this attribute?', 'wpai_woocommerce_addon_plugin'), 'name_label' => __('Name', 'wpai_woocommerce_addon_plugin'), 'remove_label' => __('Remove', 'wpai_woocommerce_addon_plugin'), 'click_to_toggle' => __('Click to toggle', 'wpai_woocommerce_addon_plugin'), 'values_label' => __('Value(s)', 'wpai_woocommerce_addon_plugin'), 'text_attribute_tip' => __('Enter some text, or some attributes by pipe (|) separating values.', 'wpai_woocommerce_addon_plugin'), 'visible_label' => __('Visible on the product page', 'wpai_woocommerce_addon_plugin'), 'used_for_variations_label' => __('Used for variations', 'wpai_woocommerce_addon_plugin'), 'new_attribute_prompt' => __('Enter a name for the new attribute term:', 'wpai_woocommerce_addon_plugin'), 'calc_totals' => __("Calculate totals based on order items, discount amount, and shipping? Note, you will need to (optionally) calculate tax rows and cart discounts manually.", 'wpai_woocommerce_addon_plugin'), 'calc_line_taxes' => __("Calculate line taxes? This will calculate taxes based on the customers country. If no billing/shipping is set it will use the store base country.", 'wpai_woocommerce_addon_plugin'), 'copy_billing' => __("Copy billing information to shipping information? This will remove any currently entered shipping information.", 'wpai_woocommerce_addon_plugin'), 'load_billing' => __("Load the customer's billing information? This will remove any currently entered billing information.", 'wpai_woocommerce_addon_plugin'), 'load_shipping' => __("Load the customer's shipping information? This will remove any currently entered shipping information.", 'wpai_woocommerce_addon_plugin'), 'featured_label' => __('Featured', 'wpai_woocommerce_addon_plugin'), 'tax_or_vat' => $woocommerce->countries->tax_or_vat(), 'prices_include_tax' => get_option('woocommerce_prices_include_tax'), 'round_at_subtotal' => get_option('woocommerce_tax_round_at_subtotal'), 'meta_name' => __('Meta Name', 'wpai_woocommerce_addon_plugin'), 'meta_value' => __('Meta Value', 'wpai_woocommerce_addon_plugin'), 'no_customer_selected' => __('No customer selected', 'wpai_woocommerce_addon_plugin'), 'tax_label' => __('Tax Label:', 'wpai_woocommerce_addon_plugin'), 'compound_label' => __('Compound:', 'wpai_woocommerce_addon_plugin'), 'cart_tax_label' => __('Cart Tax:', 'wpai_woocommerce_addon_plugin'), 'shipping_tax_label' => __('Shipping Tax:', 'wpai_woocommerce_addon_plugin'), 'plugin_url' => $woocommerce->plugin_url(), 'ajax_url' => admin_url('admin-ajax.php'), 'add_order_item_nonce' => wp_create_nonce("add-order-item"), 'add_attribute_nonce' => wp_create_nonce("add-attribute"), 'calc_totals_nonce' => wp_create_nonce("calc-totals"), 'get_customer_details_nonce' => wp_create_nonce("get-customer-details"), 'search_products_nonce' => wp_create_nonce("search-products"), 'calendar_image' => $woocommerce->plugin_url() . '/assets/images/calendar.png', 'post_id' => null); wp_localize_script('woocommerce_writepanel', 'woocommerce_writepanel_params', $woocommerce_witepanel_params); wp_enqueue_style('pmwi-woo-style', $woocommerce->plugin_url() . '/assets/css/admin.css'); }
/** * Constructor. */ function __construct($site) { parent::__construct('frontend/pages/userRegister.tpl'); // Validation checks for this form $this->addCheck(new FormValidatorCustom($this, 'username', 'required', 'user.register.form.usernameExists', array(DAORegistry::getDAO('UserDAO'), 'userExistsByUsername'), array(), true)); $this->addCheck(new FormValidator($this, 'username', 'required', 'user.profile.form.usernameRequired')); $this->addCheck(new FormValidator($this, 'password', 'required', 'user.profile.form.passwordRequired')); $this->addCheck(new FormValidatorUsername($this, 'username', 'required', 'user.register.form.usernameAlphaNumeric')); $this->addCheck(new FormValidatorLength($this, 'password', 'required', 'user.register.form.passwordLengthRestriction', '>=', $site->getMinPasswordLength())); $this->addCheck(new FormValidatorCustom($this, 'password', 'required', 'user.register.form.passwordsDoNotMatch', create_function('$password,$form', 'return $password == $form->getData(\'password2\');'), array(&$this))); $this->addCheck(new FormValidator($this, 'firstName', 'required', 'user.profile.form.firstNameRequired')); $this->addCheck(new FormValidator($this, 'lastName', 'required', 'user.profile.form.lastNameRequired')); $this->addCheck(new FormValidator($this, 'country', 'required', 'user.profile.form.countryRequired')); // Email checks $this->addCheck(new FormValidatorEmail($this, 'email', 'required', 'user.profile.form.emailRequired')); $this->addCheck(new FormValidatorCustom($this, 'email', 'required', 'user.register.form.emailExists', array(DAORegistry::getDAO('UserDAO'), 'userExistsByEmail'), array(), true)); $this->captchaEnabled = Config::getVar('captcha', 'captcha_on_register') && Config::getVar('captcha', 'recaptcha'); if ($this->captchaEnabled) { $this->addCheck(new FormValidatorReCaptcha($this, Request::getRemoteAddr(), 'common.captcha.error.invalid-input-response')); } $authDao = DAORegistry::getDAO('AuthSourceDAO'); $this->defaultAuth = $authDao->getDefaultPlugin(); if (isset($this->defaultAuth)) { $this->addCheck(new FormValidatorCustom($this, 'username', 'required', 'user.register.form.usernameExists', create_function('$username,$form,$auth', 'return (!$auth->userExists($username) || $auth->authenticate($username, $form->getData(\'password\')));'), array(&$this, $this->defaultAuth))); } $this->addCheck(new FormValidatorPost($this)); $this->addCheck(new FormValidatorCSRF($this)); }
public function actionIndex($oid) { $jobs = Jobs::model()->findAll('office_id = :office_id', array(':office_id' => $oid)); $jobs = array_map(create_function('&$item', 'if(isset($item->description) && strlen($item->description) > 600) $item->description = mb_substr($item->description, 0, 600, "utf-8")."..."; return $item;'), $jobs); Yii::app()->clientScript->registerScript('global_office_id', 'var glOfficeId = ' . $oid . ';', CClientScript::POS_HEAD); $this->render('/office/jobs/index', array('jobs' => $jobs, 'my_office' => $this->checkMyOffice($oid))); }
protected static function _getData() { if (count(self::$_dateRange) === 0) { $yesterdayLocal = new UDate('now', 'Australia/Melbourne'); $yesterdayLocal->modify('-1 day'); $fromDate = new UDate($yesterdayLocal->format('Y-m-d') . ' 00:00:00', 'Australia/Melbourne'); $fromDate->setTimeZone('UTC'); $toDate = new UDate($yesterdayLocal->format('Y-m-d') . ' 23:59:59', 'Australia/Melbourne'); $toDate->setTimeZone('UTC'); } else { $fromDate = self::$_dateRange['start']; $toDate = self::$_dateRange['end']; } self::$_fromDate = $fromDate; self::$_toDate = $toDate; $orders = Order::getAllByCriteria('invDate >= :fromDate and invDate <= :toDate', array('fromDate' => trim($fromDate), 'toDate' => trim($toDate))); $return = array(); foreach ($orders as $order) { //common fields $customer = $order->getCustomer(); $creditNotes = CreditNote::getAllByCriteria('orderId = ?', array($order->getId())); $row = array('Invoice No.' => $order->getInvNo(), 'Invoice Date' => $order->getInvDate()->setTimeZone('Australia/Melbourne')->__toString(), 'Order No.' => $order->getOrderNo(), 'Order Date' => $order->getOrderDate()->setTimeZone('Australia/Melbourne')->__toString(), 'PO No.' => $order->getPONo(), 'Customer Name' => $customer->getName(), 'Customer Ph.' => $customer->getContactNo(), 'Customer Email' => $customer->getEmail(), 'Status' => $order->getStatus()->getName(), 'Total Amt.' => StringUtilsAbstract::getCurrency($order->getTotalAmount()), 'Total Paid' => StringUtilsAbstract::getCurrency($order->getTotalPaid()), 'Total Credited' => StringUtilsAbstract::getCurrency($order->getTotalCreditNoteValue()), 'Total Due' => StringUtilsAbstract::getCurrency($order->getTotalAmount() - $order->getTotalPaid() - $order->getTotalCreditNoteValue()), 'CreditNote Nos.' => implode(', ', array_map(create_function('$a', 'return $a->getCreditNoteNo();'), $creditNotes))); $return[] = $row; } return $return; }
protected function cleanupTables() { switch ($this->db->getName()) { case 'pgsql': $tables = $this->db->query("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'")->fetchAll(); array_walk($tables, create_function('&$item,$key', '$item = $item[0];')); foreach ($tables as $tableName) { $this->db->query("DROP TABLE \"{$tableName}\""); } break; case 'oracle': $tables = $this->db->query("SELECT table_name FROM user_tables")->fetchAll(); array_walk($tables, create_function('&$item,$key', '$item = $item[0];')); foreach ($tables as $tableName) { $this->db->query("DROP TABLE \"{$tableName}\""); } $sequences = $this->db->query("SELECT sequence_name FROM user_sequences")->fetchAll(); array_walk($sequences, create_function('&$item,$key', '$item = $item[0];')); foreach ($sequences as $sequenceName) { $this->db->query("DROP SEQUENCE \"{$sequenceName}\""); } break; default: $this->db->exec('DROP TABLE IF EXISTS workflow;'); $this->db->exec('DROP TABLE IF EXISTS node;'); $this->db->exec('DROP TABLE IF EXISTS node_connection;'); $this->db->exec('DROP TABLE IF EXISTS variable_handler;'); $this->db->exec('DROP TABLE IF EXISTS execution;'); $this->db->exec('DROP TABLE IF EXISTS execution_state;'); } }
public function __construct($config, $destination) { date_default_timezone_set('UTC'); $this->destination = $destination; foreach ($this->mandatoryConfigColumns as $c) { if (!isset($config[$c])) { throw new Exception("Mandatory column '{$c}' not found or empty."); } $this->config[$c] = $config[$c]; } foreach (array('start_date', 'end_date') as $dateId) { $timestamp = strtotime($this->config[$dateId]); if ($timestamp === FALSE) { throw new Exception("Invalid time value in field " . $dateId); } $dateTime = new DateTime(); $dateTime->setTimestamp($timestamp); $this->config[$dateId] = $dateTime->format('Y-m-d'); } if (!is_array($this->config['queries'])) { throw new Exception("You have to put some queries in queries list."); } // API initialization $this->api = new RestClient(array('base_url' => "https://www.zuora.com/apps", 'headers' => array('Accept' => 'application/json', 'Content-Type' => 'application/json'), 'username' => $this->config['username'], 'password' => $this->config['#password'])); $this->api->register_decoder('json', create_function('$a', "return json_decode(\$a, TRUE);")); }
/** * Constructor * @param buyerUserId int */ function GiftIndividualSubscriptionForm($request, $buyerUserId = null) { parent::Form('subscription/giftIndividualSubscriptionForm.tpl'); $this->buyerUserId = isset($buyerUserId) ? (int) $buyerUserId : null; $this->request =& $request; $journal =& $this->request->getJournal(); $journalId = $journal->getId(); $subscriptionTypeDao =& DAORegistry::getDAO('SubscriptionTypeDAO'); $subscriptionTypes =& $subscriptionTypeDao->getSubscriptionTypesByInstitutional($journalId, false, false); $this->subscriptionTypes =& $subscriptionTypes->toArray(); // Require buyer and recipient names and emails $this->addCheck(new FormValidator($this, 'buyerFirstName', 'required', 'user.profile.form.firstNameRequired')); $this->addCheck(new FormValidator($this, 'buyerLastName', 'required', 'user.profile.form.lastNameRequired')); $this->addCheck(new FormValidatorEmail($this, 'buyerEmail', 'required', 'user.profile.form.emailRequired')); $this->addCheck(new FormValidatorCustom($this, 'buyerEmail', 'required', 'user.register.form.emailsDoNotMatch', create_function('$buyerEmail,$form', 'return $buyerEmail == $form->getData(\'confirmBuyerEmail\');'), array(&$this))); $this->addCheck(new FormValidator($this, 'recipientFirstName', 'required', 'user.profile.form.firstNameRequired')); $this->addCheck(new FormValidator($this, 'recipientLastName', 'required', 'user.profile.form.lastNameRequired')); $this->addCheck(new FormValidatorEmail($this, 'recipientEmail', 'required', 'user.profile.form.emailRequired')); $this->addCheck(new FormValidatorCustom($this, 'recipientEmail', 'required', 'user.register.form.emailsDoNotMatch', create_function('$recipientEmail,$form', 'return $recipientEmail == $form->getData(\'confirmRecipientEmail\');'), array(&$this))); // Require gift note title and note from buyer $this->addCheck(new FormValidator($this, 'giftNoteTitle', 'required', 'gifts.noteTitleRequired')); $this->addCheck(new FormValidator($this, 'giftNote', 'required', 'gifts.noteRequired')); // Ensure subscription type is valid $this->addCheck(new FormValidatorCustom($this, 'typeId', 'required', 'user.subscriptions.form.typeIdValid', create_function('$typeId, $journalId', '$subscriptionTypeDao =& DAORegistry::getDAO(\'SubscriptionTypeDAO\'); return ($subscriptionTypeDao->subscriptionTypeExistsByTypeId($typeId, $journalId) && $subscriptionTypeDao->getSubscriptionTypeInstitutional($typeId) == 0) && $subscriptionTypeDao->getSubscriptionTypeDisablePublicDisplay($typeId) == 0;'), array($journal->getId()))); // Ensure a locale is provided and valid $this->addCheck(new FormValidator($this, 'giftLocale', 'required', 'gifts.localeRequired'), create_function('$giftLocale, $availableLocales', 'return in_array($giftLocale, $availableLocales);'), array_keys($journal->getSupportedLocaleNames())); // Form was POSTed $this->addCheck(new FormValidatorPost($this)); }
/** * Helper function - filter the contents of the * selectors and return the resulting unix timestamp. * * @param $field_value * @return int Unix timestamp */ function _get_timestamp_value($field_value) { $second = 0; $filtered_values = array_map(create_function('$item', 'return (int)$item;'), $field_value); extract($filtered_values, EXTR_OVERWRITE); return mktime($hour, $minute, $second, $month, $day, $year); }
function xgettext($project, $dir, $output_file, $placeholders = array(), $excludes = array(), $includes = array()) { $meta = array_merge($this->meta['default'], $this->meta[$project]); $placeholders = array_merge($meta, $placeholders); $meta['output'] = $this->realpath_missing($output_file); $placeholders['year'] = date('Y'); $placeholder_keys = array_map(create_function('$x', 'return "{".$x."}";'), array_keys($placeholders)); $placeholder_values = array_values($placeholders); foreach ($meta as $key => $value) { $meta[$key] = str_replace($placeholder_keys, $placeholder_values, $value); } $originals = $this->extractor->extract_from_directory($dir, $excludes, $includes); $pot = new PO(); $pot->entries = $originals->entries; $pot->set_header('Project-Id-Version', $meta['package-name'] . ' ' . $meta['package-version']); $pot->set_header('Report-Msgid-Bugs-To', $meta['msgid-bugs-address']); $pot->set_header('POT-Creation-Date', gmdate('Y-m-d H:i:s+00:00')); $pot->set_header('MIME-Version', '1.0'); $pot->set_header('Content-Type', 'text/plain; charset=UTF-8'); $pot->set_header('Content-Transfer-Encoding', '8bit'); $pot->set_header('PO-Revision-Date', date('Y') . '-MO-DA HO:MI+ZONE'); $pot->set_header('Last-Translator', 'FULL NAME <EMAIL@ADDRESS>'); $pot->set_header('Language-Team', 'LANGUAGE <*****@*****.**>'); $pot->set_comment_before_headers($meta['comments']); $pot->export_to_file($output_file); return true; }
public function dump_export_data() { if ($this->exporter->get('viewexportmode') == PluginExport::EXPORT_LIST_OF_VIEWS && $this->exporter->get('artefactexportmode') == PluginExport::EXPORT_ARTEFACTS_FOR_VIEWS) { // Dont' care about profile information in this case return; } $smarty = $this->exporter->get_smarty('../../', 'internal'); $smarty->assign('page_heading', get_string('profilepage', 'artefact.internal')); // Profile page $profileviewid = $this->exporter->get('user')->get_profile_view()->get('id'); foreach ($this->exporter->get('views') as $viewid => $view) { if ($profileviewid == $viewid) { $smarty->assign('breadcrumbs', array(array('text' => 'Profile page', 'path' => 'profilepage.html'))); $view = $this->exporter->get('user')->get_profile_view(); $outputfilter = new HtmlExportOutputFilter('../../'); $smarty->assign('view', $outputfilter->filter($view->build_columns())); $content = $smarty->fetch('export:html/internal:profilepage.tpl'); if (!file_put_contents($this->fileroot . 'profilepage.html', $content)) { throw new SystemException("Unable to write profile page"); } $this->profileviewexported = true; break; } } // Generic profile information $smarty->assign('page_heading', get_string('profileinformation', 'artefact.internal')); $smarty->assign('breadcrumbs', array(array('text' => 'Profile information', 'path' => 'index.html'))); // Organise profile information by sections, ordered how it's ordered // on the 'edit profile' page $sections = array('aboutme' => array(), 'contact' => array(), 'messaging' => array(), 'general' => array()); $elementlist = call_static_method('ArtefactTypeProfile', 'get_all_fields'); $elementlistlookup = array_flip(array_keys($elementlist)); $profilefields = get_column_sql('SELECT id FROM {artefact} WHERE owner=? AND artefacttype IN (' . join(",", array_map(create_function('$a', 'return db_quote($a);'), array_keys($elementlist))) . ")", array($this->exporter->get('user')->get('id'))); foreach ($profilefields as $id) { $artefact = artefact_instance_from_id($id); $rendered = $artefact->render_self(array('link' => true)); if ($artefact->get('artefacttype') == 'introduction') { $outputfilter = new HtmlExportOutputFilter('../../'); $rendered['html'] = $outputfilter->filter($rendered['html']); } $sections[$this->get_category_for_artefacttype($artefact->get('artefacttype'))][$artefact->get('artefacttype')] = array('html' => $rendered['html'], 'weight' => $elementlistlookup[$artefact->get('artefacttype')]); } // Sort the data and then drop the weighting information foreach ($sections as &$section) { uasort($section, create_function('$a, $b', 'return $a["weight"] > $b["weight"];')); foreach ($section as &$data) { $data = $data['html']; } } $smarty->assign('sections', $sections); $iconid = $this->exporter->get('user')->get('profileicon'); if ($iconid) { $icon = artefact_instance_from_id($iconid); $smarty->assign('icon', '<img src="../../static/profileicons/200px-' . PluginExportHtml::sanitise_path($icon->get('title')) . '" alt="Profile Icon">'); } $content = $smarty->fetch('export:html/internal:index.tpl'); if (!file_put_contents($this->fileroot . 'index.html', $content)) { throw new SystemException("Unable to write profile information page"); } }
function authorize($request, &$args, $roleAssignments) { $fileIds = $request->getUserVar('filesIdsAndRevisions'); $libraryFileId = $request->getUserVar('libraryFileId'); if (is_string($fileIds)) { $fileIdsArray = explode(';', $fileIds); // Remove empty entries (a trailing ";" will cause these) $fileIdsArray = array_filter($fileIdsArray, create_function('$a', 'return !empty($a);')); } if (!empty($fileIdsArray)) { $multipleSubmissionFileAccessPolicy = new PolicySet(COMBINING_DENY_OVERRIDES); foreach ($fileIdsArray as $fileIdAndRevision) { $multipleSubmissionFileAccessPolicy->addPolicy($this->_getAccessPolicy($request, $args, $roleAssignments, $fileIdAndRevision)); } $this->addPolicy($multipleSubmissionFileAccessPolicy); } else { if (is_numeric($libraryFileId)) { import('lib.pkp.classes.security.authorization.ContextAccessPolicy'); $this->addPolicy(new ContextAccessPolicy($request, $roleAssignments)); } else { // IDs will be specified using the default parameters. $this->addPolicy($this->_getAccessPolicy($request, $args, $roleAssignments)); } } return parent::authorize($request, $args, $roleAssignments); }
/** * Constructor. * @param $request PKPRequest * @param $userId int optional * @param $author Author optional */ function UserDetailsForm($request, $userId = null, $author = null) { parent::UserForm('controllers/grid/settings/user/form/userDetailsForm.tpl', $userId); if (isset($author)) { $this->author =& $author; } else { $this->author = null; } $site = $request->getSite(); // Validation checks for this form if ($userId == null) { $this->addCheck(new FormValidator($this, 'username', 'required', 'user.profile.form.usernameRequired')); $this->addCheck(new FormValidatorCustom($this, 'username', 'required', 'user.register.form.usernameExists', array(DAORegistry::getDAO('UserDAO'), 'userExistsByUsername'), array($this->userId, true), true)); $this->addCheck(new FormValidatorAlphaNum($this, 'username', 'required', 'user.register.form.usernameAlphaNumeric')); if (!Config::getVar('security', 'implicit_auth')) { $this->addCheck(new FormValidator($this, 'password', 'required', 'user.profile.form.passwordRequired')); $this->addCheck(new FormValidatorLength($this, 'password', 'required', 'user.register.form.passwordLengthRestriction', '>=', $site->getMinPasswordLength())); $this->addCheck(new FormValidatorCustom($this, 'password', 'required', 'user.register.form.passwordsDoNotMatch', create_function('$password,$form', 'return $password == $form->getData(\'password2\');'), array($this))); } } else { $this->addCheck(new FormValidatorLength($this, 'password', 'optional', 'user.register.form.passwordLengthRestriction', '>=', $site->getMinPasswordLength())); $this->addCheck(new FormValidatorCustom($this, 'password', 'optional', 'user.register.form.passwordsDoNotMatch', create_function('$password,$form', 'return $password == $form->getData(\'password2\');'), array($this))); } $this->addCheck(new FormValidator($this, 'firstName', 'required', 'user.profile.form.firstNameRequired')); $this->addCheck(new FormValidator($this, 'lastName', 'required', 'user.profile.form.lastNameRequired')); $this->addCheck(new FormValidatorUrl($this, 'userUrl', 'optional', 'user.profile.form.urlInvalid')); $this->addCheck(new FormValidatorEmail($this, 'email', 'required', 'user.profile.form.emailRequired')); $this->addCheck(new FormValidatorCustom($this, 'email', 'required', 'user.register.form.emailExists', array(DAORegistry::getDAO('UserDAO'), 'userExistsByEmail'), array($this->userId, true), true)); $this->addCheck(new FormValidatorORCID($this, 'orcid', 'optional', 'user.orcid.orcidInvalid')); $this->addCheck(new FormValidatorPost($this)); }
/** * Takes a string and turns any URLs into formatted links * * @param string $text The input string * * @return string The output string with formatted links */ function parse_urls($text) { // URI specification: http://www.ietf.org/rfc/rfc3986.txt // This varies from the specification in the following ways: // * Supports non-ascii characters // * Does not allow parentheses and single quotes // * Cuts off commas, exclamation points, and periods off as last character // @todo this causes problems with <attr = "val"> // must be in <attr="val"> format (no space). // By default htmlawed rewrites tags to this format. // if PHP supported conditional negative lookbehinds we could use this: // $r = preg_replace_callback('/(?<!=)(?<![ ])?(?<!["\'])((ht|f)tps?:\/\/[^\s\r\n\t<>"\'\!\(\),]+)/i', $r = preg_replace_callback('/(?<![=\\/"\'])((ht|f)tps?:\\/\\/[^\\s\\r\\n\\t<>"\']+)/i', create_function('$matches', ' $url = $matches[1]; $punc = ""; $last = substr($url, -1, 1); if (in_array($last, array(".", "!", ",", "(", ")"))) { $punc = $last; $url = rtrim($url, ".!,()"); } $urltext = str_replace("/", "/<wbr />", $url); return "<a href=\\"$url\\" rel=\\"nofollow\\">$urltext</a>$punc"; '), $text); return $r; }
public function __construct(array $tosortData) { $code = ''; foreach ($tosortData as $tosort) { $key = $tosort['key']; if ($tosort['ascend']) { $ltVal = -1; $gtVal = 1; } else { $ltVal = 1; $gtVal = -1; } if ($tosort['nullsFirst']) { $leftNullVal = -1; $rightNullVal = 1; } else { $leftNullVal = 1; $rightNullVal = -1; } $code .= <<<EOC \$a_value = \$a[{$key}]; \$b_value = \$b[{$key}]; if(\$a_value === null) return {$leftNullVal}; elseif(\$b_value === null) return {$rightNullVal}; elseif(\$a_value < \$b_value) return {$ltVal}; elseif(\$a_value > \$b_value) return {$gtVal}; EOC; } $code .= 'return 0;'; $this->sortFunction = create_function('$a, $b', $code); }
/** * Display list of the available widgets, either all or matching search. * * The search parameter are search terms separated by spaces. * * @since unknown * * @param string $show Optional, default is all. What to display, can be 'all', 'unused', or 'used'. * @param string $_search Optional. Search for widgets. Should be unsanitized. */ function wp_list_widgets() { global $wp_registered_widgets, $sidebars_widgets, $wp_registered_widget_controls; $sort = $wp_registered_widgets; usort($sort, create_function('$a, $b', 'return strnatcasecmp( $a["name"], $b["name"] );')); $done = array(); foreach ($sort as $widget) { if (in_array($widget['callback'], $done, true)) { // We already showed this multi-widget continue; } $sidebar = is_active_widget($widget['callback'], $widget['id'], false, false); $done[] = $widget['callback']; if (!isset($widget['params'][0])) { $widget['params'][0] = array(); } $args = array('widget_id' => $widget['id'], 'widget_name' => $widget['name'], '_display' => 'template'); if (isset($wp_registered_widget_controls[$widget['id']]['id_base']) && isset($widget['params'][0]['number'])) { $id_base = $wp_registered_widget_controls[$widget['id']]['id_base']; $args['_temp_id'] = "{$id_base}-__i__"; $args['_multi_num'] = next_widget_id_number($id_base); $args['_add'] = 'multi'; } else { $args['_add'] = 'single'; if ($sidebar) { $args['_hide'] = '1'; } } $args = wp_list_widget_controls_dynamic_sidebar(array(0 => $args, 1 => $widget['params'][0])); call_user_func_array('wp_widget_control', $args); } }
public function load($locale, $locale_path, $domain, $textdomain = true) { $file = $locale_path . '/' . $locale . '/LC_MESSAGES/' . $domain . '.po'; $cache_file = waSystem::getInstance()->getConfig()->getPath('cache') . '/apps/' . $domain . '/locale/' . $locale . '.php'; if (isset(self::$cache[$locale][$domain])) { } elseif (!file_exists($file)) { self::$cache[$locale][$domain] = array(); } elseif (file_exists($cache_file) && filemtime($cache_file) > filemtime($file)) { self::$cache[$locale][$domain] = (include $cache_file); } else { if (file_exists($file)) { $gettext = new waGettext($file); self::$cache[$locale][$domain] = $gettext->read(); } else { self::$cache[$locale][$domain] = array(); } waFiles::create($cache_file); waUtils::varExportToFile(self::$cache[$locale][$domain], $cache_file); } if (isset(self::$cache[$locale][$domain]['meta']['Plural-Forms']['plural']) && self::$cache[$locale][$domain]['meta']['Plural-Forms']['plural']) { self::$cache[$locale][$domain]['meta']['f'] = create_function('$n', self::$cache[$locale][$domain]['meta']['Plural-Forms']['plural']); } if ($textdomain) { self::$domain = $domain; self::$locale = $locale; } if (!self::$locale) { self::$locale = $locale; } }
function fflcommerce_products($atts) { global $columns, $paged; $fflcommerce_options = FFLCommerce_Base::get_options(); if (empty($atts)) { return; } extract(shortcode_atts(array('per_page' => $fflcommerce_options->get('fflcommerce_catalog_per_page'), 'columns' => $fflcommerce_options->get('fflcommerce_catalog_columns'), 'orderby' => $fflcommerce_options->get('fflcommerce_catalog_sort_orderby'), 'order' => $fflcommerce_options->get('fflcommerce_catalog_sort_direction'), 'pagination' => false), $atts)); $args = array('post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => $per_page, 'ignore_sticky_posts' => 1, 'orderby' => $orderby, 'order' => $order, 'paged' => $paged, 'meta_query' => array(array('key' => 'visibility', 'value' => array('catalog', 'visible'), 'compare' => 'IN'))); if (isset($atts['skus'])) { $skus = explode(',', $atts['skus']); array_walk($skus, create_function('&$val', '$val = trim($val);')); $args['meta_query'][] = array('key' => 'sku', 'value' => $skus, 'compare' => 'IN'); } if (isset($atts['ids'])) { $ids = explode(',', $atts['ids']); array_walk($ids, create_function('&$val', '$val = trim($val);')); $args['post__in'] = $ids; } query_posts($args); ob_start(); fflcommerce_get_template_part('loop', 'shop'); if ($pagination) { do_action('fflcommerce_pagination'); } wp_reset_query(); return ob_get_clean(); }
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); }
function custom_permalinks($title) { $title = sanitize_title_with_dashes($title); $toupper = create_function('$m', 'return strtoupper($m[0]);'); $title = preg_replace_callback('/(%[0-9a-f]{2}?)+/', $toupper, $title); return $title; }
protected function addOption($name, $type, $default, $validate = NULL) { if (isset($this->__data[$name])) { echo 'Duplicate option ' . $name; return $this; } $this->__data[$name]['name'] = $name; $this->__data[$name]['type'] = $type; $this->__data[$name]['default'] = $default; $this->__data[$name]['validate'] = isset($validate) ? $validate : array(&$this, 'validate_default'); //dynamic function returning option value $this->__data[$name]['func'] = create_function('$self, $data', ' $value = NULL; if(array_key_exists($data["name"], $self->__options)) $value = $self->__options[$data["name"]]; return $self->get_value($data["type"], $value, $data["default"], $data["validate"]); '); $this->__data[$name . '_name'] = $this->__data[$name]; //dynamic function returning option name for settings page $this->__data[$name . '_name']['func'] = create_function('$self, $data', ' return $self->__optionName . "[" . $data["name"] . "]"; '); $this->__data[$name . '_label'] = $this->__data[$name]; //dynamic function returning option label for settings page $this->__data[$name . '_label']['func'] = create_function('$self, $data', ' return __($data["label"], $self->__localizeSlug); '); $this->lastOptionName = $name; array_push($this->optionNames, $name); return $this; }
function createFile($imgURL) { $remImgURL = urldecode($imgURL); $urlParced = pathinfo($remImgURL); $remImgURLFilename = $urlParced['basename']; $imgData = wp_remote_get($remImgURL); if (is_wp_error($imgData)) { $badOut['Error'] = print_r($imgData, true) . " - ERROR"; return $badOut; } $imgData = $imgData['body']; $tmp = array_search('uri', @array_flip(stream_get_meta_data($GLOBALS[mt_rand()] = tmpfile()))); if (!is_writable($tmp)) { return "Your temporary folder or file (file - " . $tmp . ") is not witable. Can't upload images to Flickr"; } rename($tmp, $tmp .= '.png'); register_shutdown_function(create_function('', "unlink('{$tmp}');")); file_put_contents($tmp, $imgData); if (!$tmp) { return 'You must specify a path to a file'; } if (!file_exists($tmp)) { return 'File path specified does not exist'; } if (!is_readable($tmp)) { return 'File path specified is not readable'; } // $data['name'] = basename($tmp); return "@{$tmp}"; }
/** * Constructor for a new breadcrumb_navxt object * * @param bcn_breadcrumb_trail $breadcrumb_trail An instance of a bcn_breadcrumb_trail object to use for everything */ public function __construct(bcn_breadcrumb_trail $breadcrumb_trail) { //We get our breadcrumb trail object from our constructor $this->breadcrumb_trail = $breadcrumb_trail; //Grab defaults from the breadcrumb_trail object $this->opt = $this->breadcrumb_trail->opt; //We set the plugin basename here $this->plugin_basename = plugin_basename(__FILE__); //We need to add in the defaults for CPTs and custom taxonomies after all other plugins are loaded add_action('wp_loaded', array($this, 'wp_loaded')); add_action('init', array($this, 'init')); //Register the WordPress 2.8 Widget add_action('widgets_init', create_function('', 'return register_widget("' . $this->unique_prefix . '_widget");')); //Load our network admin if in the network dashboard (yes is_network_admin() doesn't exist) if (defined('WP_NETWORK_ADMIN') && WP_NETWORK_ADMIN) { require_once dirname(__FILE__) . '/class.bcn_network_admin.php'; //Instantiate our new admin object $this->admin = new bcn_network_admin($this->breadcrumb_trail, $this->plugin_basename); } else { if (is_admin()) { require_once dirname(__FILE__) . '/class.bcn_admin.php'; //Instantiate our new admin object $this->admin = new bcn_admin($this->breadcrumb_trail, $this->plugin_basename); } } }
function scan($dir) { $files = array(); // Is there actually such a folder/file? if (file_exists($dir)) { $scanned = scandir($dir); //get a directory listing $scanned = array_diff(scandir($dir), array('.', '..', '.DS_Store', 'Thumbs.db')); //sort folders first, then by type, then alphabetically usort($scanned, create_function('$a,$b', ' return is_dir ($a) ? (is_dir ($b) ? strnatcasecmp ($a, $b) : -1) : (is_dir ($b) ? 1 : ( strcasecmp (pathinfo ($a, PATHINFO_EXTENSION), pathinfo ($b, PATHINFO_EXTENSION)) == 0 ? strnatcasecmp ($a, $b) : strcasecmp (pathinfo ($a, PATHINFO_EXTENSION), pathinfo ($b, PATHINFO_EXTENSION)) )) ; ')); foreach ($scanned as $f) { if (!$f || $f[0] == '.') { continue; // Ignore hidden files } if (is_dir($dir . '/' . $f)) { // The path is a folder $files[] = array("name" => $f, "type" => "folder", "path" => $dir . '/' . $f, "items" => scan($dir . '/' . $f)); } else { // It is a file $files[] = array("name" => $f, "type" => "file", "ext" => pathinfo($f, PATHINFO_EXTENSION), "path" => $dir . '/' . $f, "size" => filesize($dir . '/' . $f)); } } } return $files; }
/** * Implements EntityReferenceHandler::getReferencableEntities(). */ public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) { $settings = $this->field['settings']['handler_settings']; $include_space = $settings['include_space']; $all_groups = oa_core_get_all_groups(); $groups = array_map(create_function('$group', 'return $group->title;'), $all_groups); $group_options = array(); $count = 0; foreach ($groups as $nid => $group_name) { $count++; if (!$match || stripos($group_name, $match) !== FALSE) { $group_options[$nid] = $group_name; } if ($limit && $count == $limit) { break; } } if ($space_id = oa_core_get_space_context()) { // Bring current group to front. if (!empty($group_options[$space_id])) { $group_options = array($space_id => t('!name (current)', array('!name' => $group_options[$space_id]))) + $group_options; } elseif ($include_space) { $group_options = array($space_id => t('- All space members -')) + $group_options; } } return array(OA_GROUP_TYPE => $group_options); }
/** * Register an admin notification. * * @global string $pagenow The current admin page. * @param string $message The message to print. * @param string $type The type of notification [self::ERROR|self::SUCCESS]. * @param string $page (optional) A specific admin page in which the * notification should appear. If no page is specified * the message will be visible in all admin pages. */ static function notify($message, $type, $page = null) { global $pagenow; if (null != $page && $page == $pagenow || null == $page) { add_action('admin_notices', create_function('', "echo '<div class=\"" . $type . "\"><p>" . $message . "</p></div>';")); } }