/** * Gets the value of an environment variable. Supports boolean, empty and null. * * @param string $key * @param mixed $default * * @return mixed */ function env($key, $default = null) { $value = getenv($key); if ($value === false) { return value($default); } switch (strtolower($value)) { case 'true': case '(true)': return true; case 'false': case '(false)': return false; case 'null': case '(null)': return null; case 'empty': case '(empty)': return ''; } if (str_starts_with($value, '"') && str_ends_with($value, '"')) { return substr($value, 1, -1); } return $value; }
/** * Loads the given jQuery UI components JS files. * * You can indicate the name of the JS files to include as follow: * * ```php * $this->jQuery->ui('mouse', 'droppable', 'widget', ...); * ``` * * You can provide an array of options for HtmlHelper::script() as follow: * * ```php * $this->jQuery->ui('mouse', 'droppable', ['block' => 'true'], 'widget', ...); * ``` * * If no component is given, all components (concatenated as a single JS file) * will be loaded at once. * * @return mixed String of `<script />` tags or null if block is specified in * options or if $once is true and the file has been included before */ public function ui() { $args = func_get_args(); $files = []; $options = []; $out = ''; foreach ($args as $file) { if (is_array($file)) { $options = $file; continue; } $file = 'Jquery.ui/' . strtolower($file); if (!str_ends_with($file, '.js')) { $file .= '.js'; } if ($file != 'Jquery.ui/core.js') { $files[] = $file; } } if (empty($files)) { $files[] = Configure::read('debug') ? 'Jquery.jquery-ui.js' : 'Jquery.jquery-ui.min.js'; } else { array_unshift($files, 'Jquery.ui/core.js'); } foreach ($files as $file) { $out .= (string) $this->_View->Html->script($file, $options); } if (empty($out)) { return null; } return $out; }
/** * Execute search * * @param void * @return null */ function search() { if (active_project() && !logged_user()->isProjectUser(active_project())) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } // if $pageType = array_var($_GET, 'page_type'); $search_for = array_var($_GET, 'search_for'); $objectManagers = array("ProjectWebpages", "ProjectMessages", "MailContents", "ProjectFiles", "ProjectMilestones", "ProjectTasks", "ProjectEvents"); $objectTypes = array(lang('webpages'), lang('messages'), lang('emails'), lang('files'), lang('milestones'), lang('tasks'), lang('events')); $iconTypes = array('webpage', 'message', 'email', 'file', 'milestone', 'task', 'event'); if (user_config_option('show_file_revisions_search')) { array_splice($objectManagers, 4, 0, 'ProjectFileRevisions'); array_splice($objectTypes, 4, 0, lang('file contents')); array_splice($iconTypes, 4, 0, 'file'); } $search_results = array(); $timeBegin = microtime(true); if (trim($search_for) == '') { $search_results = null; $pagination = null; } else { $search_results = $this->searchWorkspaces($search_for, $search_results, 5); $search_results = $this->searchUsers($search_for, $search_results, 5); $search_results = $this->searchContacts($search_for, $search_results, 5); if (array_var($_GET, 'search_all_projects') != "true" && active_project() instanceof Project) { $projects = active_project()->getAllSubWorkspacesCSV(true); } else { $projects = null; } $c = 0; foreach ($objectManagers as $om) { $user_id = $om == "MailContents" ? logged_user()->getId() : 0; $results = SearchableObjects::searchByType($search_for, $projects, $om, true, 5, 1, null, $user_id); if (count($results[0]) > 0) { $sr = array(); $sr['result'] = $results[0]; $sr['pagination'] = $results[1]; $sr['type'] = $objectTypes[$c]; $sr['icontype'] = $iconTypes[$c]; $sr['manager'] = $om; $search_results[] = $sr; } $c++; } } // if $timeEnd = microtime(true); if (str_starts_with($search_for, '"') && str_ends_with($search_for, '"')) { $search_for = str_replace('"', '', $search_for); } tpl_assign('search_string', $search_for); tpl_assign('search_results', $search_results); tpl_assign('time', $timeEnd - $timeBegin); ajx_set_no_toolbar(true); ajx_replace(true); }
/** * test str_ends_with */ public function testStrEndsWith() { $this->assertTrue(str_ends_with('foobar', 'bar')); $this->assertTrue(str_ends_with('foobar', 'foobar')); $this->assertFalse(str_ends_with('foobar', 'qux')); $this->assertFalse(str_ends_with('foobar', 'foo')); $this->assertFalse(str_ends_with('foobar', 'oba')); $this->assertFalse(str_ends_with('foobar', 'quxfoobar')); }
/** * Test Mailer * * @param void * @return null */ function test_email() { $email_data = $this->request->post('email'); if (!is_array($email_data)) { $email_data = array('recipient' => $this->logged_user->getEmail(), 'subject' => lang('activeCollab - test email'), 'message' => lang("<p>Hi,</p>\n\n<p>Purpose of this message is to test whether activeCollab can send emails or not</p>")); } // if $this->smarty->assign('email_data', $email_data); if ($this->request->isSubmitted()) { $errors = new ValidationErrors(); $subject = trim(array_var($email_data, 'subject')); $message = trim(array_var($email_data, 'message')); $recipient = trim(array_var($email_data, 'recipient')); if ($subject == '') { $errors->addError(lang('Message subject is required'), 'subject'); } // if if ($message == '') { $errors->addError(lang('Message body is required'), 'message'); } // if if (is_valid_email($recipient)) { $recipient_name = null; $recipient_email = $recipient; } else { if (($pos = strpos($recipient, '<')) !== false && str_ends_with($recipient, '>')) { $recipient_name = trim(substr($recipient, 0, $pos)); $recipient_email = trim(substr($recipient, $pos + 1, strlen($recipient) - $pos - 2)); if (!is_valid_email($recipient_email)) { $errors->addError(lang('Invalid email address'), 'recipient'); } // if } else { $errors->addError(lang('Invalid recipient'), 'recipient'); } // if } // if if ($errors->hasErrors()) { $this->smarty->assign('errors', $errors); $this->render(); } // if $mailer =& ApplicationMailer::mailer(); $email_message = new Swift_Message($subject, $message, 'text/html', EMAIL_ENCODING, EMAIL_CHARSET); if ($mailer->send($email_message, new Swift_Address($recipient_email, $recipient_name), $this->logged_user->getEmail())) { flash_success('Test email has been sent, check your inbox'); } else { flash_error('Failed to send out test email'); } // if $this->redirectTo('admin_tools_test_email'); } // if }
public function __construct() { parent::__construct(); $documentRoot = $this->getConfig("DocumentRootConnect"); if (str_ends_with($documentRoot, "/")) { $documentRoot = substr($documentRoot, 0, -1); } $this->templatesDirectory = $_SERVER["DOCUMENT_ROOT"] . $documentRoot . DIRECTORY_SEPARATOR . $this->getConfig("TemplatesDirectory"); $this->cacheDirectory = $_SERVER["DOCUMENT_ROOT"] . $documentRoot . DIRECTORY_SEPARATOR . $this->getConfig("CacheDirectory"); $this->baseDirectory = $_SERVER["DOCUMENT_ROOT"] . $documentRoot; }
function url_trimAndClean($url) { $url = trim($url); if (str_starts_with($url, '/')) { $url = substr($url, 1); } if (str_ends_with($url, '/')) { $url = substr($url, 0, strlen($url) - 1); } $url = strtolower($url); return $url; }
/** * Render verbose permission name * * @param array $params * @param Smarty $smarty * @return string */ function smarty_function_permission_name($params, &$smarty) { $name = array_var($params, 'name', 'unknown'); if (str_ends_with($name, '_add')) { return lang('Add'); } elseif (str_ends_with($name, '_manage')) { return lang('Edit and Delete'); } else { return $name; } // if }
/** * Look for plugin/themes awaiting for installation and sets a flash message * with instructions about how to proceed. * * @param string $type Possible values `plugin` (default) or `theme`, defaults * to "plugin" * @return void */ protected function _awaitingPlugins($type = 'plugin') { $type = !in_array($type, ['plugin', 'theme']) ? 'plugin' : $type; $ignoreThemes = $type === 'plugin'; $plugins = Plugin::scan($ignoreThemes); foreach ($plugins as $name => $path) { if (Plugin::exists($name) || $type == 'theme' && !str_ends_with($name, 'Theme')) { unset($plugins[$name]); } } if (!empty($plugins)) { $this->Flash->set(__d('system', '{0} are awaiting for installation', $type == 'plugin' ? __d('system', 'Some plugins') : __d('system', 'Some themes')), ['element' => 'System.stashed_plugins', 'params' => compact('plugins')]); } }
function url_trimAndClean($url) { $url = trim($url); if (str_contains($url, '?')) { $url = explode('?', $url)[0]; } if (str_starts_with($url, '/')) { $url = substr($url, 1); } if (str_ends_with($url, '/')) { $url = substr($url, 0, strlen($url) - 1); } $url = strtolower($url); return $url; }
static function getSubscriberComments($workspace = null, $tag = null, $orderBy = 'created_on', $orderDir = "DESC", $start = 0, $limit = 20) { $oc = new ObjectController(); $queries = $oc->getDashboardObjectQueries($workspace, $tag, false, false, $orderBy); $query = ''; if (!is_array($queries)) { return array(); } foreach ($queries as $name => $q) { if (str_ends_with($name, "Comments")) { if ($query == '') { $query = $q; } else { $query .= " \n UNION \n" . $q; } } } $query .= " ORDER BY `order_value` "; if ($orderDir != "ASC" && $orderDir != "DESC") { $orderDir = "DESC"; } $query .= " " . $orderDir . " "; $query .= " LIMIT " . $start . "," . $limit . " "; $res = DB::execute($query); $comments = array(); if (!$res) { return $comments; } $rows = $res->fetchAll(); if (!is_array($rows)) { return $comments; } foreach ($rows as $row) { $manager = $row['object_manager_value']; $id = $row['oid']; if ($id && $manager) { $comment = get_object_by_manager_and_id($id, $manager); $object = $comment->getObject(); if ($object instanceof ProjectDataObject && $object->isSubscriber(logged_user())) { $comments[] = $comment; } } } return $comments; }
function format_value_to_print_task($value, $type, $textWrapper = '', $dateformat = 'Y-m-d') { switch ($type) { case DATA_TYPE_STRING: if (preg_match(EMAIL_FORMAT, strip_tags($value))) { $formatted = $value; } else { $formatted = $textWrapper . clean($value) . $textWrapper; } break; case DATA_TYPE_INTEGER: $formatted = clean($value); break; case DATA_TYPE_BOOLEAN: $formatted = $value == 1 ? lang('yes') : lang('no'); break; case DATA_TYPE_DATE: if ($value != 0) { if (str_ends_with($value, "00:00:00")) { $dateformat .= " H:i:s"; } $dtVal = DateTimeValueLib::dateFromFormatAndString($dateformat, $value); $formatted = format_date($dtVal, null, 0); } else { $formatted = ''; } break; case DATA_TYPE_DATETIME: if ($value != 0) { $dtVal = DateTimeValueLib::dateFromFormatAndString("{$dateformat} H:i:s", $value); $formatted = format_date($dtVal, null, 0); } else { $formatted = ''; } break; default: $formatted = $value; } if ($formatted == '') { $formatted = '--'; } return $formatted; }
private function matches($needle, $action) { if (array_key_exists($needle . '_' . $action, self::$cache['matches'])) { return self::$cache['matches'][$needle . '_' . $action]; } self::$cache['matches'][$needle . '_' . $action] = false; $tneedle = strtoupper($needle); $taction = strtoupper($action); if (str_ends_with($tneedle, '.*') && str_starts_with($taction, substr($tneedle, 0, strlen($tneedle - 1)))) { self::$cache['matches'][$needle . '_' . $action] = true; } else { if ($tneedle === $taction) { self::$cache['matches'][$needle . '_' . $action] = true; } else { self::$cache['matches'][$needle . '_' . $action] = false; } } return self::$cache['matches'][$needle . '_' . $action]; }
function dirToArray($dir, $fix = "", &$first = true) { $handle = opendir($dir); while (($file = readdir($handle)) !== false) { if ($file == '.' || $file == '..') { continue; } if (is_dir($dir . DIRECTORY_SEPARATOR . $file)) { dirToArray($dir . DIRECTORY_SEPARATOR . $file, $fix . $file . "/", $first); } elseif (!str_ends_with($file, ".php") && !str_ends_with($file, ".md5") && !str_ends_with($file, ".dat") && !str_starts_with($file, "installer")) { if ($first) { $first = false; } else { print "\r\n"; } print $fix . $file; } } closedir($handle); }
function &loadTheme($name) { if (str_ends_with($this->themesDir, '/')) { $this->themesDir = substr($this->themesDir, 0, strlen($this->themesDir) - 1); } $themeDir = $this->themesDir . '/' . $name . '/'; if (is_dir($themeDir)) { $themeContext = file_exists($themeDir . '/theme-context.yml') ? $themeDir . '/theme-context.yml' : null; if ($themeContext) { AppContext::load($themeContext); } $bootstrap = file_exists($themeDir . '/bootstrap' . EXT) ? $themeDir . '/bootstrap' . EXT : null; if ($bootstrap) { include $bootstrap; } $theme =& new Theme($name, $themeDir); return $theme; } show_error('ThemeManager', 'Specified theme doesn\'t exist: ' . $name); }
/** * Uploads a ZIP package to the server. * * @return bool True on success */ public function upload() { if (!isset($this->_package['tmp_name']) || !is_readable($this->_package['tmp_name'])) { $this->_error(__d('installer', 'Invalid package.')); return false; } elseif (!isset($this->_package['name']) || !str_ends_with(strtolower($this->_package['name']), '.zip')) { $this->_error(__d('installer', 'Invalid package format, it is not a ZIP package.')); return false; } else { $dst = normalizePath(TMP . $this->_package['name']); if (is_readable($dst)) { $file = new File($dst); $file->delete(); } if (move_uploaded_file($this->_package['tmp_name'], $dst)) { $this->_dst = $dst; return true; } } $this->_error(__d('installer', 'Package could not be uploaded, please check write permissions on /tmp directory.')); return false; }
/** * Compile template and generate * * @param string $path * @param string $template Path to template * @param $finalPath * * @return bool */ public function make($path, $template, &$finalPath) { $this->name = basename($path, '.php'); $this->path = $this->getPath($path); $template = $this->getTemplate($template, $this->name); // check for migration by same name but new date, I'm tired of deleting these files $filename = basename($this->path, ''); $name = strtolower($this->name) . '.php'; $fileExists = false; if ($filename !== $name && str_ends_with($filename, $name)) { // must have a date prefix, we should check if a file by the same name exists and append .new to this one if ($handle = opendir($basepath = dirname($path))) { while (false !== ($entry = readdir($handle))) { if (fnmatch('*_' . $name, $entry, FNM_PERIOD)) { if ($this->options('overwrite')) { // delete the sucker unlink($basepath . '/' . $entry); } else { $fileExists = true; } } if (!$this->options('overwrite') && fnmatch('*_' . $name . '.new', $entry, FNM_PERIOD)) { // delete the sucker unlink($basepath . '/' . $entry); } } closedir($handle); } } if ($this->options('overwrite') || !$fileExists && !$this->file->exists($this->path)) { $finalPath = $this->path; return $this->file->put($this->path, $template) !== false; } else { // put it as .new, and delete previous .new $finalPath = $this->path . ".new"; return $this->file->put($this->path . ".new", $template); } }
/** * Format filesize * * @access public * @param integer $in_bytes Site in bytes * @return string */ function format_filesize($in_bytes) { $units = array('TB' => 1099511627776.0, 'GB' => 1073741824, 'MB' => 1048576, 'KB' => 1024); // array // Loop units bigger than byte foreach ($units as $current_unit => $unit_min_value) { if ($in_bytes > $unit_min_value) { $formated_number = number_format($in_bytes / $unit_min_value, 2); while (str_ends_with($formated_number, '0')) { $formated_number = substr($formated_number, 0, strlen($formated_number) - 1); // remove zeros from the end } if (str_ends_with($formated_number, '.')) { $formated_number = substr($formated_number, 0, strlen($formated_number) - 1); // remove dot from the end } return $formated_number . $current_unit; } // if } // foreach // Bytes? return $in_bytes . 'bytes'; }
public static function init() { $url = OPTIONS::website("url_page_pattern"); $pattern = str_replace(array("%content_slug%", "%content_lang%?/", "%content_lang%"), array("[any]", '([a-z]+/)?', '([a-z]+)'), $url); URL::route('^' . $pattern . '$', function () use($url) { $url = str_replace("?", "", $url); $returns = func_get_args(); $counter = 0; foreach (explode("/", $url) as $i => $v) { if (str_starts_with($v, "%") && str_ends_with($v, "%")) { $col = substr($v, 1, strlen($v) - 2); $returns[$col] = $returns[$counter]; unset($returns[$counter]); $counter++; } } $data = self::get_page($returns); if ($data !== false) { self::$current = $data; } else { URL::routed(false); } }); }
function simple_pattern_match($patterns, $str) { if (!is_array($patterns)) { $patterns = array($patterns); } foreach ($patterns as $pattern) { if ($pattern == $str || "*" == $pattern) { return true; } if ($pattern == null || $str == null) { return false; } if (str_starts_with($pattern, "*") && str_starts_with($pattern, "*") && strpos($str, substr($pattern, 1, strlen($pattern - 1))) != -1) { return true; } if (str_starts_with($pattern, "*") && str_ends_with($str, substr($pattern, 1, strlen($pattern)))) { return true; } if (str_ends_with($pattern, "*") && str_starts_with($str, substr($pattern, 0, strlen($pattern - 1)))) { return true; } } return false; }
/** * Load all scripts from /scripts folder * * @param void * @return null */ private function loadScripts() { $script_path = UPGRADER_PATH . '/scripts'; $d = dir($script_path); $scripts = array(); while (($entry = $d->read()) !== false) { if ($entry == '.' || $entry == '..') { continue; } // if $file_path = $script_path . '/' . $entry; if (is_readable($file_path) && str_ends_with($file_path, '.class.php')) { include_once $file_path; $script_class = substr($entry, 0, strlen($entry) - 10); $script = new $script_class($this->getOutput()); if ($script instanceof $script_class) { $script->setUpgrader($this); $scripts[] = $script; } // if } // if } // while $d->close(); if (count($scripts)) { usort($scripts, 'compare_scripts_by_version_to'); $this->scripts = $scripts; } // if }
function get_member_custom_property_value_for_listing($cp, $member_id, $cp_vals = null) { if (is_null($cp_vals)) { $cp_vals = MemberCustomPropertyValues::getMemberCustomPropertyValues($member_id, $cp->getId()); } $val_to_show = ""; foreach ($cp_vals as $cp_val) { if (in_array($cp->getType(), array('contact', 'user')) && $cp_val instanceof MemberCustomPropertyValue) { $cp_contact = Contacts::findById($cp_val->getValue()); if ($cp_contact instanceof Contact) { $cp_val->setValue($cp_contact->getObjectName()); } else { $cp_val->setValue(""); } } if ($cp->getType() == 'date' && $cp_val instanceof MemberCustomPropertyValue) { $format = user_config_option('date_format'); Hook::fire("custom_property_date_format", null, $format); $tmp_date = DateTimeValueLib::dateFromFormatAndString(DATE_MYSQL, $cp_val->getValue()); if (str_starts_with($cp_val->getValue(), EMPTY_DATE)) { $formatted = ""; } else { if (str_ends_with($cp_val->getValue(), "00:00:00")) { $formatted = $tmp_date->format(user_config_option('date_format')); } else { $formatted = $tmp_date->format($format); } } $cp_val->setValue($formatted); } if ($cp->getType() == 'address' && $cp_val instanceof MemberCustomPropertyValue) { $values = str_replace("\\|", "%%_PIPE_%%", $cp_val->getValue()); $exploded = explode("|", $values); foreach ($exploded as &$v) { $v = str_replace("%%_PIPE_%%", "|", $v); $v = str_replace("'", "\\'", $v); } if (count($exploded) > 0) { $address_type = array_var($exploded, 0, ''); $street = array_var($exploded, 1, ''); $city = array_var($exploded, 2, ''); $state = array_var($exploded, 3, ''); $country = array_var($exploded, 4, ''); $zip_code = array_var($exploded, 5, ''); $country_name = CountryCodes::getCountryNameByCode($country); $tmp = array(); if ($street != '') { $tmp[] = $street; } if ($city != '') { $tmp[] = $city; } if ($state != '') { $tmp[] = $state; } if ($zip_code != '') { $tmp[] = $zip_code; } if ($country_name != '') { $tmp[] = $country_name; } $cp_val->setValue(implode(' - ', $tmp)); } } $val_to_show .= ($val_to_show == "" ? "" : ", ") . ($cp_val instanceof MemberCustomPropertyValue ? $cp_val->getValue() : ""); } $val_to_show = html_to_text($val_to_show); return $val_to_show; }
<?php function str_ends_with($haystack, $needle) { return substr($haystack, -strlen($needle)) === $needle || $needle === ''; } /* If the URL is too verbose (specifying index.php or page 1), then, of course * we just want the main page, which defaults to page 1 anyway. */ $url = parse_url($_SERVER['REQUEST_URI']); if (strpos($_SERVER['REQUEST_URI'], 'index.php') !== false || isset($_GET['page']) && $_GET['page'] == 1) { header("HTTP/1.1 301 Moved Permanently"); $_SERVER['QUERY_STRING'] = str_replace('page=1', '', $_SERVER['QUERY_STRING']); header("Location: ./" . ($_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : '')); exit; } elseif (str_ends_with($url['path'], '/page/1') || str_ends_with($url['path'], '/page/1/')) { header("HTTP/1.1 301 Moved Permanently"); header("Location: ../" . ($_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : '')); exit; } include_once 'internal/Smarty.class.php'; $main_smarty = new Smarty(); include 'config.php'; include mnminclude . 'html1.php'; include mnminclude . 'link.php'; include mnminclude . 'tags.php'; include mnminclude . 'search.php'; include mnminclude . 'smartyvariables.php'; // module system hook $vars = ''; check_actions('index_top', $vars); // find the name of the current category
/** * Validates a composer.json file. * * Below a list of validation rules that are applied: * * - must be a valid JSON file. * - key `name` must be present and follow the pattern `author/package` * - key `type` must be present. * - key `extra.regions` must be present if it's a theme (its name ends with * `-theme`, e.g. `quickapps/blue-sky-theme`) * * ### Usage: * * ```php * $json = json_decode(file_gets_content('/path/to/composer.json'), true); * Plugin::validateJson($json); * * // OR: * * Plugin::validateJson('/path/to/composer.json'); * ``` * * @param array|string $json JSON given as an array result of * `json_decode(..., true)`, or a string as path to where .json file can be found * @param bool $errorMessages If set to true an array of error messages * will be returned, if set to false boolean result will be returned; true on * success, false on validation failure. Defaults to false (boolean result) * @return array|bool */ public static function validateJson($json, $errorMessages = false) { if (is_string($json) && is_readable($json) && !is_dir($json)) { $json = json_decode((new File($json))->read(), true); } $errors = []; if (!is_array($json) || empty($json)) { $errors[] = __d('cms', 'Corrupt JSON information.'); } else { if (!isset($json['type'])) { $errors[] = __d('cms', 'Missing field: "{0}"', 'type'); } if (!isset($json['name'])) { $errors[] = __d('cms', 'Missing field: "{0}"', 'name'); } elseif (!preg_match('/^(.+)\\/(.+)+$/', $json['name'])) { $errors[] = __d('cms', 'Invalid field: "{0}" ({1}). It should be: {2}', 'name', $json['name'], '{author-name}/{package-name}'); } elseif (str_ends_with(strtolower($json['name']), 'theme')) { if (!isset($json['extra']['regions'])) { $errors[] = __d('cms', 'Missing field: "{0}"', 'extra.regions'); } } } if ($errorMessages) { return $errors; } return empty($errors); }
</table> </div><!--calowner --> </div><!--gridcontainer --> </div> </td> </tr> </table> </td> </tr></table> </div> </div> <?php $wdst = user_config_option('work_day_start_time'); $h_m = explode(':', $wdst); if (str_ends_with($wdst, 'PM')) { $h_m[0] = ($h_m[0] + 12) % 24; $h_m[1] = substr($h_m[1], 0, strpos(' ', $h_m[1])); } $defaultScrollTo = PX_HEIGHT * ($h_m[0] + $h_m[1] / 60); ?> <script> // Top Toolbar ogCalendarUserPreferences = Ext.util.JSON.decode(document.getElementById('hfCalUserPreferences').value); var ogCalTT = new og.CalendarTopToolbar({ renderTo:'calendarPanelTopToolbar' }); var ogCalSecTT = new og.CalendarSecondTopToolbar({ usersHfId:'hfCalUsers', companiesHfId:'hfCalCompanies',
/** * Forget all of the queued listeners. * * @return void */ public function forgetQueued() { foreach ($this->listeners as $key => $value) { if (str_ends_with($key, '_queue')) { $this->forget($key); } } }
public function webmention(Request $request, Response $response) { # Require the token parameter if (!($token = $request->get('token'))) { return $this->respond($response, 401, ['error' => 'authentication_required', 'error_description' => 'A token is required to use the API']); } # Require source and target or target_domain parameters $target = $target_domain = null; if (!($source = $request->get('source')) || !($target = $request->get('target')) && !($target_domain = $request->get('target_domain'))) { return $this->respond($response, 400, ['error' => 'missing_parameters', 'error_description' => 'The source or target or target_domain parameters were missing']); } if ($target && $target_domain) { return $this->respond($response, 400, ['error' => 'invalid_parameter', 'error_description' => 'Can\'t provide both target and target_domain together']); } $urlregex = '/^https?:\\/\\/[^ ]+\\.[^ ]+$/'; $domainregex = '/^[^ ]+$/'; # Verify source, target, and callback are URLs $callback = $request->get('callback'); if (!preg_match($urlregex, $source) || !preg_match($urlregex, $target) && !preg_match($domainregex, $target_domain) || $callback && !preg_match($urlregex, $callback)) { return $this->respond($response, 400, ['error' => 'invalid_parameter', 'error_description' => 'The source, target, or callback parameters were invalid']); } # Don't send anything if the source domain matches the target domain # The problem is someone pushing to Superfeedr who is also subscribed, will cause a # request to be sent with the source of one of their posts, and their own target domain. # This causes a whole slew of webmentions to be queued up, almost all of which are not needed. if ($target_domain) { $source_domain = parse_url($source, PHP_URL_HOST); if ($target_domain == $source_domain) { # Return 200 so Superfeedr doesn't think something is broken return $this->respond($response, 200, ['error' => 'not_supported', 'error_description' => 'You cannot use the target_domain feature to send webmentions to the same domain as the source URL']); } } # Verify the token is valid $role = ORM::for_table('roles')->where('token', $token)->find_one(); if (!$role) { return $this->respond($response, 401, ['error' => 'invalid_token', 'error_description' => 'The token provided is not valid']); } # Check the blacklist of domains that are known to not accept webmentions if ($target && !Telegraph\Webmention::isProbablySupported($target)) { return $this->respond($response, 400, ['error' => 'not_supported', 'error_description' => 'The target domain is known to not accept webmentions. If you believe this is in error, please file an issue at https://github.com/aaronpk/Telegraph/issues']); } # If there is no code given, # Synchronously check the source URL and verify that it actually contains # a link to the target. This way we prevent this API from sending known invalid mentions. if ($request->get('code')) { # target URL is required if (!$target) { return $this->respond($response, 400, ['error' => 'not_supported', 'error_description' => 'The target_domain parameter is not supported for sending private webmentions']); } $found[$target] = null; } else { $sourceData = $this->http->get($source); $doc = new DOMDocument(); libxml_use_internal_errors(true); # suppress parse errors and warnings @$doc->loadHTML(self::toHtmlEntities($sourceData['body']), LIBXML_NOWARNING | LIBXML_NOERROR); libxml_clear_errors(); if (!$doc) { return $this->respond($response, 400, ['error' => 'source_not_html', 'error_description' => 'The source document could not be parsed as HTML']); } $xpath = new DOMXPath($doc); $found = []; foreach ($xpath->query('//a[@href]') as $href) { $url = $href->getAttribute('href'); if ($target) { # target parameter was provided if ($url == $target) { $found[$url] = null; } } elseif ($target_domain) { # target_domain parameter was provided $domain = parse_url($url, PHP_URL_HOST); if ($domain && ($domain == $target_domain || str_ends_with($domain, '.' . $target_domain))) { $found[$url] = null; } } } if (!$found) { return $this->respond($response, 400, ['error' => 'no_link_found', 'error_description' => 'The source document does not have a link to the target URL or domain']); } } # Write the webmention to the database and queue a job to start sending $statusURLs = []; foreach ($found as $url => $_) { $w = ORM::for_table('webmentions')->create(); $w->site_id = $role->site_id; $w->created_by = $role->user_id; $w->created_at = date('Y-m-d H:i:s'); $w->token = self::generateStatusToken(); $w->source = $source; $w->target = $url; $w->vouch = $request->get('vouch'); $w->code = $request->get('code'); $w->realm = $request->get('realm'); $w->callback = $callback; $w->save(); q()->queue('Telegraph\\Webmention', 'send', [$w->id]); $statusURLs[] = Config::$base . 'webmention/' . $w->token; } if ($target) { $body = ['status' => 'queued', 'location' => $statusURLs[0]]; $headers = ['Location' => $statusURLs[0]]; } else { $body = ['status' => 'queued', 'location' => $statusURLs]; $headers = []; } return $this->respond($response, 201, $body, $headers); }
function format_value_to_print($col, $value, $type, $obj_type_id, $textWrapper = '', $dateformat = 'Y-m-d') { switch ($type) { case DATA_TYPE_STRING: if (preg_match(EMAIL_FORMAT, strip_tags($value))) { $formatted = strip_tags($value); } else { $formatted = $textWrapper . clean($value) . $textWrapper; } break; case DATA_TYPE_INTEGER: if ($col == 'priority') { switch ($value) { case 100: $formatted = lang('low priority'); break; case 200: $formatted = lang('normal priority'); break; case 300: $formatted = lang('high priority'); break; case 400: $formatted = lang('urgent priority'); break; default: $formatted = clean($value); } } elseif ($col == 'time_estimate') { if ($value > 0) { $formatted = DateTimeValue::FormatTimeDiff(new DateTimeValue(0), new DateTimeValue($value * 60), 'hm', 60); } else { $formatted = clean($value); } } else { $formatted = clean($value); } break; case DATA_TYPE_BOOLEAN: $formatted = $value == 1 ? lang('yes') : lang('no'); break; case DATA_TYPE_DATE: if ($value != 0) { if (str_ends_with($value, "00:00:00")) { $dateformat .= " H:i:s"; } $dtVal = DateTimeValueLib::dateFromFormatAndString($dateformat, $value); $formatted = format_date($dtVal, null, 0); } else { $formatted = ''; } break; case DATA_TYPE_DATETIME: if ($value != 0) { $dtVal = DateTimeValueLib::dateFromFormatAndString("{$dateformat} H:i:s", $value); if ($obj_type_id == ProjectEvents::instance()->getObjectTypeId() && $col == 'start') { $formatted = format_datetime($dtVal); } else { $formatted = format_date($dtVal, null, 0); } } else { $formatted = ''; } break; default: $formatted = $value; } if ($formatted == '') { $formatted = '--'; } return $formatted; }
public function readDatabaseProperties(BaseDatabaseModel $model, ViewBase $view, $excludedProps = null) { $html = ""; $props = $model->getDatabaseArray(); foreach ($props as $key => $val) { if (in_array($key, $excludedProps)) { continue; } if (str_ends_with($key, "Id") && strlen($key) > 2) { $objName = substr($key, 0, -2); $obj = $view->tryRetrieve($objName); if ($obj instanceof BaseModel) { $html .= "<p><b>" . $objName . "</b>" . $obj->getIdentification() . "</p>"; } } else { $equalHides = array("Id" => "hidden"); $endHides = array("Password", "AuthHash"); $equalVal = str_equals_with_any($key, $equalHides, true); $endVal = str_ends_with_any($key, $endHides, true); if ($equalVal === false && $endVal === false) { $html .= "<p><b>" . $key . "</b>" . $this->formatProperty($val, $key) . "</p>"; } } } return $html; }
/** * @deprecated by listing(args) * @param unknown_type $context * @param unknown_type $object_type * @param unknown_type $order * @param unknown_type $order_dir * @param unknown_type $extra_conditions * @param unknown_type $join_params * @param unknown_type $trashed * @param unknown_type $archived * @param unknown_type $start * @param unknown_type $limit */ static function getContentObjects($context, $object_type, $order = null, $order_dir = null, $extra_conditions = null, $join_params = null, $trashed = false, $archived = false, $start = 0, $limit = null) { $table_name = $object_type->getTableName(); $object_type_id = $object_type->getId(); //Join conditions $join_conditions = self::prepareJoinConditions($join_params); //Trash && Archived conditions $conditions = self::prepareTrashandArchivedConditions($trashed, $archived); $trashed_cond = $conditions[0]; $archived_cond = $conditions[1]; //Order conditions $order_conditions = self::prepareOrderConditions($order, $order_dir); //Extra conditions if (!$extra_conditions) { $extra_conditions = ""; } //Dimension conditions $member_conditions = self::prepareDimensionConditions($context, $object_type_id); if ($member_conditions == "") { $member_conditions = "true"; } $limit_query = ""; if ($limit !== null) { $limit_query = "LIMIT {$start} , {$limit} "; } $sql_count = "SELECT COUNT( DISTINCT `om`.`object_id` ) AS total FROM `" . TABLE_PREFIX . "object_members` `om` \r\n \t\tINNER JOIN `" . TABLE_PREFIX . "objects` `o` ON `o`.`id` = `om`.`object_id`\r\n \t\tINNER JOIN `" . TABLE_PREFIX . "{$table_name}` `e` ON `e`.`object_id` = `o`.`id`\r\n \t\t{$join_conditions} WHERE {$trashed_cond} {$archived_cond} AND ({$member_conditions}) {$extra_conditions}"; $total = array_var(DB::executeOne($sql_count), "total"); $sql = "SELECT DISTINCT `om`.`object_id` FROM `" . TABLE_PREFIX . "object_members` `om` \r\n \t\tINNER JOIN `" . TABLE_PREFIX . "objects` `o` ON `o`.`id` = `om`.`object_id`\r\n \t\tINNER JOIN `" . TABLE_PREFIX . "{$table_name}` `e` ON `e`.`object_id` = `o`.`id`\r\n \t\t{$join_conditions} WHERE {$trashed_cond} {$archived_cond} AND ({$member_conditions}) {$extra_conditions} {$order_conditions}\r\n \t\t{$limit_query}\r\n \t\t"; $result = DB::execute($sql); $rows = $result->fetchAll(); $objects = array(); $handler_class = $object_type->getHandlerClass(); if (!is_null($rows)) { $ids = array(); foreach ($rows as $row) { $ids[] = array_var($row, 'object_id'); } if (count($ids) > 0) { $join_str = ""; if ($join_params) { $join_str = ', "join" => array('; if (isset($join_params['join_type'])) { $join_str .= '"join_type" => "' . $join_params['join_type'] . '",'; } if (isset($join_params['table'])) { $join_str .= '"table" => "' . $join_params['table'] . '",'; } if (isset($join_params['jt_field'])) { $join_str .= '"jt_field" => "' . $join_params['jt_field'] . '",'; } if (isset($join_params['e_field'])) { $join_str .= '"e_field" => "' . $join_params['e_field'] . '",'; } if (isset($join_params['j_sub_q'])) { $join_str .= '"j_sub_q" => "' . $join_params['j_sub_q'] . '",'; } if (str_ends_with($join_str, ",")) { $join_str = substr($join_str, 0, strlen($join_str) - 1); } $join_str .= ')'; } $phpCode = '$objects = ' . $handler_class . '::findAll(array("conditions" => "`e`.`object_id` IN (' . implode(',', $ids) . ')", "order" => "' . str_replace("ORDER BY ", "", $order_conditions) . '"' . $join_str . '));'; eval($phpCode); } } $result = new stdClass(); $result->objects = $objects; $result->total = $total; return $result; }