function actionAdd() { // We return to the default action $action = 'default'; // Process the form if ($this->form->validate()) { // Move the uploaded file $file = $this->form->getElement('image'); if ($file->isUploaded()) { // Get the new filename $filename = YDStringUtil::stripSpecialCharacters($file->getBaseName()); // Move the upload $file->moveUpload($this->dir_rel, $filename); // Check if it's an image $fileObj = new YDFSFile($this->dir_rel . $file->getBaseName()); if (!$fileObj->isImage()) { @unlink($this->dir_rel . $file->getBaseName()); } // Create the thumbnails $thumb = new YDFSImage($this->dir_rel . $file->getBaseName()); $thumb->_createThumbnail(100, 100, true); $thumb->_createThumbnail(48, 48, true); } // Get the name of the action $action = $this->form->getValue('action'); } // Redirect to the list view $destination = YD_SELF_SCRIPT . '?do=' . $action; if (isset($_GET['field'])) { $destination .= '&field=' . $_GET['field']; } $this->redirect($destination); }
function actionAdd() { // We return to the default action $action = 'default'; // Process the form if ($this->form->validate()) { // Move the uploaded file $file = $this->form->getElement('image'); if ($file->isUploaded()) { // Get the new filename $filename = YDStringUtil::stripSpecialCharacters($file->getBaseName()); // Move the upload if (!is_dir($this->dir_rel)) { @mkdir($this->dir_rel); } $file->moveUpload($this->dir_rel, $filename); // Check if it's an image $fileObj = new YDFSFile($this->dir_rel . $file->getBaseName()); if (!$fileObj->isImage()) { @unlink($this->dir_rel . $file->getBaseName()); } // Delete the thumbnails @unlink($this->dir_rel . 's_' . $file->getBaseName()); @unlink($this->dir_rel . 'm_' . $file->getBaseName()); } } // Redirect to the list view $this->redirect(YD_SELF_SCRIPT . '?id=' . $this->item['id']); }
function actionDefault() { // Test the formatting of filesizes $filesizes = array('1152921504606846977', '1125899906842625', '1099511627777', '75715455455', '1048577', '6543', '42'); // Format the filesizes foreach ($filesizes as $filesize) { YDDebugUtil::dump(YDStringUtil::formatFileSize($filesize), 'Formatting filesize: ' . $filesize); } // Test the formatDate function YDDebugUtil::dump(YDStringUtil::formatDate(time(), 'date'), 'Formatting date - date'); YDDebugUtil::dump(YDStringUtil::formatDate(time(), 'time'), 'Formatting date - time'); YDDebugUtil::dump(YDStringUtil::formatDate(time(), 'datetime'), 'Formatting date - datetime'); YDDebugUtil::dump(YDStringUtil::formatDate(time(), '%x'), 'Formatting date - %x'); // Test the encode string function $string = 'Pieter Claerhout @ creo.com "générales obsolète"'; YDDebugUtil::dump(YDStringUtil::encodeString($string), 'Encoding: ' . $string); // Test the truncate function YDDebugUtil::dump(YDStringUtil::truncate($string), 'Truncate (default): ' . $string); YDDebugUtil::dump(YDStringUtil::truncate($string, 20), 'Truncate (20): ' . $string); YDDebugUtil::dump(YDStringUtil::truncate($string, 20, ' [more]'), 'Truncate (20/more): ' . $string); YDDebugUtil::dump(YDStringUtil::truncate($string, 20, ' [more]', true), 'Truncate (20/more/true): ' . $string); // Test the normalizing of newlines $string = "line1\nline2\rline3\r\nline4"; YDDebugUtil::dump(explode("\n", $string), 'Original string'); YDDebugUtil::dump(explode(YD_CRLF, YDStringUtil::normalizeNewlines($string)), 'normalizeNewlines'); // Test the normalizing of newlines $string = " line1 \n line2 \r line3 \r\n line4 "; YDDebugUtil::dump(YDStringUtil::removeWhiteSpace($string), 'removeWhiteSpace'); }
function result($currentdate, $operation, $number, $type) { // create date object with timestamp from the 'currentdate' form element $date = new YDDate(); $date->set(intval($currentdate)); // if operation is 1 we want subtract the number if ($operation == 1) { $number = -intval($number); } else { $number = intval($number); } // add number to date switch (intval($type)) { case 0: $date->addMinute($number); break; case 1: $date->addDay($number); break; case 2: $date->addMonth($number); break; default: $date->addYear($number); } // assign span with date $this->ajax->addResult('myspanresult', YDStringUtil::formatDate($date->getTimestamp(), 'datetime')); // return response to client browser return $this->ajax->processResults(); }
function actionAdd() { // We return to the default action $action = 'default'; // Process the form if ($this->form->validate()) { // Move the uploaded file $file = $this->form->getElement('image'); if ($file->isUploaded()) { // Get the new filename $filename = YDStringUtil::stripSpecialCharacters($file->getBaseName()); // Move the upload if (!is_dir($this->dir_rel)) { @mkdir($this->dir_rel); } @$file->moveUpload($this->dir_rel, $filename); // Convert it to an object $fileObj = new YDFSFile($this->dir_rel . $file->getBaseName()); // Check if it's a ZIP file if (strtolower($fileObj->getExtension() == 'zip')) { // Include the unzip library include YD_DIR_HOME . '/3rdparty/zip/unzip.lib.php'; // Convert it to a ZIP object $zip = new SimpleUnzip($fileObj->getAbsolutePath()); // Get the directory as a path $dir = new YDFSDirectory($this->dir_rel); // Extract the images foreach ($zip->Entries as $entry) { // Save it as a filee $entryFile = $dir->createFile($entry->Name, $entry->Data); // Delete it if it's not an image if (!$entryFile->isImage()) { @unlink($entryFile->getAbsolutePath()); } else { $entryFile = $this->weblog->resizeUploadedImage($entryFile); } } } // Check if it's an image if (!$fileObj->isImage()) { @unlink($fileObj->getAbsolutePath()); } else { $fileObj = $this->weblog->resizeUploadedImage($fileObj); } // Delete the thumbnails @unlink($this->dir_rel . 's_' . $file->getBaseName()); @unlink($this->dir_rel . 'm_' . $file->getBaseName()); } } // Redirect to the list view $this->redirect(YD_SELF_SCRIPT . '?id=' . $this->item['id']); }
function addentry($items) { // create element name $element = time(); // add element name and value to previous items $items[$element] = 'New option added at ' . YDStringUtil::formatDate(time(), '%d %B %Y %H:%M:%S'); // assign items to select box (because it's an array, will replace all values) $this->ajax->addResult('items', $items); // define the last element as the element selected (because it's a string will define a new selection) $this->ajax->addResult('items', $element); // return response to client browser return $this->ajax->processResults(); }
function actionDefault() { // create a pdfReport object $pdf = new YDPdfReport(); // set Report title (optional) $pdf->setTitle(YD_FW_NAMEVERS . ' PDF Report'); // set pdf author, a pdf meta-tag (optional) $pdf->setAuthor('ximian'); // create translations (optional) $pdf->setLanguage(array('page' => 'Page ', 'createdby' => 'Created by the YDF addon (v' . $pdf->_version . ') on ' . YDStringUtil::formatDate(time(), "datetime"), 'createdlink' => '', 'pageseparator' => ' of ')); // use this html $pdf->setHTML("<h1>Example 1</h1>Hello World!"); // create pdf file $pdf->output('inline'); }
function result($option) { // compute message switch ($option) { case 1: $message = YD_FW_NAMEVERS; break; default: YDInclude('YDUtil.php'); $message = YDStringUtil::formatDate(time(), '%d %B %Y %H:%M:%S'); } // assign span 'myspanresult' of 'myform' with dynamic message $this->ajax->addResult('myspanresult', $message); // return response to client browser return $this->ajax->processResults(); }
function actionDefault() { // Create the form $form = new YDForm('form1'); // Add a first set of elements $elementDate = $form->addElement('dateselect', 'dateSelect1', 'Enter data:'); $elementTime = $form->addElement('timeselect', 'timeSelect1', 'Enter data:'); $elementDateTime = $form->addElement('datetimeselect', 'datetimeSelect1', 'Enter data:'); // Add a second set of elements $form->addElement('dateselect', 'dateSelect2', 'Enter data:', array(), array('yearstart' => 1970, 'yearend' => '2050')); $form->addElement('timeselect', 'timeSelect2', 'Enter data:'); $form->addElement('datetimeselect', 'datetimeSelect2', 'Enter data:', array(), array('yearstart' => 1970, 'yearend' => '2050')); $form->addElement('datetimeselect', 'datetimeSelect3', 'Enter data with seconds:', array(), array('seconds' => true)); // Add the send button $form->addElement('submit', 'cmd1', 'Send'); // Set the defaults $form->setDefaults(array('dateSelect1' => array('month' => 4, 'day' => 4, 'year' => 2002), 'dateSelect2' => strval(time()), 'timeSelect2' => strval(time()), 'datetimeSelect2' => time() + 3600 * 24)); // Display the form $form->display(); // Show the contents of the form if (YDConfig::get('YD_DEBUG') == 1) { YDDebugUtil::dump($form->_regElements, 'Registered elements'); YDDebugUtil::dump($form->_regRules, 'Registered rules'); YDDebugUtil::dump($form->_regFilters, 'Registered filters'); YDDebugUtil::dump($form->_filters, 'Filters'); YDDebugUtil::dump($form->_rules, 'Rules'); YDDebugUtil::dump($form->_formrules, 'Form Rules'); YDDebugUtil::dump($form->getValue('dateSelect1'), 'dateSelect1'); YDDebugUtil::dump($form->getValue('timeSelect1'), 'timeSelect1'); YDDebugUtil::dump($form->getValue('datetimeSelect1'), 'datetimeSelect1'); YDDebugUtil::dump($form->getValues(), '$form->getValues()'); YDDebugUtil::dump($_POST, '$_POST'); YDDebugUtil::dump($_FILES, '$_FILES'); } if ($form->validate()) { YDDebugUtil::dump($form->getValues(), '$form->getValues()'); YDDebugUtil::dump($elementDate->getTimeStamp(), '$elementDate->getTimeStamp()'); YDDebugUtil::dump($elementDate->getTimeStamp('%d/%m/%Y'), '$elementDate->getTimeStamp( "%d/%m/%Y" )'); YDDebugUtil::dump(date('M-d-Y', $elementDate->getTimeStamp()), '$elementDate->gdate( getTimeStamp() )'); YDDebugUtil::dump($elementTime->getTimeStamp(), '$elementTime->getTimeStamp()'); YDDebugUtil::dump($elementTime->getTimeStamp('%H:%M'), '$elementTime->getTimeStamp( "%H:%M" )'); YDDebugUtil::dump($elementDateTime->getTimeStamp(), '$elementDateTime->getTimeStamp()'); YDDebugUtil::dump($elementDateTime->getTimeStamp('%d/%m/%Y %H:%M'), '$elementDateTime->getTimeStamp( "%H:%M" )'); YDDebugUtil::dump(YDStringUtil::formatDate($elementDateTime, 'datetime', 'pt'), 'YDStringUtil::formatDate'); } }
/** * This function updates current user login details * * @returns true if user login details updated, false if user is not valid or details not updated */ function updateLogin() { $this->resetAll(); // set our user_id for search $this->set('user_id', $this->currentID()); // get all attributes $this->find(); // increase login counter value $this->set('login_counter', 1 + $this->get('login_counter')); // set last login date $this->set('login_last', $this->get('login_current')); // set current login $this->set('login_current', YDStringUtil::formatDate(time(), 'datetimesql')); // because we don't have a primary key we must do this $this->where('user_id = ' . $this->get('user_id')); // return update result if ($this->update() == 1) { return true; } return false; }
/** * This function will add a new item to the feed. You need to at least give in a title, link. A description is * advised but optional. Also a GUID is optional. If no GUID is given, an automatic one will be created which * is the md5 checksum of the different elememts. * * @param $title The title of the feed item. * @param $link The link to the feed item. * @param $desc (optional) The description for the feed item. * @param $guid (optional) The guid for the feed item. * @param $enclosure (optional) The url of the enclosure. * @param $enclosure_size (optional) The size in bytes of the enclosure. * @param $enclosure_type (optional) The mime-type of the enclosure. * @param $commentlink (optional) The link to the comment page for the item. * * @remark * Enclosures are only supported for ATOM and RSS 2.0 feeds. */ function addItem($title, $link, $desc = null, $guid = null, $enclosure = null, $enclosure_size = null, $enclosure_type = null, $commentlink = null) { $link = YDUrl::makeLinkAbsolute($link, $this->_link); $desc = YDUrl::makeLinksAbsolute($desc, $this->_link); if (empty($guid)) { $checkSum = $this->_link . $title . $link; if ($desc != null) { $checkSum .= $desc; } $guid = md5($checkSum); } if (!is_null($enclosure) && (is_null($enclosure_size) || is_null($enclosure_type))) { trigger_error('Enclosures must have both type and size specified!', YD_ERROR); } $item = array('title' => $this->_encodeStrings ? YDStringUtil::encodeString($title) : $title, 'link' => $link, 'description' => $this->_encodeStrings ? YDStringUtil::encodeString($desc) : $desc, 'guid' => $guid, 'enclosure' => $enclosure, 'enclosure_size' => $enclosure_size, 'enclosure_type' => $enclosure_type, 'comments' => $commentlink); $this->_items[$guid] = $item; }
/** * Returns the total size of the directory. * * @param $recursive (optional) Recurse into the subdirectories. Default is false. * @param $formatted (optional) If set to true, the filesize will be returned in a human readable format. * @param $decimals (optional) The number of decimals to use for formatting the filesize. * * @returns The total size of the directory. */ function getSize($recursive = false, $formatted = false, $decimals = 1) { $total = 0; $dirHandle = opendir($this->getPath()); while (false !== ($file = readdir($dirHandle))) { if ($file == '.' || $file == '..') { continue; } if (is_file($this->getPath() . '/' . $file)) { $total += filesize($this->getPath() . '/' . $file); } else { if ($recursive && is_dir($this->getPath() . '/' . $file)) { $subdir = new YDFSDirectory($this->getPath() . '/' . $file); $total += $subdir->getSize(true, false, $decimals); } } } closedir($dirHandle); if (!$formatted) { return $total; } return YDStringUtil::formatFilesize($total, $decimals); }
function _getTotalSizeAndCountAsText($pattern) { $res = $this->_getTotalSizeAndCount($pattern); return sprintf('(%s %s, %s)', $res[0], t('items'), YDStringUtil::formatFileSize($res[1])); }
/** * This function will take a piece of text and convert the BBCode tags to their HTML equivalents. You can * optionally convert line breaks as well as convert the remaining HTML tags to their entities. * * @param $data The data you want to convert. * @param $convertBr (optional) Boolean to indicate that new lines should be converted to <br/> tags. * This is turned on by default. * @param $convertTags (optional) Boolean to indicate that tags should be converted to HTML. This is turned * on by default. * @param $convertLinks (optional) Boolean to indicate if links should be automatically highlighted or not. * This is turned on by default. * @param $baseUrl (optional) If you give this a non-null value, it will convert all links to absolute * links using this url as the base url. * * @returns The HTML equivalent of the string with all the BBCode's converted according to the conversion table * of this class. */ function toHtml($data, $convertBr = true, $convertTags = true, $convertLinks = true, $baseUrl = null) { // Encode the references $data = YDStringUtil::encodeString($data); // Convert the links to BBcode if ($convertLinks === true) { $data = $this->convertLinks($data); } // Convert tags if needed if ($convertTags === true) { $data = str_replace('<', '<', $data); $data = str_replace('>', '>', $data); } // Fix common problems $data = str_replace("\r\n", "\n", $data); $data = str_replace("\r", "\n", $data); $data = str_replace("[/quote]\n\n", "[/quote]\n", $data); // Convert the tags $data = $this->parser->parse($data); // Strip the leftover tags $data = trim(preg_replace('/\\[\\/[a-z]+\\]/i', '', $data)); // Open http links in a new window $data = str_replace(' href="http://', ' target="_blank" href="http://', $data); // Convert tags if needed if ($convertBr === true) { $data = nl2br(trim($data)); } // Convert smilies if needed $smilies_path = YDConfig::get('YD_BBCODE_SMILIES_DIR', ''); $smilies_url = YDConfig::get('YD_BBCODE_SMILIES_URL', ''); if (is_dir($smilies_path)) { foreach ($this->smilies as $smilie => $file) { $data = str_replace($smilie, '<img src="' . $smilies_url . '/' . $file . '" width="15" height="15" />', $data); } } // Make links absolute if needed if (!is_null($baseUrl)) { include_once dirname(__FILE__) . '/../../YDClasses/YDUrl.php'; $data = YDUrl::makeLinksAbsolute($data, $baseUrl); } // Return the data return $data; }
$form = new YDForm('ydcmforumpost'); $form->addElement('textarea', 'content', 'Content'); $form->addElement('button', 'cmdLogin', 'Submit'); // if we are replying to someone, let's get the content if (is_numeric($quote_id)) { // get replying post $posts = new YDCMForum_posts(); $post = $posts->getElement($quote_id); // apply default to content textarea $form->setDefault('content', $post['post_content']); } return $form; } } // last user login date. YDConfig::set('YD_FORUM_LASTLOGINDATE', YDStringUtil::formatDate(time(), 'datetimesql'), false); class YDCMForum_topics extends YDDatabaseObject { function YDCMForum_topics() { // init DB object $this->YDDatabaseObject(); // register database as default $this->registerDatabase(); // register table for this component $this->registerTable('YDCMForum_topics'); // register fields $this->registerKey('topic_id', true); $this->registerField('topic_forum_id'); $this->registerField('topic_title'); $this->registerField('topic_user_id');
/** * This function will return the feed in the specified format. The following formats are recognized: RSS0.91, * RSS1.0, RSS2.0, ATOM * * @remark * The default format is "RSS2.0". If you specify no argument indicating the requested format, the "RSS2.0" * format will be used. * * @param $format (optional) The format in which the items should be converted. * * @returns String with the data in the requested format. */ function toXml($format = 'RSS2.0') { // Convert the format to uppercase $format = strtoupper($format); // Check if the format is an allowed one if (!in_array($format, array('RSS0.91', 'RSS1.0', 'RSS2.0', 'ATOM'))) { trigger_error('The YDFeedCreator does not support the format called "' . $format . '". Only the formats "RSS0.91"' . ', "RSS1.0", "RSS2.0" and "ATOM" are supported.', YD_ERROR); } // Start with the first XML line $xml = '<?xml version="1.0" encoding="' . $this->_encoding . '"?>'; // Formatter for RSS 0.91 if ($format == 'RSS0.91' || $format == 'RSS2.0') { if ($format == 'RSS0.91') { $xml .= '<rss version="0.91">'; } else { $xml .= '<rss version="2.0">'; } $xml .= '<channel>'; $xml .= '<title>' . $this->_title . '</title>'; if (!empty($this->_description)) { $xml .= '<description>' . $this->_description . '</description>'; } $xml .= '<link>' . $this->_link . '</link>'; $xml .= '<generator>' . $this->_generator . '</generator>'; foreach ($this->_items as $item) { $item['description'] = YDStringUtil::encodeString($item['description'], true); $xml .= '<item>'; $xml .= '<title>' . $item['title'] . '</title>'; $xml .= '<link>' . $item['link'] . '</link>'; $xml .= '<guid isPermanlink="false">' . $item['guid'] . '</guid>'; if (!empty($item['description'])) { $xml .= '<description>' . $item['description'] . '</description>'; } $xml .= '</item>'; } $xml .= '</channel>'; $xml .= '</rss>'; } // Formatter for RSS1.0 if ($format == 'RSS1.0') { $xml .= '<rdf:RDF'; $xml .= ' xmlns="http://purl.org/rss/1.0/"'; $xml .= ' xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"'; $xml .= ' xmlns:dc="http://purl.org/dc/elements/1.1/">'; $xml .= '<channel rdf:about="">'; $xml .= '<title>' . $this->_title . '</title>'; $xml .= '<description>' . $this->_description . '</description>'; $xml .= '<link>' . $this->_link . '</link>'; $xml .= '<items>'; $xml .= '<rdf:Seq>'; foreach ($this->_items as $item) { $xml .= '<rdf:li rdf:resource="' . $item['link'] . '"/>'; } $xml .= '</rdf:Seq>'; $xml .= '</items>'; $xml .= '</channel>'; foreach ($this->_items as $item) { $item['description'] = YDStringUtil::encodeString($item['description'], true); $xml .= '<item rdf:about="' . $item['link'] . '">'; $xml .= '<dc:format>text/html</dc:format>'; $xml .= '<title>' . $item['title'] . '</title>'; $xml .= '<link>' . $item['link'] . '</link>'; if (!empty($item['description'])) { $xml .= '<description>' . $item['description'] . '</description>'; } $xml .= '</item>'; } $xml .= '</rdf:RDF>'; } // Formatter for ATOM if ($format == 'ATOM') { $xml .= '<feed version="0.3" xmlns="http://purl.org/atom/ns#">'; $xml .= '<title>' . $this->_title . '</title>'; if (!empty($this->_description)) { $xml .= '<tagline>' . $this->_description . '</tagline>'; } $xml .= '<link rel="alternate" type="text/html" href="' . $this->_link . '"/>'; $xml .= '<id>' . $this->_link . '</id>'; $xml .= '<generator>' . $this->_generator . '</generator>'; foreach ($this->_items as $item) { $xml .= '<entry>'; $xml .= '<title>' . $item['title'] . '</title>'; $xml .= '<link rel="alternate" type="text/html" href="' . $item['link'] . '"/>'; $xml .= '<id>' . $item['guid'] . '</id>'; if (!empty($item['description'])) { $xml .= '<content type="text/html" mode="escaped" xml:base="' . $item['link'] . '"><![CDATA[ '; $xml .= $item['description']; $xml .= ' ]]></content>'; } $xml .= '</entry>'; } $xml .= '</feed>'; } // Return the XML return $xml; }
function addResponse($post_id, $user_id, $message) { YDInclude('YDUtil.php'); $this->resetValues(); // create response // TODO: check if post_id and user_id are valid $this->post_id = intval($post_id); $this->user_id = intval($user_id); $this->date = YDStringUtil::formatDate(time(), 'datetimesql'); $this->description = $message; return $this->insert(); }
/** * This is the function we use for finishing the request. * * @internal */ function finish() { // Mark that the request is processed define('YD_REQ_PROCESSED', 1); // Stop the timer $elapsed = $GLOBALS['timer']->getElapsed(); // Total size of include files $includeFiles = get_included_files(); // Calculate the total size $includeFilesSize = 0; $includeFilesWithSize = array(); foreach ($includeFiles as $key => $includeFile) { $includeFilesSize += filesize($includeFile); $includeFilesWithSize[filesize($includeFile)] = realpath($includeFile); } $includeFilesSize = YDStringUtil::formatFileSize($includeFilesSize); // Sort the list of include files by file size krsort($includeFilesWithSize); // Convert to a string $includeFiles = array(); foreach ($includeFilesWithSize as $size => $file) { array_push($includeFiles, YDStringUtil::formatFileSize($size) . "\t " . $file); } // Show debugging info if needed if (YD_DEBUG == 1) { // Create the debug messages $debug = "\n\n"; $debug .= 'Processing time: ' . $elapsed . ' ms' . "\n\n"; $debug .= 'Total size include files: ' . $includeFilesSize . "\n\n"; $debug .= 'Included files: ' . "\n\n\t" . implode("\n\t", $includeFiles) . "\n\n"; // If there is a database instance $debug .= 'Number of SQL queries: ' . sizeof($GLOBALS['YD_SQL_QUERY']) . "\n\n"; // Add the queries if any if (sizeof($GLOBALS['YD_SQL_QUERY']) > 0) { $debug .= 'Executed SQL queries: ' . "\n\n"; foreach ($GLOBALS['YD_SQL_QUERY'] as $key => $query) { $debug .= "\t" . ($key + 1) . ': ' . trim($query) . "\n\n"; } } // Output the debug message YDDebugUtil::debug($debug); } else { // Short version echo "\n" . '<!-- ' . $elapsed . ' ms / ' . $includeFilesSize . ' -->'; } // Stop the execution of the request die; }
/** * This function removes the default table prefix to the field name. * * @param $field The name of the field to remove the prefix from. * * @returns The name of the field with the prefix removed from it. */ function _removeTablePrefix($field) { $field = explode(', ', $field); foreach ($field as $key => $val) { if (YDStringUtil::startsWith($val, $this->tablePrefix . '.')) { $field[$key] = substr($val, strlen($this->tablePrefix) + 1); } $pos = strpos($val, '.'); if ($pos !== false) { $field[$key] = substr($val, $pos + 1); } } return join(', ', $field); }
function actionUpdate() { // Check if a software update is going on YDDatabaseTools::checkLockDb(); // Download the needed files foreach ($this->changed_files as $file => $action) { if ($action != 'D') { $this->updateDb->downloadFile($file); } } // Lock the weblog application YDDatabaseTools::lockDb(); // Install the new files foreach ($this->changed_files as $file => $action) { YDUpdateTools::installFile($file, $action); } // Update the init file if ($this->updateDb->isUpdated('%YD_WEBLOG_HOME%/include/YDWeblog_init.php')) { YDUpdateTools::replaceInFile('%YD_WEBLOG_HOME%/include/YDWeblog_init.php', '\'/../../../YDFramework2/YDF2_init.php\' );', '\'/YDFramework2/YDF2_init.php\' );'); } // Update the database if needed foreach ($this->changed_files as $file => $action) { if (YDStringUtil::startsWith(YDUpdateTools::shortPath($file), '%YD_WEBLOG_HOME%/include/dbupdates/')) { YDDatabaseTools::installDbUpdate($file); } } // Save the new version number $this->updateDb->saveVersionNumber(); // Unlock the weblog application YDDatabaseTools::unlockDb(); // Delete the downloaded files YDUpdateLog::info('Cleaning up the file downloads...'); foreach ($this->changed_files as $file => $action) { @unlink(YDUpdateTools::tempPath($file)); } // Clear the weblog cache YDUpdateLog::info('Clearing the weblog cache...'); $cachePatterns = array(YD_WEBLOG_CACHE_PREFIX . '*.' . YD_WEBLOG_CACHE_SUFFIX, YD_TMP_PRE . 'N_*.*', '*.wch', '*.tpl.php', YD_TMP_PRE . 'U_*.upd'); $dir = new YDFSDirectory(YD_DIR_TEMP); foreach ($cachePatterns as $pattern) { $filesToDelete = $dir->getContents($pattern, null); foreach ($filesToDelete as $file) { @unlink($file->getAbsolutePath()); } } // Show a message echo '</p><p class="title">Software is now updated to version ' . $this->updateDb->getLastRevision() . '</p>'; }
/** * This filter reads a date form element result and returns a custom result * * @param $data The data to filter. * @param $option (Optional) Filter option. By default, is returned the timestamp * * @returns The filtered data as a string. */ function YDFormFilter_dateformat($data, $option = "timestamp") { if (isset($data[$option])) { return $data[$option]; } YDInclude('YDUtil.php'); return YDStringUtil::formatDate($data, $option); }
/** * This checks if the specified text is a valid HTTP url. It should start with http:// and it should have at * least one dot in there. * * @param $val The value to test. * @param $opts (not required) */ function httpurl($val, $opts = array()) { // Return true if empty if (empty($val)) { return true; } // Convert to lowercase and trim $val = strtolower(trim($val)); // Add http:// if needed if (substr($val, 0, 7) != 'http://') { $val = 'http://' . $val; } // Check if it starts with http:// if (!YDStringUtil::startsWith($val, 'http://')) { return false; } // Check the hostname $host = substr($val, 7); if (strpos($host, '/') !== false) { $host = trim(substr($host, 0, strpos($host, '/'))); } if (strpos($host, ':') !== false) { $host = trim(substr($host, 0, strpos($host, ':'))); } // Localhost is allowed if ($host == 'localhost') { return true; } // Check that we have at least a dot return strpos($host, '.') === false ? false : true; }
/** * This function execute the SQL statement passed and adds it's * results to the object. * * @param $sql The SQL statement. * @param $limit (optional) How many records to return. * @param $offset (optional) Where to start from. * * @returns The number of records found. */ function findSql($sql, $limit = -1, $offset = -1, $prefixes = array()) { YDDebugUtil::debug(YDStringUtil::removeWhiteSpace($sql)); if ($limit != -1 || $offset != -1) { $this->setLimit($limit, $offset); } $results = $this->__db->getRecords($sql, $this->__limit, $this->__offset); $this->__results = array(); $this->__count = $results ? sizeof($results) : 0; $this->resetQuery(); if (!$results) { return $this->__count; } if (!sizeof($prefixes)) { $prefixes = array(''); } for ($i = 0; $i < count($prefixes); $i++) { $prefix = sizeof($prefixes) > 1 ? substr('0' . ($i + 1) . '_', -3) : ''; $var = $prefixes[$i]; if (!strlen($var)) { $dataobject =& $this; } else { $dataobject =& $this->{$var}; } $dataobject->__results = array(); if (sizeof($prefixes) > 1) { // Find the range of fields with prefix $first_result = $results[0]; ksort($first_result); $pos = false; $length = 0; $j = 0; foreach ($first_result as $field => $value) { if (substr($field, 0, strlen($prefix)) == $prefix) { if ($pos === false) { $pos = $j; } $length++; } $j++; } // Filter the range of prefix for each result $j = 0; $continue = true; while ($continue) { $result =& $results[$j]; ksort($result); $j++; $res = array_splice($result, $pos, $length); // Take out the prefix $res_noprefix = array(); foreach ($res as $field => $value) { $field = substr($field, strlen($prefix), strlen($field) - strlen($prefix)); $res_noprefix[$field] = $value; } unset($res); // Add the result to the dataobject $dataobject->__results[] = $res_noprefix; if (!array_key_exists($j, $results)) { $continue = false; } } } else { $dataobject->__results = $results; } if ($this->__count == 1) { $dataobject->setValues($dataobject->__results[0]); } } return $this->__count; }
/** * This function processes the specified action. * * @param $action The action name. * @param $enable_callbacks Default is true. Use this to disable callback processing. * * @returns Returns an array containing results returned from action and callback processing. * Elements of this array are keyed by strings: * action:before * <actionname>:before * <actionname> * <actionname>:after * action:after * * @internal */ function _processAction($action, $enable_callbacks = true) { if (!YDStringUtil::startsWith($action, 'action')) { $action = 'action' . $action; } $results = array(); if ($enable_callbacks == true) { $results['action:before'] = $this->_executeCallbacks('action', true); $results[$action . ':before'] = $this->_executeCallbacks($action, true); } $results[$action] = call_user_func(array($this, $action)); if ($enable_callbacks == true) { $results[$action . ':after'] = $this->_executeCallbacks($action, false); $results['action:after'] = $this->_executeCallbacks('action', false); } return $results; }
/** * This function will remove all newlines and all spaces at the beginning and end of each line. * * @param $string String to remove the whitespace from. * * @returns The original string without the newlines and spaces at the beginning and end of each line. * * @static */ function removeWhiteSpace($string) { // First, normalize the newlines $string = YDStringUtil::normalizeNewLines($string); // Now, remove the whitespace $string = implode(' ', array_map('trim', explode(YD_CRLF, $string))); // Return the changed string return $string; }
/** * This function returns a list with an instance of each loaded module. * * @returns A list with an instance of each loaded module. */ function getModuleList() { $modules = array(); foreach (get_declared_classes() as $class) { if (YDStringUtil::startsWith($class, YD_SIMPLECMS_MODULE_PREFIX)) { $modules[$class] = new $class($this); } } return $modules; }
/** * This function updates a node fields ( that are NOT RESERVED only ) * * @param $values The field values of the node. Do NOT update position, parent_id, lineage or level * @param $id (optional) The ID of the node to update. * @param $onDate (optional) When element of $values is a date (read: array ), we should convert to this format. Default: 'datetimesql' * @param $updateChildren (optional) Flag that defines is children nodes of $id should be updated too. By default: false. * * @returns Total of lines affected */ function updateNode($values, $id, $onDate = 'datetimesql', $updateChildren = false) { // check values foreach ($values as $element => $value) { if (is_array($value)) { $values[$element] = YDStringUtil::formatDate($value, $onDate); } } $this->resetAll(); // apply custom values $this->setValues($values); // unset reserved fields $this->unsetVar($this->__parent); $this->unsetVar($this->__lineage); $this->unsetVar($this->__level); $this->unsetVar($this->__position); if ($updateChildren) { $this->where('(' . $this->__table_lineage . ' LIKE "%/' . intval($id) . '/%" OR ' . $this->__table_id . ' = ' . intval($id) . ')'); } else { $this->set($this->__id, intval($id)); } return $this->update(); }
function YDTplModDate($text, $format = null) { if (is_null($format)) { $format = '%A, %d %b %Y'; } return YDStringUtil::encodeString(ucwords(strtolower(YDTemplate_modifier_date_format($text, $format)))); }
/** * This function execute the SQL statement passed and adds it's * results to the object. * * @param $sql The SQL statement. * @param $slices (optional) The slices of the query. * * @returns The number of records found. */ function findSql($sql, $slices = array()) { YDDebugUtil::debug(YDStringUtil::removeWhiteSpace($sql)); $fetch = YDConfig::get('YD_DB_FETCHTYPE'); YDConfig::set('YD_DB_FETCHTYPE', YD_DB_FETCH_NUM); $results = $this->_db->getRecords($sql); YDConfig::set('YD_DB_FETCHTYPE', $fetch); if (!sizeof($slices)) { $slices = array(0 => ''); } reset($slices); $var = current($slices); while ($var !== false) { $curr_pos = key($slices); $next = next($slices); $next_pos = $next ? key($slices) : false; if (!$var) { $obj =& $this; } else { $obj =& $this->{$var}; } $obj->resetResults(); $obj->_count = $results ? sizeof($results) : 0; $select = $obj->_query->select; foreach ($results as $result) { if (!$next_pos) { $next_pos = sizeof($result); } $length = $next_pos - $curr_pos; $res = array_slice($result, $curr_pos, $length); $new_res = array(); for ($i = 0; $i < sizeof($res); $i++) { $new_res[$select[$i]['alias']] = $res[$i]; } $obj->_results[] = $new_res; } $obj->resetQuery(); if ($obj->_count >= 1) { $obj->setValues($obj->_results[0]); } $var = current($slices); } return $this->_count; }
/** * @internal */ function YDTemplate_modifier_fmtfileize($size) { return YDStringUtil::formatFileSize($size); }