branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>epdtry/emscripten-fastcomp<file_sep>/lib/Target/CppBackend/readme.txt TODO: restore old cpp backend to here <file_sep>/lib/Transforms/NaCl/ExpandStructRegs.cpp //===- ExpandStructRegs.cpp - Expand out variables with struct type--------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass expands out some uses of LLVM variables // (a.k.a. registers) of struct type. It replaces loads and stores of // structs with separate loads and stores of the structs' fields. The // motivation is to omit struct types from PNaCl's stable ABI. // // ExpandStructRegs does not yet handle all possible uses of struct // values. It is intended to handle the uses that Clang and the SROA // pass generate. Clang generates struct loads and stores, along with // extractvalue instructions, in its implementation of C++ method // pointers, and the SROA pass sometimes converts this code to using // insertvalue instructions too. // // ExpandStructRegs does not handle: // // * Nested struct types. // * Array types. // * Function types containing arguments or return values of struct // type without the "byval" or "sret" attributes. Since by-value // struct-passing generally uses "byval"/"sret", this does not // matter. // // Other limitations: // // * ExpandStructRegs does not attempt to use memcpy() where that // might be more appropriate than copying fields individually. // * ExpandStructRegs does not preserve the contents of padding // between fields when copying structs. However, the contents of // padding fields are not defined anyway. // //===----------------------------------------------------------------------===// #include "llvm/ADT/SmallVector.h" #include "llvm/IR/Function.h" #include "llvm/IR/Instructions.h" #include "llvm/Pass.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/NaCl.h" using namespace llvm; namespace { struct ExpandStructRegs : public FunctionPass { static char ID; // Pass identification, replacement for typeid ExpandStructRegs() : FunctionPass(ID) { initializeExpandStructRegsPass(*PassRegistry::getPassRegistry()); } virtual bool runOnFunction(Function &F); }; } char ExpandStructRegs::ID = 0; INITIALIZE_PASS(ExpandStructRegs, "expand-struct-regs", "Expand out variables with struct types", false, false) static void SplitUpPHINode(PHINode *Phi) { StructType *STy = cast<StructType>(Phi->getType()); Value *NewStruct = UndefValue::get(STy); Instruction *NewStructInsertPt = Phi->getParent()->getFirstInsertionPt(); // Create a separate PHINode for each struct field. for (unsigned Index = 0; Index < STy->getNumElements(); ++Index) { SmallVector<unsigned, 1> EVIndexes; EVIndexes.push_back(Index); PHINode *NewPhi = PHINode::Create( STy->getElementType(Index), Phi->getNumIncomingValues(), Phi->getName() + ".index", Phi); CopyDebug(NewPhi, Phi); for (unsigned PhiIndex = 0; PhiIndex < Phi->getNumIncomingValues(); ++PhiIndex) { BasicBlock *IncomingBB = Phi->getIncomingBlock(PhiIndex); Value *EV = CopyDebug( ExtractValueInst::Create( Phi->getIncomingValue(PhiIndex), EVIndexes, Phi->getName() + ".extract", IncomingBB->getTerminator()), Phi); NewPhi->addIncoming(EV, IncomingBB); } // Reconstruct the original struct value. NewStruct = CopyDebug( InsertValueInst::Create(NewStruct, NewPhi, EVIndexes, Phi->getName() + ".insert", NewStructInsertPt), Phi); } Phi->replaceAllUsesWith(NewStruct); Phi->eraseFromParent(); } static void SplitUpSelect(SelectInst *Select) { StructType *STy = cast<StructType>(Select->getType()); Value *NewStruct = UndefValue::get(STy); // Create a separate SelectInst for each struct field. for (unsigned Index = 0; Index < STy->getNumElements(); ++Index) { SmallVector<unsigned, 1> EVIndexes; EVIndexes.push_back(Index); Value *TrueVal = CopyDebug( ExtractValueInst::Create(Select->getTrueValue(), EVIndexes, Select->getName() + ".extract", Select), Select); Value *FalseVal = CopyDebug( ExtractValueInst::Create(Select->getFalseValue(), EVIndexes, Select->getName() + ".extract", Select), Select); Value *NewSelect = CopyDebug( SelectInst::Create(Select->getCondition(), TrueVal, FalseVal, Select->getName() + ".index", Select), Select); // Reconstruct the original struct value. NewStruct = CopyDebug( InsertValueInst::Create(NewStruct, NewSelect, EVIndexes, Select->getName() + ".insert", Select), Select); } Select->replaceAllUsesWith(NewStruct); Select->eraseFromParent(); } template <class InstType> static void ProcessLoadOrStoreAttrs(InstType *Dest, InstType *Src) { CopyDebug(Dest, Src); Dest->setVolatile(Src->isVolatile()); if (Src->isAtomic()) { errs() << "Use: " << *Src << "\n"; report_fatal_error("Atomic struct loads/stores not supported"); } // Make a pessimistic assumption about alignment. Preserving // alignment information here is tricky and is not really desirable // for PNaCl because mistakes here could lead to non-portable // behaviour. Dest->setAlignment(1); } template <typename StructOrArrayType> static void SplitUpStore(StoreInst *Store) { StructOrArrayType *STy = cast<StructOrArrayType>(Store->getValueOperand()->getType()); // Create a separate store instruction for each struct field. for (unsigned Index = 0; Index < STy->getNumElements(); ++Index) { SmallVector<Value *, 2> Indexes; Indexes.push_back(ConstantInt::get(Store->getContext(), APInt(32, 0))); Indexes.push_back(ConstantInt::get(Store->getContext(), APInt(32, Index))); Value *GEP = CopyDebug(GetElementPtrInst::Create( Store->getPointerOperand(), Indexes, Store->getPointerOperand()->getName() + ".index", Store), Store); SmallVector<unsigned, 1> EVIndexes; EVIndexes.push_back(Index); Value *Field = ExtractValueInst::Create(Store->getValueOperand(), EVIndexes, "", Store); StoreInst *NewStore = new StoreInst(Field, GEP, Store); ProcessLoadOrStoreAttrs(NewStore, Store); if (NewStore->getValueOperand()->getType()->isStructTy()) { SplitUpStore<StructType>(NewStore); } else if (NewStore->getValueOperand()->getType()->isArrayTy()) { SplitUpStore<ArrayType>(NewStore); } } Store->eraseFromParent(); } template <typename StructOrArrayType> static void SplitUpLoad(LoadInst *Load) { StructOrArrayType *STy = cast<StructOrArrayType>(Load->getType()); Value *NewStruct = UndefValue::get(STy); // Create a separate load instruction for each struct field. for (unsigned Index = 0; Index < STy->getNumElements(); ++Index) { SmallVector<Value *, 2> Indexes; Indexes.push_back(ConstantInt::get(Load->getContext(), APInt(32, 0))); Indexes.push_back(ConstantInt::get(Load->getContext(), APInt(32, Index))); Value *GEP = CopyDebug( GetElementPtrInst::Create(Load->getPointerOperand(), Indexes, Load->getName() + ".index", Load), Load); LoadInst *NewLoad = new LoadInst(GEP, Load->getName() + ".field", Load); ProcessLoadOrStoreAttrs(NewLoad, Load); // Reconstruct the struct value. SmallVector<unsigned, 1> EVIndexes; EVIndexes.push_back(Index); NewStruct = CopyDebug( InsertValueInst::Create(NewStruct, NewLoad, EVIndexes, Load->getName() + ".insert", Load), Load); if (NewLoad->getType()->isStructTy()) { SplitUpLoad<StructType>(NewLoad); } else if (NewLoad->getType()->isArrayTy()) { SplitUpLoad<ArrayType>(NewLoad); } } Load->replaceAllUsesWith(NewStruct); Load->eraseFromParent(); } static Value *GetExtractedValue(ExtractValueInst *EV); template <typename StructOrArrayType> static Value *GetExtractedCompoundValue(ExtractValueInst *EV) { StructOrArrayType *STy = cast<StructOrArrayType>(EV->getType()); Value *NewStruct = UndefValue::get(STy); SmallVector<unsigned, 4> Indexes; for (unsigned I = 0; I < EV->getNumIndices(); ++I) { Indexes.push_back(EV->getIndices()[I]); } Indexes.push_back(0); for (unsigned I = 0; I < STy->getNumElements(); ++I) { Indexes.back() = I; // Skip copying debug info, since NewEV is never actually added to the // basic block. ExtractValueInst *NewEV = ExtractValueInst::Create(EV->getAggregateOperand(), Indexes, EV->getName() + ".extract", EV); Value *ExtractedValue = GetExtractedValue(NewEV); NewEV->eraseFromParent(); SmallVector<unsigned, 1> IVIndexes; IVIndexes.push_back(I); NewStruct = CopyDebug( InsertValueInst::Create(NewStruct, ExtractedValue, IVIndexes, EV->getName() + ".insert", EV), EV); } return NewStruct; } static Value *GetExtractedValue(ExtractValueInst *EV) { if (EV->getType()->isStructTy()) { return GetExtractedCompoundValue<StructType>(EV); } else if (EV->getType()->isArrayTy()) { return GetExtractedCompoundValue<ArrayType>(EV); } // Search for the insertvalue instruction that inserts the struct // field referenced by this extractvalue instruction. Value *CurrentVal = EV->getAggregateOperand(); unsigned I = 0; while (I < EV->getNumIndices()) { if (InsertValueInst *IV = dyn_cast<InsertValueInst>(CurrentVal)) { bool AllMatch = true; for (unsigned J = 0; J < IV->getNumIndices(); ++J) { if (I + J >= EV->getNumIndices()) { // We're matching `extractvalue %foo, 0, 1` (I = 0) against // `%foo = insertvalue %bar, %baz, 0, 1, 2`. // That means we're extracting a struct/array value that was built // using multiple `insertvalue` instructions. errs() << "Extract: " << *EV << "\n"; errs() << "Indices handled so far: " << I << "\n"; errs() << "Insert: " << *IV << "\n"; report_fatal_error("ExpandStructRegs does not handle extracting " "values built with multiple insertvalue instructions"); } if (EV->getIndices()[I + J] != IV->getIndices()[J]) { AllMatch = false; break; } } if (AllMatch) { // We handled some of the `extractvalue` indices, but possibly not all // of them. CurrentVal = IV->getInsertedValueOperand(); I += IV->getNumIndices(); continue; } else { // No match. Try the next struct value in the chain. CurrentVal = IV->getAggregateOperand(); } } else if (Constant *C = dyn_cast<Constant>(CurrentVal)) { // C is the value of `extractvalue %foo, idx0, ..., idx(I-1)`. Use the // remaining indices to get the final result. CurrentVal = ConstantExpr::getExtractValue(C, EV->getIndices().slice(I)); break; } else { errs() << "Value: " << *CurrentVal << "\n"; report_fatal_error("Unrecognized struct value"); } } return CurrentVal; } static void ExpandExtractValue(ExtractValueInst *EV) { EV->replaceAllUsesWith(GetExtractedValue(EV)); EV->eraseFromParent(); } bool ExpandStructRegs::runOnFunction(Function &Func) { bool Changed = false; // Split up aggregate loads, stores and phi nodes into operations on // scalar types. This inserts extractvalue and insertvalue // instructions which we will expand out later. for (Function::iterator BB = Func.begin(), E = Func.end(); BB != E; ++BB) { for (BasicBlock::iterator Iter = BB->begin(), E = BB->end(); Iter != E; ) { Instruction *Inst = Iter++; if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) { if (Store->getValueOperand()->getType()->isStructTy()) { SplitUpStore<StructType>(Store); Changed = true; } else if (Store->getValueOperand()->getType()->isArrayTy()) { SplitUpStore<ArrayType>(Store); Changed = true; } } else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) { if (Load->getType()->isStructTy()) { SplitUpLoad<StructType>(Load); Changed = true; } else if (Load->getType()->isArrayTy()) { SplitUpLoad<ArrayType>(Load); Changed = true; } } else if (PHINode *Phi = dyn_cast<PHINode>(Inst)) { if (Phi->getType()->isStructTy()) { SplitUpPHINode(Phi); Changed = true; } } else if (SelectInst *Select = dyn_cast<SelectInst>(Inst)) { if (Select->getType()->isStructTy()) { SplitUpSelect(Select); Changed = true; } } } } // Expand out all the extractvalue instructions. for (Function::iterator BB = Func.begin(), E = Func.end(); BB != E; ++BB) { for (BasicBlock::iterator Iter = BB->begin(), E = BB->end(); Iter != E; ) { Instruction *Inst = Iter++; if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Inst)) { ExpandExtractValue(EV); Changed = true; } } } // Now collect up all the insertvalue instructions for deletion. This must // happen after expanding all extractvalues in order to catch insertvalues // introduced by GetExtractedCompoundValue. SmallVector<Instruction *, 10> ToErase; for (Function::iterator BB = Func.begin(), E = Func.end(); BB != E; ++BB) { for (BasicBlock::iterator Iter = BB->begin(), E = BB->end(); Iter != E; ) { Instruction *Inst = Iter++; if (isa<InsertValueInst>(Inst)) { ToErase.push_back(Inst); Changed = true; } } } // Delete the insertvalue instructions. These can reference each // other, so we must do dropAllReferences() before doing // eraseFromParent(), otherwise we will try to erase instructions // that are still referenced. for (SmallVectorImpl<Instruction *>::iterator I = ToErase.begin(), E = ToErase.end(); I != E; ++I) { (*I)->dropAllReferences(); } for (SmallVectorImpl<Instruction *>::iterator I = ToErase.begin(), E = ToErase.end(); I != E; ++I) { (*I)->eraseFromParent(); } return Changed; } FunctionPass *llvm::createExpandStructRegsPass() { return new ExpandStructRegs(); } <file_sep>/lib/Target/JSBackend/JSTargetMachine.cpp #include "JSTargetMachine.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/PassManager.h" using namespace llvm; JSTargetMachine::JSTargetMachine(const Target &T, StringRef Triple, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL) : TargetMachine(T, Triple, CPU, FS, Options), DL("e-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-" "f32:32:32-f64:64:64-p:32:32:32-v128:32:128-n32-S128") { CodeGenInfo = T.createMCCodeGenInfo(Triple, RM, CM, OL); } <file_sep>/lib/Target/JSBackend/TargetInfo/JSBackendTargetInfo.cpp //===-- JSBackendTargetInfo.cpp - JSBackend Target Implementation -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===--------------------------------------------------------------------===// #include "JSTargetMachine.h" #include "MCTargetDesc/JSBackendMCTargetDesc.h" #include "llvm/IR/Module.h" #include "llvm/Support/TargetRegistry.h" using namespace llvm; Target llvm::TheJSBackendTarget; static unsigned JSBackend_TripleMatchQuality(const std::string &TT) { switch (Triple(TT).getArch()) { case Triple::asmjs: // That's us! return 20; case Triple::le32: case Triple::x86: // For compatibility with older versions of Emscripten, we also basically // support generating code for le32-unknown-nacl and i386-pc-linux-gnu, // but we use a low number here so that we're not the default. return 1; default: return 0; } } extern "C" void LLVMInitializeJSBackendTargetInfo() { TargetRegistry::RegisterTarget(TheJSBackendTarget, "js", "JavaScript (asm.js, emscripten) backend", &JSBackend_TripleMatchQuality); }
b4f3dc1915a70e691cf2db7ed9745feca4d0f7af
[ "Text", "C++" ]
4
Text
epdtry/emscripten-fastcomp
1331b061fcb813dad71719792a89fa5cc396864a
704f8e16d9116b8aceaf2fdcb6128bcf4a6444c7
refs/heads/master
<file_sep>// // ViewController.swift // PlaceHolderTextView // // Created by langyue on 16/1/25. // Copyright © 2016年 langyue. All rights reserved. // import UIKit class ViewController: UIViewController { var textView : PHTextView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.setupLabel() self.setupTextView() } func setupLabel(){ let titleLabel = UILabel(frame: CGRectMake(0,40,self.view.frame.size.width,44)) titleLabel.text = "自定义textView控件" titleLabel.textAlignment = NSTextAlignment.Center titleLabel.textColor = UIColor.blackColor() self.view.addSubview(titleLabel) } func setupTextView(){ let textView = PHTextView() textView.frame = CGRectMake(0, 100, self.view.frame.size.width, 200) textView.backgroundColor = UIColor.lightGrayColor() textView.font = UIFont.systemFontOfSize(15) //设置占位文字 textView.placeholder = "这里是占位文字..." self.view.addSubview(textView) self.textView = textView NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: textView) } func textDidChange(){ if self.textView.hasText() == true { print("文字发生改变----%@",self.textView.text) } } deinit{ NSNotificationCenter.defaultCenter().removeObserver(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep>// // PHTextView.swift // PlaceHolderTextView // // Created by langyue on 16/1/25. // Copyright © 2016年 langyue. All rights reserved. // import UIKit class PHTextView: UITextView { /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ //占位文字 var placeholder : NSString? { didSet{ self.setNeedsDisplay() } } //占位文字颜色 var placeholderColor : UIColor? override internal var text: String! { didSet{ self.setNeedsDisplay() } } override internal var font: UIFont?{ didSet{ self.setNeedsDisplay() } } override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: self) } func textDidChange(){ self.setNeedsDisplay() } override func drawRect(rect: CGRect) { if self.hasText(){ return}; var attributes : Dictionary<String,AnyObject> = [NSFontAttributeName:self.font!] attributes[NSForegroundColorAttributeName] = (self.placeholderColor == nil) ? (self.placeholderColor) : (UIColor .grayColor()) let x : CGFloat = 5 let width = rect.size.width - 2 * x let y : CGFloat = 8 let height = rect.size.width - 2 * y let placeholderRect = CGRectMake(x, y, width, height) self.placeholder!.drawInRect(placeholderRect, withAttributes: attributes) } deinit{ NSNotificationCenter.defaultCenter().removeObserver(self) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
1febc492ce78362e33dbf7c3e66dec1d6f657b1d
[ "Swift" ]
2
Swift
LiuLongChang/PlaceHolderTextView
6bd22db660d1d004496646cf26c488e75585b393
77a4713ee7cae07039adb1a82c8d42467f04e1f0
refs/heads/master
<repo_name>jasondavis/WPMigrate<file_sep>/wp-migrate.php <?php require_once('wp-load.php'); ?> <html> <head> <title>Migrate WP Site</title> <style type="text/css"> body { font-family:"Lucida Sans","Lucida Grande","Lucida Unicode","Lucida",sans-serif; background-color: #666; } h1 { font-size:24px; margin:0; padding:5px; color:#fff; text-shadow: 1px 1px rgba(0,0,0,0.2); background-color: rgba(0,0,0,0.6); -moz-border-radius:9px; -webkit-border-radius:9px; -khtml-border-radius:9px; border-radius:9px; } h2 { font-size: 18px; } #container { width:600px; margin:20px auto; border:1px solid #333; background-color: rgba(255,255,255,0.8); -moz-border-radius:10px; -webkit-border-radius:10px; -khtml-border-radius:10px; border-radius:10px; } #content { padding:20px; } p { font-size:14px; line-height: 18px; margin-bottom: 18px; } p:last-child { margin-bottom: 0; } a, a:visited { color:#20668a; } ul { margin:10px; padding: 0; list-style: square; } form {} label { display: block; font-weight:bold; } input[type=text] { display: block; -moz-border-radius:5px; -webkit-border-radius:5px; -khtml-border-radius:5px; border-radius:5px; width: 100%; margin-bottom: 10px; padding: 5px; } input[type=submit] { color:#fff; background: #20668a; -moz-border-radius:5px;; -webkit-border-radius:5px; -khtml-border-radius:5px; border-radius:5px; text-shadow: 1px 1px #0b4462; box-shadow: 1px 1px 3px rgba(0,0,0,0.5); font-size:14px; font-weight:bold; position: relative; cursor: pointer; float:right; margin:10px 0; border:none; } input[type=submit]:active { left:1px; top:1px; } .message { padding:5px; margin:10px 0; border-width: 2px; border-style: solid; list-style: none; -moz-border-radius:5px; -webkit-border-radius:5px; -khtml-border-radius:5px; border-radius:5px; } .message.success { color:#30ac12; border-color: #30ac12; background-color: #afd9a5; } .message.warning { border-color: #efce15; color: #957236; background-color: #f2e8af; } .message.error { border-color: #c51414; color: #c51414; background-color: #f5a2a2; } </style> </head> <body> <div id="container"> <h1>Migrate WordPress Site</h1> <div id="content"> <?php global $wpdb; if ( !$_POST['submit_update_url'] ) { //FORM HAS NOT BEEN SUBMITTED ?> <p class="message warning">This script will update all references in the DB to a new URL. Before proceeding, you should <a href="http://codex.wordpress.org/Backing_Up_Your_Database" target="_blank">make a complete backup of your database</a>.</p> <ul> <li>The current WP URL is: <strong><?php echo get_bloginfo('url'); ?></strong></li> <li>Database: <?php echo DB_NAME; ?></li> <li>DB Host: <?php echo DB_HOST; ?></li> </ul> <form action="#" method="post"> <label for="old_url">Current URL</label> <input type="text" name="old_url" value="<?php echo get_bloginfo('url'); ?>" class="text" /> <label for="new_url">New URL</label> <input type="text" name="new_url" class="text" /> <input type="submit" name="submit_update_url" value="Update Database" class="button " /> <p style="display:block;">&nbsp;</p> </form> <?php } else { extract($_POST); //CHECK FOR ERRORS if ( !$old_url || !$new_url ) { echo '<p class="message error">You must enter both the old and new URLs.</p>'; die(); } //SHOW SQL ERRORS $wpdb->show_errors(); echo '<h2>Updating Database...</h2>'; echo '<ul>'; $error = false; $options_query = "UPDATE $wpdb->options SET option_value = replace(option_value, '$old_url', '$new_url') WHERE option_name = 'home' OR option_name = 'siteurl'"; if ( $wpdb->query($options_query) ) { echo '<li class="message success">Options table updated successfully.</li>'; } else { echo '<li class="message error">Problem updating options table.'; echo $wpdb->print_error().'</li>'; $error = true; } $posts_query = "UPDATE $wpdb->posts SET guid = replace(guid, '$old_url','$new_url')"; if ( $wpdb->query($posts_query) ) { echo '<li class="message success">Posts table updated successfully.</li>'; } else { echo '<li class="message error">Problem updating posts table. '; echo $wpdb->print_error().'</li>'; $error = true; } $items_query = "UPDATE $wpdb->posts SET post_content = replace(post_content, '$old_url', '$new_url')"; if ( $wpdb->query($items_query) ) { echo '<li class="message success">All posts/pages updated successfully.</li>'; } else { echo '<li class="message error">Problem updating posts/pages. '; echo $wpdb->print_error().'</li>'; $error = true; } $meta_query = "UPDATE $wpdb->postmeta SET meta_value = replace(meta_value, '$old_url', '$new_url')"; if ( $wpdb->query($meta_query) ) { echo '<li class="message success">All custom fields updated successfully.</li>'; } else { echo '<li class="message error">Problem updating custom fields. '; echo $wpdb->print_error().'</li>'; $error = true; } if (!$error) { echo '<p class="message success">All done. <a href="'.$new_url.'">Go to home page</a> | <a href="'.$new_url.'/wp-migrate.php">Do another migration</a></p>'; echo '<p class="message warning">You should delete the \'wp-migrate.php\' file from your root directory. Failing to do so is a major security risk and could cause your site to be hacked.</p>'; } echo '</ul>'; } ?> </div><!--#content --> </div><!-- #container --> </body> </html>
cb3a7921c93de30fdfaa6b273a0dfedd3468a878
[ "PHP" ]
1
PHP
jasondavis/WPMigrate
d3f217017be76761e39dc607073e790751979092
c868f9bc89b3eedbec6024cc177828248bf8ff2e
refs/heads/main
<repo_name>DeveloperGulam/Ajax-Product-Filter<file_sep>/fetch.php <?php //fetch.php $connect = mysqli_connect("localhost","root","","machine_test"); $query="SELECT * FROM products WHERE price BETWEEN '".$_POST["minimum_range"]."' AND '".$_POST["maximum_range"]."' ORDER BY price ASC"; $fire = mysqli_query($connect,$query); $total_row = mysqli_num_rows($fire); $output = '<h4 align="center">Total Item - '.$total_row.'</h4><div class="row">'; if($total_row > 0) { while($fetch=mysqli_fetch_array($fire,MYSQLI_BOTH)) { $output .= ' <div class="col-md-2"> <img src="product/'.$fetch["product_img"].'" style="height:150px;width:150px;" /> <h4 align="center">'.$fetch["product_name"].'</h4> <h3 align="center" class="text-danger">Price: '.$fetch["price"].'</h3> <br /> </div> '; } } else { $output .= ' <h3 align="center">No Product Found</h3> '; } $output .= ' </div> '; echo $output; ?><file_sep>/machine_test.sql -- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Jul 30, 2021 at 02:08 PM -- Server version: 10.4.14-MariaDB -- PHP Version: 7.4.9 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `machine_test` -- -- -------------------------------------------------------- -- -- Table structure for table `products` -- CREATE TABLE `products` ( `id` int(11) NOT NULL, `product_name` varchar(75) NOT NULL, `product_img` varchar(255) NOT NULL, `price` int(11) NOT NULL, `pincode` varchar(6) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `products` -- INSERT INTO `products` (`id`, `product_name`, `product_img`, `price`, `pincode`) VALUES (1, 'Vivo X60', 'vivo3.jpg', 3999, '400703'), (2, 'OnePlus 8T', 'oneplus.jpg', 4999, '226007'), (3, 'Redmi 9', 'redmi.jpg', 1999, '226006'), (4, 'LG Phone', 'lg.jpg', 2499, '226007'), (5, 'Iphone 10', 'iphone.jpg', 4999, '400703'), (6, 'Vivo V19', 'vivo2.jpg', 3999, '226006'); -- -- Indexes for dumped tables -- -- -- Indexes for table `products` -- ALTER TABLE `products` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `products` -- ALTER TABLE `products` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/index.php <?php //index.php $minimum_range = 1500; $maximum_range = 5000; ?> <html> <head> <link rel="stylesheet" href="https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <br /> <br /> <input type="text" name="pincode" id="pincode" placeholder="Filter By Pincode" /> <button id="Filter2" type="button">Filter</button> <br /> <br /> <div class="row"> <div class="col-md-2"> <input type="text" name="minimum_range" id="minimum_range" class="form-control" value="<?php echo $minimum_range; ?>" /> </div> <div class="col-md-8" style="padding-top:12px"> <div id="price_range"></div> </div> <div class="col-md-2"> <input type="text" name="maximum_range" id="maximum_range" class="form-control" value="<?php echo $maximum_range; ?>" /> </div> </div> <br /> <div id="load_product"></div> <br /> </div> </body> </html> <script> $(document).ready(function(){ $('#price_range').slider({ range:true, min:1500, max:5000, values:[<?php echo $minimum_range; ?>, <?php echo $maximum_range; ?>], slide:function(event, ui){ $("#minimum_range").val(ui.values[0]); $('#maximum_range').val(ui.values[1]); load_product(ui.values[0], ui.values[1]); } }); load_product(<?php echo $minimum_range; ?>, <?php echo $maximum_range; ?>) ; function load_product(minimum_range, maximum_range) { $.ajax({ url:"fetch.php", method:"POST", data:{minimum_range:minimum_range, maximum_range:maximum_range}, success:function(data) { $('#load_product').html(data); } }); } $("#Filter2").click(function(){ var pincode = $("#pincode").val(); $.ajax({ url:"fetch2.php", method:"POST", data:{"pincode":pincode}, success:function(data) { $('#load_product').html(data); } }); }); }); </script>
35aaf5ce7e2865eba26018b576c19486822322f8
[ "SQL", "PHP" ]
3
PHP
DeveloperGulam/Ajax-Product-Filter
e31bddcaec9c53dcd77eb4f880152d88fb7c9a22
d209c9a3941e86d8e851d03e97965be9084287ec
refs/heads/master
<repo_name>Farhan71/react-online-course-dashboard<file_sep>/src/components/Courses/Courses.js import React from 'react'; import './Courses.css' const Courses = (props) => { // console.log (props) const {course_name, instructor_name, price, rating, taken_by, ask_anything_at}= props.course const handleEnrollCourse = props.handleEnrollCourse const cardWidth = { width: "900px" } return ( <div className="card course_detail" style={cardWidth}> <div className="card-body"> <h5 className="card-title text-danger" > Course name:- {course_name}</h5> <p className="card-text"> <p> Instructor: {instructor_name}</p> <p> Price: ${price}</p> <p> Rating: {rating}</p> <p> Taken by: {taken_by} students</p> <p> Ask anything at: {ask_anything_at}</p> </p> <button className="btn btn-primary" onClick={()=> handleEnrollCourse(props.course)}> Enroll Now</button> </div> </div> ); }; export default Courses;<file_sep>/src/components/Shop/Shop.js import React, { useEffect, useState } from 'react'; import Cart from '../Cart/Cart'; import fakedata from '../../MOCK_DATA.json' import Courses from '../Courses/Courses'; import './Shop.css' const Shop = () => { // console.log (fakedata) const [data, setData]= useState([]); const [cart, setCart] = useState([]); useEffect(()=> { setData(fakedata) },[]) const handleEnrollCourse = (course) => { const newCart = [...cart, course] setCart (newCart) // console.log ("Enrolled course") } return ( <div className="shop"> <div className="course"> {/* <h2 >This is shop</h2> */} { // console.log (data) data.map ( (course) => <Courses course = {course} handleEnrollCourse={handleEnrollCourse}></Courses> ) } </div> <div className="cart"> <Cart cart ={cart}></Cart> </div> </div> ); }; export default Shop;
da8410b07a0397b2d35d722c3d3761bc4539a6e7
[ "JavaScript" ]
2
JavaScript
Farhan71/react-online-course-dashboard
3fb1189b9d9fc0da8c1a3e6b19abdd9decc294f7
95c7a4fdff7f29acc3df53baac35235e545d9c55
refs/heads/master
<file_sep>#!/bin/bash -e export PACKER_DOWNLOAD_URL='https://releases.hashicorp.com/packer/0.10.0/packer_0.10.0_linux_amd64.zip' export PACKER_INSTALL_FOLDER='/opt/packer'<file_sep>#!/bin/bash -e export VBOX_GUEST_ADDITIONS_DOWNLOAD_URL='http://download.virtualbox.org/virtualbox/5.0.16/VBoxGuestAdditions_5.0.16.iso'
7ddd0f5fa437fc96cf6542ccfb320e29869c7837
[ "Shell" ]
2
Shell
RoseySoft/ubuntu-cookbooks
fdfaf468b3d7ce34669b078bf58f9ad71d522b09
472999fab1359153592edea3aed269839fa7aa83
refs/heads/master
<file_sep>module testForGit { }
7d03a3d3103f9973d2a5548e5247eab250b54155
[ "Java" ]
1
Java
hedviger/Test1
aee7b58d9467d6a3820854ceadad63c077eccb79
7c1dd335f9d42c781adce8c4121ad67ca7387528
refs/heads/master
<repo_name>canfeng/contract-js-demo<file_sep>/src/index.js import * as slt from './slt' import * as erc721 from './erc721' import * as metamask from './metamask' window['szg'] = { metamask: metamask, slt: slt, erc721: erc721 }; <file_sep>/src/metamask.js /** * 检测metamask插件 */ if (typeof window.ethereum == 'undefined') { console.warn('MetaMask未安装!'); } export let currentAccount; function getCurrentAccount(){ ethereum .request({ method: 'eth_accounts' }) .then(handleAccountsChanged) .catch((err) => { console.error(err); }); } getCurrentAccount(); /** * 监听账户变更 */ ethereum.on('accountsChanged', handleAccountsChanged); // For now, 'eth_accounts' will continue to always return an array function handleAccountsChanged(accounts) { if (accounts.length === 0) { // MetaMask is locked or the user has not connected any accounts console.log('Please connect to MetaMask.'); } else if (accounts[0] !== currentAccount) { currentAccount = accounts[0]; } console.log("当前账户地址=" + currentAccount); } /** * 建立连接,并获取账户地址 * @returns {Promise<void>} */ export async function connect() { ethereum.request({method: 'eth_requestAccounts'}) .then(handleAccountsChanged) .catch((err) => { if (err.code === 4001) { // EIP-1193 userRejectedRequest error // If this happens, the user rejected the connection request. console.log('Please connect to MetaMask.'); } else { console.error(err); } }); } export function component(name, func) { const element = document.createElement('button'); // lodash,现在通过一个 script 引入 element.innerText = name; element.addEventListener('click', func); return element; } document.body.appendChild(component('连接MetaMask', connect)); <file_sep>/src/util/ethers-util.js //初始化jsonRpcProvider import * as ethers from "ethers"; export const provider = new ethers.providers.Web3Provider(window.ethereum); export const signer = provider.getSigner(); /** * 实例化合约-用于和只读方法交互 * @param contractAddress * @returns {Contract} */ export function contractInstanceByProvider(contractAddress, abi) { return new ethers.Contract(contractAddress, abi, provider); } /** * 实例化合约-用于和写方法交互 * @param contractAddress * @returns {Contract} */ export function contractInstanceBySigner(contractAddress, abi) { return new ethers.Contract(contractAddress, abi, signer); } export { ethers }<file_sep>/README.md ### 如何开始 1. 安装依赖 ```shell script npm install ``` 2. 运行 ```shell script npm start ``` 该命令会启动一个本地服务器,自动在浏览器打开http://localhost:8080 3. 连接MetaMask:点击'连接MetaMask'按钮与MetaMask建立连接 4. 调用合约方法 - 4.1 打开开发者模式(F12) - 4.2 在Console中通过自定义全局变量`szg`进行操作。 - 4.3 示例: ``` await szg.erc721.totalSupply() await szg.erc721.addToWhitelist('0xf<KEY>') ``` ### 目录结构 ``` contract-js-demo |---dist //输出目录 |---node_modules //下载的依赖 |---src //源码目录 |---contract //智能合约相关 |---ozerc721_abi.json //OZERC721的ABI文件 |---slt_abi.json //SLT的ABI文件 |---util //工具目录 |---ethers-util.js |---erc721.js //OZERC721的wrapper |---index.js //总入口 |---metamask.js //MetaMask交互相关 |---slt.js //SLT的Wrapper |---template.html //模板html |---.babelrc |---.gitignore |---package.json //依赖管理配置文件 |---package-lock.json |---README.md |---webpack.config.js //webpack配置文件 ```<file_sep>/src/slt.js import slt_abi from './contract/slt_abi.json'; import * as ethersUtil from "./util/ethers-util"; /** * 打印SLT信息 * @returns {Promise<void>} */ export async function printSLTInfo() { let SLT = ethersUtil.contractInstanceByProvider('0xEa5ddf1cB1adF0a041E71Fe16Dc71A632D85e77d', slt_abi); console.log(await SLT.name()); console.log(await SLT.symbol()); console.log(await SLT.totalSupply()); }
bbbae3b74cf7c8dddce5547cd2dabf695ae0f46b
[ "JavaScript", "Markdown" ]
5
JavaScript
canfeng/contract-js-demo
c95c3da812197dc0aa9e851d6c3ed86835550e01
1a8a4d57ef9d7dca7976fed6f9753559ed06d53c
refs/heads/master
<repo_name>LunarShadow/LunchPicker<file_sep>/addRestaurant.php <?php /* * Author: <NAME> */ //Database connection information define("HOST","localhost"); define("USER","code"); define("PASSWORD","<PASSWORD>"); define("DATABASE","restaurant"); //check for add button click if(isset($_POST['add']) && $_POST['add'] == 'Add'){ //attempt to connect to database if successfull connection do stuff $connection = new mysqli(HOST, USER, PASSWORD, DATABASE); if(!$connection->connect_error) { $name = filter_var($_POST['name'], FILTER_SANITIZE_STRING); //check for empty name value if(!(trim($name))){ $success = "A name is required"; } else { $query = "INSERT INTO `restaurant` VALUES"."('NULL','$name')"; //add new row if name isn't empty if(!$result = $connection->query($query)){ $success = "Something went wrong, data could not be added"; }else { $success = "$name was successfully added"; } } } } ?> <!DOCTYPE html> <html> <title>add Restaurant</title> <meta charset="utf-8"> <meta name="description" content="Lets go to lunch! Not sure where to eat today?..."/> <meta name="keywords" content="Random Lunch Generator, Lunch Picker, Lunch Chooser, random string chooser" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" /> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <link href="https://fonts.googleapis.com/css?family=Handlee|Kalam|Righteous" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://www.w3schools.com/lib/w3-theme-red.css"> <style> h1,h2,h3,h4,h5,h6 {font-family: Kalam, serif;} html, body{font-family: Handlee, sans-serif;font-size:1.12em;} </style> <body class="w3-theme-l3"> <!-- Navbar --> <div class="w3-top"> <div class="w3-bar w3-theme-d1 w3-left-align w3-large"> <a href="www.jackycyntias.net" class="w3-bar-item w3-button w3-padding-large w3-theme-d4 w3-hover-white"><i class="fa fa-home w3-margin-right"></i><b>JCS</b></a> <a class="w3-bar-item w3-button w3-padding-large w3-hover-white w3-right w3-hide-small" href="http://www.jackycyntias.net/contact.php">Leave Feedback</a> </div> </div> <!-- Page Container --> <div class="w3-container w3-content" style="max-width:600px;margin-top:80px"> <form action="addRestaurant.php" method="post" class="w3-container"> <div class="w3-row w3-container"> <label for="name" class="w3-m3 w3-xlarge w3-padding">Name:</label> <div class="w3-m3"> <input class="w3-input" type="text" name="name" id="name" /> </div> <div class="w3-margin-left w3-m4 w3-padding"> <input type="submit" value="Add" class="w3-button w3-theme-d3 w3-right w3-small" name="add" /><br /> </div> </div> <br /> <div class="w3-row w3-display-container" style="margin-left: -15%;"> <span class="w3-text-blue w3-display-middle w3-padding"><?php echo $success ?></span> </div> </form> <br /><br /> <a href="removeRestaurant.php" class="w3-button w3-theme-d4">Delete</a> <a href="index.php" class="w3-button w3-theme-d4">Go Back</a> <!-- End Page Container --> </div> <br> <!-- Footer --> <footer class="w3-container w3-theme-d3 w3-padding-16 w3-center"> <p>Copyright &copy; 2017-2018 <NAME></p> </footer> </body> <file_sep>/removeRestaurant.php <?php /* * Author: <NAME> */ //Database connectino informtion define("HOST","localhost"); define("USER","code"); define("PASSWORD","<PASSWORD>"); define("DATABASE","restaurant"); //attempt to connect to database $connection = new mysqli(HOST, USER, PASSWORD, DATABASE); if(!$connection->connect_error){ $result = $connection->query("SELECT * FROM `restaurant`"); if(isset($_POST['Delete']) && $_POST['Delete']=='Delete'){ $query = "DELETE FROM `restaurant` WHERE id = ("; if(is_array($id=$_POST['id'])) foreach($id as $restaurant){ $endQuery = $query . "'$restaurant')"; if(!$deleteResult = $connection->query($endQuery)) $success = "Unable to access database. Please try again later."; else $success = ($connection->affected_rows < 1?" ":"Restaurant(s) Successfully removed"); } } $result = $connection->query("SELECT * FROM `restaurant`"); } ?> <!DOCTYPE html> <html> <title>Remove Restaurant</title> <meta charset="utf-8"> <meta name="description" content="Lets go to lunch! Not sure where to eat today?..."/> <meta name="keywords" content="Random Lunch Generator, Lunch Picker, Lunch Chooser, random string chooser" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" /> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <link href="https://fonts.googleapis.com/css?family=Handlee|Kalam|Righteous" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://www.w3schools.com/lib/w3-theme-red.css"> <style> h1,h2,h3,h4,h5,h6 {font-family: Kalam, serif;} html, body{font-family: Handlee, sans-serif;font-size:1.12em;} </style> <body class="w3-theme-l3"> <!-- Navbar --> <div class="w3-top"> <div class="w3-bar w3-theme-d1 w3-left-align w3-large"> <a href="www.jackycyntias.net" class="w3-bar-item w3-button w3-padding-large w3-theme-d4 w3-hover-white"><i class="fa fa-home w3-margin-right"></i><b>JCS</b></a> <a class="w3-bar-item w3-button w3-padding-large w3-hover-white w3-right w3-hide-small" href="http://www.jackycyntias.net/contact.php">Leave Feedback</a> </div> </div> <!-- Page Container --> <div class="w3-container w3-content" style="max-width:700px;margin-top:80px"> <form action="removeRestaurant.php" method="post"> <table class="w3-table-all w3-hoverable"> <tr class="w3-red"> <th>Restaurant</th> </tr> <?php if(!$connection->connect_error) { if($result->num_rows < 1) echo "<tr><td colspan='2'> No restaurants to show</td></tr>"; else{ while($row=$result->fetch_array()) { echo "<tr>". "<td><input type='checkbox' class='w3-check' name='id[]' value='".$row["id"]."' />".$row["name"]."</td>". "</tr>"; } } } ?> </table> <input type="submit" name="Delete" value="Delete" class="w3-button w3-theme-d2 w3-center" style="width:80%;margin:1% 10%"/> </form> <div class="w3-row w3-display-container" style="margin-left: -15%;margin-top:2%;"> <span class="w3-text-blue w3-display-middle w3-padding"><?php echo $success; ?></span> </div> <p> <a href="addRestaurant.php" class="w3-button w3-theme-d4">Add Restaurant</a> <a href="index.php" class="w3-button w3-theme-d4">Home</a> </p> <!-- End Page Container --> </div> <br> <!-- Footer --> <footer class="w3-container w3-theme-d3 w3-padding-16 w3-center"> <p>Copyright &copy; 2017-2018 <NAME></p> </footer> </body> <file_sep>/index.php <?php /* * Author: <NAME> */ //Database connection information define("HOST","localhost"); define("USER","code"); define("PASSWORD","<PASSWORD>"); define("DATABASE","restaurant"); //attempt to connect to database $connection = new mysqli(HOST, USER, PASSWORD, DATABASE); if(!$connection->connect_error) { // if successfull connection do stuff $result = $connection->query("SELECT * FROM restaurant ORDER BY RAND() LIMIT 1"); if($result->num_rows < 1) $restaurantName = "There are no restaurants to pick from"; else $restaurantName = $result->fetch_array()["name"]; } ?> <!DOCTYPE html> <html> <title>What is for lunch?</title> <meta charset="utf-8"> <meta name="description" content="Lets go to lunch! Not sure where to eat today?..."/> <meta name="keywords" content="Random Lunch Generator, Lunch Picker, Lunch Chooser, random string chooser" /> <meta name="robots" content="index,follow" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" /> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <link href="https://fonts.googleapis.com/css?family=Handlee|Kalam|Righteous" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://www.w3schools.com/lib/w3-theme-red.css"> <style> h1,h2,h3,h4,h5,h6 {font-family: Kalam, serif;} html, body{font-family: Handlee, sans-serif;font-size:1.12em;} </style> <body class="w3-theme-l3"> <!-- Navbar --> <div class="w3-top"> <div class="w3-bar w3-theme-d1 w3-left-align w3-large"> <a href="www.jackycyntias.net" class="w3-bar-item w3-button w3-padding-large w3-theme-d4 w3-hover-white"><i class="fa fa-home w3-margin-right"></i><b>JCS</b></a> <a class="w3-bar-item w3-button w3-padding-large w3-hover-white w3-right w3-hide-small" href="http://www.jackycyntias.net/contact.php">Leave Feedback</a> </div> </div> <!-- Page Container --> <div class="w3-container w3-content" style="max-width:700px;margin-top:80px"> <h1>What's for Lunch?</h1> <p class="w3-center w3-card-4 w3-white w3-padding-large"> Would you like to eat at: <br /> <?php echo $restaurantName ?>? <br /> <a href="index.php" class="w3-button w3-white w3-theme-d1 w3-hover-white">Nope. Try again</a> </p> <p> <a href="addRestaurant.php" class="w3-button w3-theme-d4">Add Restaurant</a> <a href="removeRestaurant.php" class="w3-button w3-theme-d4">Delete Restaurant</a> </p> <!-- End Page Container --> </div> <br> <!-- Footer --> <footer class="w3-container w3-theme-d3 w3-padding-16 w3-center"> <p>Copyright &copy; 2017-2018 <NAME></p> </footer> </body> <file_sep>/README.md # LunchPicker Webpage that randomly gives out a recommendation of where to eat.
087789c13ca1653024e77aa4c8c8766924472f4a
[ "Markdown", "PHP" ]
4
PHP
LunarShadow/LunchPicker
933bcdebd34e17c74f82366dc9936ce2e1410706
6e917472ecc5618df58aabbec74262a732ed1250
refs/heads/master
<file_sep>/** @jsx h */ import React from 'react' import h from '../../helpers/h' export const schema = { nodes: { code: (props) => { return ( React.createElement('pre', props.attributes, React.createElement('code', {}, props.children) ) ) } } } export const state = ( <state> <document> <code> word </code> <code> word </code> <code> word </code> </document> </state> ) export const output = ` <div data-slate-editor="true" contenteditable="true" role="textbox"> <pre> <code> <span> <span>word</span> </span> </code> </pre> <pre> <code> <span> <span>word</span> </span> </code> </pre> <pre> <code> <span> <span>word</span> </span> </code> </pre> </div> `.trim() <file_sep> import { Editor } from 'slate-react' import { Block, State } from 'slate' import React from 'react' import initialState from './state.json' import isImage from 'is-image' import isUrl from 'is-url' /** * Default block to be inserted when the document is empty, * and after an image is the last node in the document. * * @type {Object} */ const defaultBlock = { type: 'paragraph', isVoid: false, data: {} } /** * Define a schema. * * @type {Object} */ const schema = { nodes: { image: (props) => { const { node, isSelected } = props const src = node.data.get('src') const className = isSelected ? 'active' : null return ( <img src={src} className={className} {...props.attributes} /> ) }, paragraph: (props) => { return <p {...props.attributes}>{props.children}</p> } }, rules: [ // Rule to insert a paragraph block if the document is empty. { match: (node) => { return node.kind == 'document' }, validate: (document) => { return document.nodes.size ? null : true }, normalize: (change, document) => { const block = Block.create(defaultBlock) change.insertNodeByKey(document.key, 0, block) } }, // Rule to insert a paragraph below a void node (the image) if that node is // the last one in the document. { match: (node) => { return node.kind == 'document' }, validate: (document) => { const lastNode = document.nodes.last() return lastNode && lastNode.isVoid ? true : null }, normalize: (change, document) => { const block = Block.create(defaultBlock) change.insertNodeByKey(document.key, document.nodes.size, block) } } ] } /** * A change function to standardize inserting images. * * @param {Change} change * @param {String} src * @param {Selection} target */ function insertImage(change, src, target) { if (target) { change.select(target) } change.insertBlock({ type: 'image', isVoid: true, data: { src } }) } /** * The images example. * * @type {Component} */ class Images extends React.Component { /** * Deserialize the raw initial state. * * @type {Object} */ state = { state: State.fromJSON(initialState) } /** * Render the app. * * @return {Element} element */ render() { return ( <div> {this.renderToolbar()} {this.renderEditor()} </div> ) } /** * Render the toolbar. * * @return {Element} element */ renderToolbar = () => { return ( <div className="menu toolbar-menu"> <span className="button" onMouseDown={this.onClickImage}> <span className="material-icons">image</span> </span> </div> ) } /** * Render the editor. * * @return {Element} element */ renderEditor = () => { return ( <div className="editor"> <Editor schema={schema} state={this.state.state} onChange={this.onChange} onDrop={this.onDrop} onPaste={this.onPaste} /> </div> ) } /** * On change. * * @param {Change} change */ onChange = ({ state }) => { this.setState({ state }) } /** * On clicking the image button, prompt for an image and insert it. * * @param {Event} e */ onClickImage = (e) => { e.preventDefault() const src = window.prompt('Enter the URL of the image:') if (!src) return const change = this.state.state .change() .call(insertImage, src) this.onChange(change) } /** * On drop, insert the image wherever it is dropped. * * @param {Event} e * @param {Object} data * @param {Change} change * @param {Editor} editor */ onDrop = (e, data, change, editor) => { switch (data.type) { case 'files': return this.onDropOrPasteFiles(e, data, change, editor) } } /** * On drop or paste files, read and insert the image files. * * @param {Event} e * @param {Object} data * @param {Change} change * @param {Editor} editor */ onDropOrPasteFiles = (e, data, change, editor) => { for (const file of data.files) { const reader = new FileReader() const [ type ] = file.type.split('/') if (type != 'image') continue reader.addEventListener('load', () => { editor.change((t) => { t.call(insertImage, reader.result, data.target) }) }) reader.readAsDataURL(file) } } /** * On paste, if the pasted content is an image URL, insert it. * * @param {Event} e * @param {Object} data * @param {Change} change * @param {Editor} editor */ onPaste = (e, data, change, editor) => { switch (data.type) { case 'files': return this.onDropOrPasteFiles(e, data, change, editor) case 'text': return this.onPasteText(e, data, change) } } /** * On paste text, if the pasted content is an image URL, insert it. * * @param {Event} e * @param {Object} data * @param {Change} change */ onPasteText = (e, data, change) => { if (!isUrl(data.text)) return if (!isImage(data.text)) return change.call(insertImage, data.text, data.target) } } /** * Export. */ export default Images <file_sep> # Changelog This document maintains a list of changes to the `slate-react` package with each new version. Until `1.0.0` is released, breaking changes will be added as minor version bumps, and smaller changes won't be accounted for since the library is moving quickly. --- ### `0.2.0` — September 29, 2017 - **`onBeforeChange` is now called automatically again in `<Editor>`.** This was removed before, in attempt to decrease the "magic" that the editor was performing, since it normalizes when new props are passed to it, creating instant changes. But we discovered that it is actually necessary for now, so it has been added again. --- ### `0.1.0` — September 17, 2017 :tada: <file_sep> # Resources A few resources that are helpful for building with Slate. ## Tooling - [Immutable.js Console Extension](https://github.com/mattzeunert/immutable-object-formatter-extension) — this greatly improves the `console.log` output when working with [Immutable.js](https://facebook.github.io/immutable-js/) objects, which Slate's data model is based on. ## Showcase - [ORY Editor](https://editor.ory.am/) — a self-contained, inline WYSIWYG editor library built on top of Slate. - [Reboo Editor](http://slate-editor.bonde.org/) — a drop-in WYSIWYG editor built with Slate. <file_sep>import Plain from 'slate-plain-serializer' import {Editor} from 'slate-react' import {Mark} from 'slate' import Prism from 'prismjs' import React from 'react' /** * Add the markdown syntax to Prism. */ // eslint-disable-next-line Prism.languages.markdown = Prism.languages.extend("markup", {}), Prism.languages.insertBefore("markdown", "prolog", { blockquote: { pattern: /^>(?:[\t ]*>)*/m, alias: "punctuation" }, code: [{pattern: /^(?: {4}|\t).+/m, alias: "keyword"}, {pattern: /``.+?``|`[^`\n]+`/, alias: "keyword"}], title: [{ pattern: /\w+.*(?:\r?\n|\r)(?:==+|--+)/, alias: "important", inside: {punctuation: /==+$|--+$/} }, {pattern: /(^\s*)#+.+/m, lookbehind: !0, alias: "important", inside: {punctuation: /^#+|#+$/}}], hr: {pattern: /(^\s*)([*-])([\t ]*\2){2,}(?=\s*$)/m, lookbehind: !0, alias: "punctuation"}, list: {pattern: /(^\s*)(?:[*+-]|\d+\.)(?=[\t ].)/m, lookbehind: !0, alias: "punctuation"}, "url-reference": { pattern: /!?\[[^\]]+\]:[\t ]+(?:\S+|<(?:\\.|[^>\\])+>)(?:[\t ]+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\)))?/, inside: { variable: {pattern: /^(!?\[)[^\]]+/, lookbehind: !0}, string: /(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\))$/, punctuation: /^[\[\]!:]|[<>]/ }, alias: "url" }, bold: { pattern: /(^|[^\\])(\*\*|__)(?:(?:\r?\n|\r)(?!\r?\n|\r)|.)+?\2/, lookbehind: !0, inside: {punctuation: /^\*\*|^__|\*\*$|__$/} }, italic: { pattern: /(^|[^\\])([*_])(?:(?:\r?\n|\r)(?!\r?\n|\r)|.)+?\2/, lookbehind: !0, inside: {punctuation: /^[*_]|[*_]$/} }, url: { pattern: /!?\[[^\]]+\](?:\([^\s)]+(?:[\t ]+"(?:\\.|[^"\\])*")?\)| ?\[[^\]\n]*\])/, inside: { variable: {pattern: /(!?\[)[^\]]+(?=\]$)/, lookbehind: !0}, string: {pattern: /"(?:\\.|[^"\\])*"(?=\)$)/} } } }), Prism.languages.markdown.bold.inside.url = Prism.util.clone(Prism.languages.markdown.url), Prism.languages.markdown.italic.inside.url = Prism.util.clone(Prism.languages.markdown.url), Prism.languages.markdown.bold.inside.italic = Prism.util.clone(Prism.languages.markdown.italic), Prism.languages.markdown.italic.inside.bold = Prism.util.clone(Prism.languages.markdown.bold); /** * Define a decorator for markdown styles. * * @param {Text} text * @param {Block} block */ function markdownDecorator(text, block) { const characters = text.characters.asMutable() const language = 'markdown' const string = text.text const grammar = Prism.languages[language] const tokens = Prism.tokenize(string, grammar) addMarks(characters, tokens, 0) return characters.asImmutable() } function addMarks(characters, tokens, offset) { for (const token of tokens) { if (typeof token == 'string') { offset += token.length continue } const {content, length, type} = token const mark = Mark.create({type}) for (let i = offset; i < offset + length; i++) { let char = characters.get(i) let {marks} = char marks = marks.add(mark) char = char.set('marks', marks) characters.set(i, char) } if (Array.isArray(content)) { addMarks(characters, content, offset) } offset += length } } /** * Define a schema. * * @type {Object} */ const schema = { marks: { 'title': { fontWeight: 'bold', fontSize: '20px', margin: '20px 0 10px 0', display: 'inline-block' }, 'bold': { fontWeight: 'bold' }, 'italic': { fontStyle: 'italic' }, 'punctuation': { opacity: 0.2 }, 'code': { fontFamily: 'monospace', display: 'inline-block', padding: '2px 1px', }, 'list': { paddingLeft: '10px', lineHeight: '10px', fontSize: '20px' }, 'hr': { borderBottom: '2px solid #000', display: 'block', opacity: 0.2 } }, rules: [ { match: () => true, decorate: markdownDecorator, } ] } /** * The markdown preview example. * * @type {Component} */ class RequirementsEdit extends React.Component { /** * Deserialize the initial editor state. * * @type {Object} */ state = { state: "" } constructor(props) { super(props); this.state = { state: Plain.deserialize(props.text) || "", }; } /** * * Render the example. * * @return {Component} component */ render() { return ( <div className="editor"> <Editor schema={schema} state={this.state.state} onChange={this.onChange} /> </div> ) } /** * On change. * * @param {Change} change */ onChange = ({state}) => { this.setState({state}) } } /** * Export. */ export default RequirementsEdit <file_sep> # Utils ```js import { findDOMNode } from 'slate-react' ``` React-specific utility functions for Slate that may be useful in certain use cases. ## Functions ### `findDOMNode` `findDOMNode(node: Node) => DOMElement` Find the DOM node for a Slate [`Node`](../slate/node.md). Modelled after React's built-in `findDOMNode` helper. <file_sep> /** * Components. */ import Editor from './components/editor' import Placeholder from './components/placeholder' /** * Utils. */ import findDOMNode from './utils/find-dom-node' /** * Export. * * @type {Object} */ export { Editor, Placeholder, findDOMNode, } export default { Editor, Placeholder, findDOMNode, } <file_sep>/** @jsx h */ import React from 'react' import h from '../../helpers/h' class Bold extends React.Component { render() { return ( React.createElement('strong', {}, this.props.children) ) } } export const schema = { marks: { bold: Bold, } } export const state = ( <state> <document> <paragraph> one<b>two</b>three </paragraph> </document> </state> ) export const output = ` <div data-slate-editor="true" contenteditable="true" role="textbox"> <div style="position:relative;"> <span> <span>one</span> <span><strong>two</strong></span> <span>three</span> </span> </div> </div> `.trim() <file_sep>/* eslint-disable no-console */ /** * Is in development? * * @type {Boolean} */ const IS_DEV = ( typeof process !== 'undefined' && process.env && process.env.NODE_ENV !== 'production' ) /** * Log a `message` at `level`. * * @param {String} level * @param {String} message * @param {Any} ...args */ function log(level, message, ...args) { if (!IS_DEV) { return } if (typeof console != 'undefined' && typeof console[level] == 'function') { console[level](message, ...args) } } /** * Log a development warning `message`. * * @param {String} message * @param {Any} ...args */ function warn(message, ...args) { log('warn', `Warning: ${message}`, ...args) } /** * Log a deprecation warning `message`, with helpful `version` number. * * @param {String} version * @param {String} message * @param {Any} ...args */ function deprecate(version, message, ...args) { log('warn', `Deprecation (v${version}): ${message}`, ...args) } /** * Export. * * @type {Function} */ export default { deprecate, warn, } <file_sep> # Schemas Every Slate editor has a "schema" associated with it, which contains information about the structure of its content. It lets you specify how to render each different type of node. And for more advanced use cases it lets you enforce rules about what the content of the editor can and cannot be. ## Rules Slate schemas are built up of a set of rules. Every rule has a few properties: ```js { match: Function || Object, render: Component || Function || Object || String, decorate: Function, validate: Function || Object, change: Function } ``` Each of the properties will add certain functionality to the schema. For example, ## Matches For any schema rule to be applied, it has to match a node in the editor's content. The most basic way to do this is to match by `kind` and `type`. For example: ```js ## Components The most basic use of a schema is to define which React components should be rendered for each node in the editor. For example, you might want to ``` <file_sep>/** @jsx h */ import h from '../../helpers/h' import { Mark } from 'slate' export const schema = { nodes: { paragraph: { decorate(text, block) { let { characters } = text let second = characters.get(1) const mark = Mark.create({ type: 'bold' }) const marks = second.marks.add(mark) second = second.merge({ marks }) characters = characters.set(1, second) return characters } } }, marks: { bold: { fontWeight: 'bold', } } } export const state = ( <state> <document> <paragraph> one </paragraph> </document> </state> ) export const output = ` <div data-slate-editor="true" contenteditable="true" role="textbox"> <div style="position:relative;"> <span> <span>o</span> <span><span style="font-weight:bold;">n</span></span> <span>e</span> </span> </div> </div> `.trim() <file_sep> # `<Placeholder>` ```js import { Placeholder } from 'slate-react' ``` A simple component that adds a placeholder to a node. It encapsulates all of the Slate-related logic that determines when to render the placeholder, so you don't have to think about it. ## Properties ```js <Placeholder className={String} node={Node} parent={Node} state={State} style={Object} > {children} </Placeholder> ``` ### `children` `Any` React child elements to render inside the placeholder `<span>` element. ### `className` `String` An optional class name string to add to the placeholder `<span>` element. ### `firstOnly` `Boolean` An optional toggle that allows the Placeholder to render even if it is not the first node of the parent. This is useful for cases where the Placeholder should show up at every empty instance of the node. Defaults to `true`. ### `node` `Node` The node to render the placeholder element on top of. The placeholder is positioned absolutely, covering the entire node. ### `parent` `Node` The node to check for non-empty content, to determine whether the placeholder should be shown or not, if `firstOnly` is set to `false`. ### `state` `State` The current state of the editor. ### `style` `Object` An optional dictionary of styles to pass to the placeholder `<span>` element. <file_sep> import assert from 'assert' import fs from 'fs' import { Schema } from '../..' import { basename, extname, resolve } from 'path' /** * Tests. */ describe('schemas', () => { describe('core', () => { const innerDir = resolve(__dirname, 'core') const tests = fs.readdirSync(innerDir).filter(t => t[0] != '.').map(t => basename(t, extname(t))) for (const test of tests) { it(test, async () => { const module = require(resolve(innerDir, test)) const { input, output, schema } = module const s = Schema.create(schema) const actual = input.change().normalize(s).state.toJSON() const expected = output assert.deepEqual(actual, expected) }) } }) }) <file_sep># How to run this thing - Start yarn cd ./slate/examples yarn run watch - Open http://localhost:8080/dev.html#/requirements ---- Сейчас используется статика в /slate/examples/ # Туду - Я как пользователь хочу иметь аналог GitBook-а с улучшенным отображением свойств файла + Я как пользователь хочу редактировать в визивиге текст в формате маркдан + Я как пользователь хочу просматривать параметры артефакта (2) - Я как пользователь хочу редактировать параметры артефакта (4) - мультипл поле текста - добавлять - убирать - мультипл поле ссылки + добавлять + поля добавляются с заранее заданными значениями + при добавлении поля делаем поля, заполняем и потом прячем. Потом вообще автокомплит должен будет быть. может сразу под автокомплит сделать, хз. - убирать - Я как пользователь хочу читать данные реального файла из апи хранилища, в гите (4) + компоненту передаём имя файла + компонент идёт по нему в апишечку и получает данные1 - компонент берёт имя файла из урла открытой страницы, нужно будет какой-то роутинг сделать - компонент делает заголовок страницы из ответа апи - Я как пользователь хочу сохранять данные в хранилище (2) + нужно добиться, чтобы изменение компонента (например, компонена с integer полем) прокидывалось наружу, в state формы + нужно добиться, чтобы изменение компонена с multiple полем прокидывалось корректно в state формы // https://ru.stackoverflow.com/questions/549974/%D0%9C%D0%B5%D0%B6%D0%BA%D0%BE%D0%BC%D0%BF%D0%BE%D0%BD%D0%B5%D0%BD%D1%82%D0%BD%D0%B0%D1%8F-%D1%81%D0%B2%D1%8F%D0%B7%D1%8C-react-%D0%BA%D0%B0%D0%BA-%D0%BF%D0%B5%D1%80%D0%B5%D0%B4%D0%B0%D0%B2%D0%B0%D1%82%D1%8C-%D0%B4%D0%B0%D0%BD%D0%BD%D1%8B%D0%B5-%D0%BC%D0%B5%D0%B6%D0%B4%D1%83-%D0%BA%D0%BE%D0%BC%D0%BF%D0%BE%D0%BD%D0%B5%D0%BD%D1%82%D0%B0%D0%BC%D0%B8 - нужно прокинуть вообще все поля в state формы + multiple int - single int (ПОЧЕМУ-ТО НЕ ПРОКИДЫВАЕТСЯ В ФОРМУ ЗНАЧЕНИЕ ХОТЯ У МУЛЬТИПЛА ПРОКИДЫВАЕТСЯ :( ) https://reactjs.org/docs/lifting-state-up.html - тут короче чото есть, но хз непонятно. + multiple field - single field - multiple link - single field - text - нужно научиться отправлять данные из state формы в апи - Я как разработчик хочу иметь стандарт описания полей и апи (2) - Я как пользователь хочу иметь возможность сохранять файлы в ветке по определённому пути (1) - Я как пользователь хочу видеть свои сохранённые файлы в гите, в соответствующих ветках (2) - Я как пользователь хочу добавлять-убирать новые свойства (3) - Я как пользователь хочу видеть список файлов в определённой ветке (4) - Я как пользователь хочу иметь возможность переключаться между ветками (4) - Я как владелец продукта хочу, чтобы документация на этот продукт хранилась с помощью него же (4) - Я как пользователь хочу, чтобы корректно работали свойства ссылок и работала валидация (16) - Я как администратор хочу, чтобы файлы принадлежали жёстко к определённым типам и не могли обрабатываться некоррекно (16) - Я как администратор хочу, чтобы с системой работали разные роли пользователей (32) - Я как владелец продукта хочу, чтобы с системой могли одновременно работать несколько человек (32)
d15e66f00eb378f52f94a7a4f5b61d596c159d8d
[ "JavaScript", "Markdown" ]
14
JavaScript
may-cat/markdown-editor
0a3f6998ee4fae2e621c5b56a7a131c76f86ba92
c3b024c0538d026ce5ef7ca861bf9b144cc41d9d
refs/heads/master
<repo_name>cawfeecoder/frontend-examples<file_sep>/kotlin-react-example/src/main/kotlin/Hello.kt import kotlinext.js.js import react.* import react.dom.* import kotlinx.html.* import kotlin.browser.document fun main(args: Array<String>) { render(document.getElementById("root")) { div { welcome("Mary") } } } interface WelcomeProps: RProps { var name: String } class Welcome(props: WelcomeProps) : RComponent<WelcomeProps, RState>(props){ override fun RBuilder.render() { div { +"Hello, ${props.name}" } } } fun RBuilder.welcome(name: String = "John") = child(Welcome::class) { attrs.name = name }<file_sep>/kotlin-react-example/out/production/classes/kotlin-dce-example_main.js (function (root, factory) { if (typeof define === 'function' && define.amd) define(['exports', 'kotlin', 'kotlin-react-dom', 'kotlin-react'], factory); else if (typeof exports === 'object') factory(module.exports, require('kotlin'), require('kotlin-react-dom'), require('kotlin-react')); else { if (typeof kotlin === 'undefined') { throw new Error("Error loading module 'kotlin-dce-example_main'. Its dependency 'kotlin' was not found. Please, check whether 'kotlin' is loaded prior to 'kotlin-dce-example_main'."); } if (typeof this['kotlin-react-dom'] === 'undefined') { throw new Error("Error loading module 'kotlin-dce-example_main'. Its dependency 'kotlin-react-dom' was not found. Please, check whether 'kotlin-react-dom' is loaded prior to 'kotlin-dce-example_main'."); } if (typeof this['kotlin-react'] === 'undefined') { throw new Error("Error loading module 'kotlin-dce-example_main'. Its dependency 'kotlin-react' was not found. Please, check whether 'kotlin-react' is loaded prior to 'kotlin-dce-example_main'."); } root['kotlin-dce-example_main'] = factory(typeof this['kotlin-dce-example_main'] === 'undefined' ? {} : this['kotlin-dce-example_main'], kotlin, this['kotlin-react-dom'], this['kotlin-react']); } }(this, function (_, Kotlin, $module$kotlin_react_dom, $module$kotlin_react) { 'use strict'; var $$importsForInline$$ = _.$$importsForInline$$ || (_.$$importsForInline$$ = {}); var Unit = Kotlin.kotlin.Unit; var render = $module$kotlin_react_dom.react.dom.render_2955dm$; var Kind_INTERFACE = Kotlin.Kind.INTERFACE; var RComponent_init = $module$kotlin_react.react.RComponent_init_8bz2yq$; var Kind_CLASS = Kotlin.Kind.CLASS; var RComponent = $module$kotlin_react.react.RComponent; var getKClass = Kotlin.getKClass; Welcome.prototype = Object.create(RComponent.prototype); Welcome.prototype.constructor = Welcome; var attributesMapOf = $module$kotlin_react_dom.$$importsForInline$$['kotlinx-html-js'].kotlinx.html.attributesMapOf_jyasbz$; var DIV_init = $module$kotlin_react_dom.$$importsForInline$$['kotlinx-html-js'].kotlinx.html.DIV; function div$lambda(closure$classes) { return function (it) { return new DIV_init(attributesMapOf('class', closure$classes), it); }; } var RDOMBuilder_init = $module$kotlin_react_dom.react.dom.RDOMBuilder; function main$lambda($receiver) { var $receiver_0 = new RDOMBuilder_init(div$lambda(null)); welcome($receiver_0, 'Mary'); $receiver.child_2usv9w$($receiver_0.create()); return Unit; } function main(args) { render(document.getElementById('root'), void 0, main$lambda); } function WelcomeProps() { } WelcomeProps.$metadata$ = { kind: Kind_INTERFACE, simpleName: 'WelcomeProps', interfaces: [] }; function Welcome(props) { RComponent_init(props, this); } Welcome.prototype.render_ss14n$ = function ($receiver) { var $receiver_0 = new RDOMBuilder_init(div$lambda(null)); $receiver_0.unaryPlus_pdl1vz$('Hello, ' + this.props.name); $receiver.child_2usv9w$($receiver_0.create()); }; Welcome.$metadata$ = { kind: Kind_CLASS, simpleName: 'Welcome', interfaces: [RComponent] }; function welcome$lambda(closure$name) { return function ($receiver) { $receiver.attrs.name = closure$name; return Unit; }; } function welcome($receiver, name) { if (name === void 0) name = 'John'; return $receiver.child_bzgiuu$(getKClass(Welcome), welcome$lambda(name)); } $$importsForInline$$['kotlin-react-dom'] = $module$kotlin_react_dom; _.main_kand9s$ = main; _.WelcomeProps = WelcomeProps; _.Welcome = Welcome; _.welcome_hw0qe1$ = welcome; main([]); Kotlin.defineModule('kotlin-dce-example_main', _); return _; })); <file_sep>/kotlin-react-example/webpack.config.js var webpack = require("webpack"); var path = require("path"); module.exports = { entry: path.resolve(__dirname, "build/classes/main/min/kotlin-dce-example.js"), output: { path: path.resolve(__dirname, "build"), filename: "bundle.js" }, resolve: { alias: { kotlin: path.resolve(__dirname, "build/classes/main/min/kotlin.js"), 'kotlin-react': path.resolve(__dirname, "build/classes/main/min/kotlin-react.js"), 'kotlin-react-dom': path.resolve(__dirname, "build/classes/main/min/kotlin-react-dom.js"), 'kotlinx-html-js': path.resolve(__dirname, "build/classes/main/min/kotlinx-html-js.js"), 'kotlin-extensions': path.resolve(__dirname, "build/classes/main/min/kotlin-extensions.js") } }, plugins: [ new webpack.optimize.UglifyJsPlugin() ] };
292443f9616ac15a4cef5e607c22a302c8811543
[ "JavaScript", "Kotlin" ]
3
Kotlin
cawfeecoder/frontend-examples
b8fec995045afa0e8d95c8e26cb3c21da389ba86
0769b5f2543cbac249440bf7fb9f39d82d5a5980
refs/heads/master
<repo_name>skeevis/rails-contactually-api-base<file_sep>/app/models/user.rb class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers => [:contactually] def self.from_omniauth(auth) user = where(provider: auth.provider, uid: auth.uid).first_or_create do |user| user.provider = auth.provider user.uid = auth.uid user.email = auth.info.email user.password = Devise.friendly_token[0,20] user.access_token = auth.credentials['token'] end user.access_token = auth.credentials['token'] #poor man's refresh, I know. user.save user end def contactually_api @api_client ||= OAuth2::Client.new(configatron.contactually.application_id, configatron.contactually.application_secret, :site => 'https://api.contactually.com') @access_token ||= OAuth2::AccessToken.from_hash(@api_client, access_token: access_token) end end <file_sep>/app/controllers/home_controller.rb class HomeController < ApplicationController layout 'application' def index #Making a test call @client = current_user.contactually_api @me = @client.get("/v2/me").parsed['data'] SampleWorker.perform_async() render 'index' end end <file_sep>/app/workers/sample_worker.rb class SampleWorker include Sidekiq::Worker def perform() #do stuff here end end <file_sep>/README.rdoc == README This is a base application making it incredibly easy to build standalone apps that consume the Contactually API (https://developers.contactually.com/). The only think you need to do is register for an application at https://www.contactually.com/developer/applications, then set your CONTACTUALLY_APP_ID and CONTACTUALLY_APP_SECRET env variables. Or set them somewhere else and modify devise.rb and user.rb. Basic user flow already put in and tested. Disabled a lot of the other devise functionality, so single point of authentication is Contactually. But feel free to modify as you want. Zurb's Foundation 6 installed for the frontend. Basic UI already in. Completely as-is.<file_sep>/config/initializers/omniauth.rb Rails.application.config.middleware.use OmniAuth::Builder do # provider :contactually, ENV['CONTACTUALLY_APP_ID'], ENV['CONTACTUALLY_APP_SECRET'], :scope=>"all:manage", :strategy_class => "OmniAuth::Strategies::Contactually" end<file_sep>/config/initializers/configatron.rb require 'configatron' #Configatron::Rails.init config_file = ERB.new(File.read("#{Rails.root}/config/config.yml")).result configuration_hash = YAML.load(config_file)[Rails.env] || {} configatron.configure_from_hash(configuration_hash) puts "Test String: #{configatron.test_string}"
5df485ee32f05dc37aed9be983fffb3467398785
[ "RDoc", "Ruby" ]
6
Ruby
skeevis/rails-contactually-api-base
3ecb1b9b6ca92e44db743ab63cb83c07ba1a6594
17ea6277d3b1a0122e9458443ab072e8f75d8ca4
refs/heads/master
<repo_name>linxinpeng/---<file_sep>/src/SelectPosition/data1.js module.exports= [ { "code": "5132", "name": "阿坝", "key": "A", "first": "abzzqzzzz", "full": "abazangzuqiangzuzizhizhou" }, { "code": "6529", "name": "阿克苏", "key": "A", "first": "aksdq", "full": "akesudiqu" }, { "code": "1529", "name": "阿拉善盟", "key": "A", "first": "alsm", "full": "alashanmeng" }, { "code": "6543", "name": "阿勒泰", "key": "A", "first": "altdq", "full": "aletaidiqu" }, { "code": "5425", "name": "阿里", "key": "A", "first": "aldq", "full": "alidiqu" }, { "code": "6109", "name": "安康", "key": "A", "first": "aks", "full": "ankang" }, { "code": "3408", "name": "安庆", "key": "A", "first": "aqs", "full": "anqing" }, { "code": "2103", "name": "鞍山", "key": "A", "first": "ass", "full": "anshan" }, { "code": "5204", "name": "安顺", "key": "A", "first": "ass", "full": "anshun" }, { "code": "4105", "name": "安阳", "key": "A", "first": "ays", "full": "anyang" }, { "code": "8200", "name": "澳门", "key": "A", "first": "am", "full": "aomen" }, { "code": "2208", "name": "白城", "key": "B", "first": "bcs", "full": "baicheng" }, { "code": "4510", "name": "百色", "key": "B", "first": "bss", "full": "baise" }, { "code": "2206", "name": "白山", "key": "B", "first": "bss", "full": "baishan" }, { "code": "6204", "name": "白银", "key": "B", "first": "bys", "full": "baiyin" }, { "code": "3403", "name": "蚌埠", "key": "B", "first": "bbs", "full": "bangbu" }, { "code": "1306", "name": "保定", "key": "B", "first": "bds", "full": "baoding" }, { "code": "6103", "name": "宝鸡", "key": "B", "first": "bjs", "full": "baoji" }, { "code": "5305", "name": "保山", "key": "B", "first": "bss", "full": "baoshan" }, { "code": "1502", "name": "包头", "key": "B", "first": "bts", "full": "baotou" }, { "code": "1508", "name": "巴彦淖尔", "key": "B", "first": "bynes", "full": "bayannaoer" }, { "code": "6528", "name": "巴音郭楞蒙古自治州", "key": "B", "first": "byglmgzzz", "full": "bayinguolengmengguzizhizhou" }, { "code": "5119", "name": "巴中", "key": "B", "first": "bzs", "full": "bazhong" }, { "code": "4505", "name": "北海", "key": "B", "first": "bhs", "full": "beihai" }, { "code": "1101", "name": "北京", "key": "B", "first": "bjs", "full": "beijing" }, { "code": "2105", "name": "本溪", "key": "B", "first": "bxs", "full": "benxi" }, { "code": "5224", "name": "毕节", "key": "B", "first": "bjdq", "full": "bijiediqu" }, { "code": "3716", "name": "滨州", "key": "B", "first": "bzs", "full": "binzhou" }, { "code": "6527", "name": "博尔塔拉蒙古自治州", "key": "B", "first": "betlmgzzz", "full": "boertalamengguzizhizhou" }, { "code": "3416", "name": "亳州", "key": "B", "first": "bzs", "full": "bozhou" }, { "code": "1309", "name": "沧州", "key": "C", "first": "czs", "full": "cangzhou" }, { "code": "2201", "name": "长春", "key": "C", "first": "ccs", "full": "changchun" }, { "code": "4307", "name": "常德", "key": "C", "first": "cds", "full": "changde" }, { "code": "5421", "name": "昌都", "key": "C", "first": "cddq", "full": "changdudiqu" }, { "code": "6523", "name": "昌吉", "key": "C", "first": "cjhzzzz", "full": "changjihuizuzizhizhou" }, { "code": "4301", "name": "长沙", "key": "C", "first": "css", "full": "changsha" }, { "code": "1404", "name": "长治", "key": "C", "first": "czs", "full": "changzhi" }, { "code": "3204", "name": "常州", "key": "C", "first": "czs", "full": "changzhou" }, { "code": "2113", "name": "朝阳", "key": "C", "first": "cys", "full": "chaoyang" }, { "code": "4451", "name": "潮州", "key": "C", "first": "czs", "full": "chaozhou" }, { "code": "1308", "name": "承德", "key": "C", "first": "cds", "full": "chengde" }, { "code": "5101", "name": "成都", "key": "C", "first": "cds", "full": "chengdu" }, { "code": "4310", "name": "郴州", "key": "C", "first": "czs", "full": "chenzhou" }, { "code": "1504", "name": "赤峰", "key": "C", "first": "cfs", "full": "chifeng" }, { "code": "3417", "name": "池州", "key": "C", "first": "czs", "full": "chizhou" }, { "code": "5001", "name": "重庆", "key": "C", "first": "cqs", "full": "chongqing" }, { "code": "4514", "name": "崇左", "key": "C", "first": "czs", "full": "chongzuo" }, { "code": "5323", "name": "楚雄", "key": "C", "first": "cxyzzzz", "full": "chuxiongyizuzizhizhou" }, { "code": "3411", "name": "滁州", "key": "C", "first": "czs", "full": "chuzhou" }, { "code": "2102", "name": "大连", "key": "D", "first": "dls", "full": "dalian" }, { "code": "5329", "name": "大理", "key": "D", "first": "dlbzzzz", "full": "dalibaizuzizhizhou" }, { "code": "2106", "name": "丹东", "key": "D", "first": "dds", "full": "dandong" }, { "code": "2306", "name": "大庆", "key": "D", "first": "dqs", "full": "daqing" }, { "code": "1402", "name": "大同", "key": "D", "first": "dts", "full": "datong" }, { "code": "2327", "name": "大兴安岭", "key": "D", "first": "dxaldq", "full": "daxinganlingdiqu" }, { "code": "5117", "name": "达州", "key": "D", "first": "dzs", "full": "dazhou" }, { "code": "5331", "name": "德宏", "key": "D", "first": "dhdzjpzzzz", "full": "dehongdaizujingpozuzizhizhou" }, { "code": "5106", "name": "德阳", "key": "D", "first": "dys", "full": "deyang" }, { "code": "3714", "name": "德州", "key": "D", "first": "dzs", "full": "dezhou" }, { "code": "6211", "name": "定西", "key": "D", "first": "dxs", "full": "dingxi" }, { "code": "5334", "name": "迪庆", "key": "D", "first": "dqzzzzz", "full": "diqingzangzuzizhizhou" }, { "code": "3705", "name": "东营", "key": "D", "first": "dys", "full": "dongying" }, { "code": "4419", "name": "东莞", "key": "D", "first": "dzs", "full": "dongzuo" }, { "code": "1506", "name": "鄂尔多斯", "key": "E", "first": "eedss", "full": "eerduosi" }, { "code": "4228", "name": "恩施", "key": "E", "first": "estjzmzzzz", "full": "enshitujiazumiaozuzizhizhou" }, { "code": "4207", "name": "鄂州", "key": "E", "first": "ezs", "full": "ezhou" }, { "code": "4506", "name": "防城港", "key": "F", "first": "fcgs", "full": "fangchenggang" }, { "code": "4406", "name": "佛山", "key": "F", "first": "fss", "full": "foshan" }, { "code": "2104", "name": "抚顺", "key": "F", "first": "fss", "full": "fushun" }, { "code": "2109", "name": "阜新", "key": "F", "first": "fxs", "full": "fuxin" }, { "code": "3412", "name": "阜阳", "key": "F", "first": "fys", "full": "fuyang" }, { "code": "3501", "name": "福州", "key": "F", "first": "fzs", "full": "fuzhou" }, { "code": "3610", "name": "抚州", "key": "F", "first": "fzs", "full": "fuzhou" }, { "code": "6230", "name": "甘南", "key": "G", "first": "gnzzzzz", "full": "gannanzangzuzizhizhou" }, { "code": "3607", "name": "赣州", "key": "G", "first": "gzs", "full": "ganzhou" }, { "code": "5133", "name": "甘孜", "key": "G", "first": "gzzzzzz", "full": "ganzizangzuzizhizhou" }, { "code": "5116", "name": "广安", "key": "G", "first": "gas", "full": "guangan" }, { "code": "5108", "name": "广元", "key": "G", "first": "gys", "full": "guangyuan" }, { "code": "4401", "name": "广州", "key": "G", "first": "gzs", "full": "guangzhou" }, { "code": "4508", "name": "贵港", "key": "G", "first": "ggs", "full": "guigang" }, { "code": "4503", "name": "桂林", "key": "G", "first": "gls", "full": "guilin" }, { "code": "5201", "name": "贵阳", "key": "G", "first": "gys", "full": "guiyang" }, { "code": "6326", "name": "果洛", "key": "G", "first": "glzzzzz", "full": "guoluozangzuzizhizhou" }, { "code": "6404", "name": "固原", "key": "G", "first": "gys", "full": "guyuan" }, { "code": "2301", "name": "哈尔滨", "key": "H", "first": "hebs", "full": "haerbin" }, { "code": "6322", "name": "海北", "key": "H", "first": "hbzzzzz", "full": "haibeizangzuzizhizhou" }, { "code": "6321", "name": "海东", "key": "H", "first": "hddq", "full": "haidongdiqu" }, { "code": "4601", "name": "海口", "key": "H", "first": "hks", "full": "haikou" }, { "code": "6325", "name": "海南", "key": "H", "first": "hnzzzzz", "full": "hainanzangzuzizhizhou" }, { "code": "6328", "name": "海西", "key": "H", "first": "hxmgzzzzzz", "full": "haiximengguzuzangzuzizhizhou" }, { "code": "6522", "name": "哈密", "key": "H", "first": "hmdq", "full": "hamidiqu" }, { "code": "1304", "name": "邯郸", "key": "H", "first": "hds", "full": "handan" }, { "code": "3301", "name": "杭州", "key": "H", "first": "hzs", "full": "hangzhou" }, { "code": "6107", "name": "汉中", "key": "H", "first": "hzs", "full": "hanzhong" }, { "code": "4106", "name": "鹤壁", "key": "H", "first": "hbs", "full": "hebi" }, { "code": "4512", "name": "河池", "key": "H", "first": "hcs", "full": "hechi" }, { "code": "3401", "name": "合肥", "key": "H", "first": "hfs", "full": "hefei" }, { "code": "2304", "name": "鹤岗", "key": "H", "first": "hgs", "full": "hegang" }, { "code": "2311", "name": "黑河", "key": "H", "first": "hhs", "full": "heihe" }, { "code": "1311", "name": "衡水", "key": "H", "first": "hss", "full": "hengshui" }, { "code": "4304", "name": "衡阳", "key": "H", "first": "hys", "full": "hengyang" }, { "code": "6532", "name": "和田", "key": "H", "first": "htdq", "full": "hetiandiqu" }, { "code": "4416", "name": "河源", "key": "H", "first": "hys", "full": "heyuan" }, { "code": "3717", "name": "菏泽", "key": "H", "first": "hzs", "full": "heze" }, { "code": "4511", "name": "贺州", "key": "H", "first": "hzs", "full": "hezhou" }, { "code": "5325", "name": "红河", "key": "H", "first": "hhhnzyzzzz", "full": "honghehanizuyizuzizhizhou" }, { "code": "3208", "name": "淮安", "key": "H", "first": "has", "full": "huaian" }, { "code": "3406", "name": "淮北", "key": "H", "first": "hbs", "full": "huaibei" }, { "code": "4312", "name": "怀化", "key": "H", "first": "hhs", "full": "huaihua" }, { "code": "3404", "name": "淮南", "key": "H", "first": "hns", "full": "huainan" }, { "code": "4211", "name": "黄冈", "key": "H", "first": "hgs", "full": "huanggang" }, { "code": "6323", "name": "黄南", "key": "H", "first": "hnzzzzz", "full": "huangnanzangzuzizhizhou" }, { "code": "3410", "name": "黄山", "key": "H", "first": "hss", "full": "huangshan" }, { "code": "4202", "name": "黄石", "key": "H", "first": "hss", "full": "huangshi" }, { "code": "1501", "name": "呼和浩特", "key": "H", "first": "hhhts", "full": "huhehaote" }, { "code": "4413", "name": "惠州", "key": "H", "first": "hzs", "full": "huizhou" }, { "code": "2114", "name": "葫芦岛", "key": "H", "first": "hlds", "full": "huludao" }, { "code": "1507", "name": "呼伦贝尔", "key": "H", "first": "hlbes", "full": "hulunbeier" } ]
d96dec11d13d432985b2be73f63153d53f8c7f24
[ "JavaScript" ]
1
JavaScript
linxinpeng/---
294d70b1c1538d639d39182774a2338b140c99f3
2da72084313aa581629fe0dc827825075e265290
refs/heads/master
<repo_name>xudongstorm/MVPTest<file_sep>/app/src/main/java/com/example/mvptest/presenter/IpInfoPresenter.java package com.example.mvptest.presenter; import com.example.mvptest.model.IpInfo; import com.example.mvptest.net.LoadTasksCallBack; import com.example.mvptest.net.NetTask; public class IpInfoPresenter implements IpInfoContract.Presenter,LoadTasksCallBack<IpInfo> { private NetTask netTask; private IpInfoContract.View addTaskView; public IpInfoPresenter(NetTask netTask,IpInfoContract.View addTaskView){ this.netTask=netTask; this.addTaskView=addTaskView; } @Override public void getIpInfo(String ip) { netTask.excute(ip,this); } @Override public void onSuccess(IpInfo ipInfo) { if(addTaskView.isActive()){ addTaskView.setIpInfo(ipInfo); } } @Override public void onStart() { if(addTaskView.isActive()){ addTaskView.showLoading(); } } @Override public void onFailed() { if(addTaskView.isActive()){ addTaskView.hideLoading(); addTaskView.showError(); } } @Override public void onFinish() { if(addTaskView.isActive()){ addTaskView.hideLoading(); } } }
eeb556c968aa9cfc74816814541224ae49756d09
[ "Java" ]
1
Java
xudongstorm/MVPTest
63b0f8b60f27571c586ba73cb378913b8191cf80
f714b51bda76cd80d166d07233104558ef7215b8
refs/heads/master
<file_sep>''' These classes cache metadata from TheMovieDB and TVDB. It uses sqlite databases. It uses themoviedb JSON api class and TVDB XML api class. For TVDB it currently uses a modified version of Python API by <NAME> (http://loopj.com) Metahandler intially created for IceFilms addon, reworked to be it's own script module to be used by many addons. Created/Modified by: Eldorado Initial creation and credits: Daledude / Anarchintosh / WestCoast13 *To-Do: - write a clean database function (correct imgs_prepacked by checking if the images actually exist) for pre-packed container creator. also retry any downloads that failed. also, if database has just been created for pre-packed container, purge all images are not referenced in database. ''' import os import re import sys from datetime import datetime import time import common from TMDB import TMDB from thetvdbapi import TheTVDB #necessary so that the metacontainers.py can use the scrapers import xbmc import xbmcvfs ''' Use addon.common library for http calls ''' from addon.common.net import Net net = Net() sys.path.append((os.path.split(common.addon_path))[0]) ''' Use SQLIte3 wherever possible, needed for newer versions of XBMC Keep pysqlite2 for legacy support ''' try: if common.addon.get_setting('use_remote_db')=='true' and \ common.addon.get_setting('db_address') is not None and \ common.addon.get_setting('db_user') is not None and \ common.addon.get_setting('db_pass') is not None and \ common.addon.get_setting('db_name') is not None: import mysql.connector as database common.addon.log('Loading MySQLdb as DB engine', 2) DB = 'mysql' else: raise ValueError('MySQL not enabled or not setup correctly') except: try: from sqlite3 import dbapi2 as database common.addon.log('Loading sqlite3 as DB engine version: %s' % database.sqlite_version, 2) except: from pysqlite2 import dbapi2 as database common.addon.log('pysqlite2 as DB engine', 2) DB = 'sqlite' def make_dir(mypath, dirname): ''' Creates sub-directories if they are not found. ''' subpath = os.path.join(mypath, dirname) try: if not xbmcvfs.exists(subpath): xbmcvfs.mkdirs(subpath) except: if not os.path.exists(subpath): os.makedirs(subpath) return subpath def bool2string(myinput): ''' Neatens up usage of preparezip flag. ''' if myinput is False: return 'false' elif myinput is True: return 'true' class MetaData: ''' This class performs all the handling of meta data, requesting, storing and sending back to calling application - Create cache DB if it does not exist - Create a meta data zip file container to share - Get the meta data from TMDB/IMDB/TVDB - Store/Retrieve meta from cache DB - Download image files locally ''' def __init__(self, preparezip=False, tmdb_api_key='af95ef8a4fe1e697f86b8c194f2e5e11'): #Check if a path has been set in the addon settings settings_path = common.addon.get_setting('meta_folder_location') # TMDB constants self.tmdb_image_url = '' self.tmdb_api_key = tmdb_api_key if settings_path: self.path = xbmc.translatePath(settings_path) else: self.path = common.profile_path(); self.cache_path = make_dir(self.path, 'meta_cache') if preparezip: #create container working directory #!!!!!Must be matched to workdir in metacontainers.py create_container() self.work_path = make_dir(self.path, 'work') #set movie/tvshow constants self.type_movie = 'movie' self.type_tvshow = 'tvshow' self.type_season = 'season' self.type_episode = 'episode' #this init auto-constructs necessary folder hierarchies. # control whether class is being used to prepare pre-packaged .zip self.classmode = bool2string(preparezip) self.videocache = os.path.join(self.cache_path, 'video_cache.db') self.tvpath = make_dir(self.cache_path, self.type_tvshow) self.tvcovers = make_dir(self.tvpath, 'covers') self.tvbackdrops = make_dir(self.tvpath, 'backdrops') self.tvbanners = make_dir(self.tvpath, 'banners') self.mvpath = make_dir(self.cache_path, self.type_movie) self.mvcovers = make_dir(self.mvpath, 'covers') self.mvbackdrops = make_dir(self.mvpath, 'backdrops') # connect to db at class init and use it globally if DB == 'mysql': class MySQLCursorDict(database.cursor.MySQLCursor): def _row_to_python(self, rowdata, desc=None): row = super(MySQLCursorDict, self)._row_to_python(rowdata, desc) if row: return dict(zip(self.column_names, row)) return None db_address = common.addon.get_setting('db_address') db_port = common.addon.get_setting('db_port') if db_port: db_address = '%s:%s' %(db_address,db_port) db_user = common.addon.get_setting('db_user') db_pass = common.addon.get_setting('db_pass') db_name = common.addon.get_setting('db_name') self.dbcon = database.connect(database=db_name, user=db_user, password=<PASSWORD>, host=db_address, buffered=True) self.dbcur = self.dbcon.cursor(cursor_class=MySQLCursorDict, buffered=True) else: self.dbcon = database.connect(self.videocache) self.dbcon.row_factory = database.Row # return results indexed by field names and not numbers so we can convert to dict self.dbcur = self.dbcon.cursor() # initialize cache db self._cache_create_movie_db() # Check TMDB configuration, update if necessary self._set_tmdb_config() ## !!!!!!!!!!!!!!!!!! Temporary code to update movie_meta columns cover_url and backdrop_url to store only filename !!!!!!!!!!!!!!!!!!!!! ## We have matches with outdated url, so lets strip the url out and only keep filename try: if DB == 'mysql': sql_select = "SELECT imdb_id, tmdb_id, cover_url, backdrop_url "\ "FROM movie_meta "\ "WHERE (substring(cover_url, 1, 36 ) = 'http://d3gtl9l2a4fn1j.cloudfront.net' "\ "OR substring(backdrop_url, 1, 36 ) = 'http://d3gtl9l2a4fn1j.cloudfront.net')" self.dbcur.execute(sql_select) matchedrows = self.dbcur.fetchall()[0] if matchedrows: sql_update = "UPDATE movie_meta "\ "SET cover_url = SUBSTRING_INDEX(cover_url, '/', -1), "\ "backdrop_url = SUBSTRING_INDEX(backdrop_url, '/', -1) "\ "where substring(cover_url, 1, 36 ) = 'http://d3gtl9l2a4fn1j.cloudfront.net' "\ "or substring(backdrop_url, 1, 36 ) = 'http://d3gtl9l2a4fn1j.cloudfront.net'" self.dbcur.execute(sql_update) self.dbcon.commit() common.addon.log('MySQL rows successfully updated') else: common.addon.log('No MySQL rows requiring update') else: sql_select = "SELECT imdb_id, tmdb_id, cover_url, thumb_url, backdrop_url "\ "FROM movie_meta "\ "WHERE substr(cover_url, 1, 36 ) = 'http://d3gtl9l2a4fn1j.cloudfront.net' "\ "OR substr(thumb_url, 1, 36 ) = 'http://d3gtl9l2a4fn1j.cloudfront.net' "\ "OR substr(backdrop_url, 1, 36 ) = 'http://d3gtl9l2a4fn1j.cloudfront.net' "\ "OR substr(cover_url, 1, 1 ) in ('w', 'o') "\ "OR substr(thumb_url, 1, 1 ) in ('w', 'o') "\ "OR substr(backdrop_url, 1, 1 ) in ('w', 'o') " self.dbcur.execute(sql_select) matchedrows = self.dbcur.fetchall() if matchedrows: dictrows = [dict(row) for row in matchedrows] for row in dictrows: if row["cover_url"]: row["cover_url"] = '/' + row["cover_url"].split('/')[-1] if row["thumb_url"]: row["thumb_url"] = '/' + row["thumb_url"].split('/')[-1] if row["backdrop_url"]: row["backdrop_url"] = '/' + row["backdrop_url"].split('/')[-1] sql_update = "UPDATE movie_meta SET cover_url = :cover_url, thumb_url = :thumb_url, backdrop_url = :backdrop_url WHERE imdb_id = :imdb_id and tmdb_id = :tmdb_id" self.dbcur.executemany(sql_update, dictrows) self.dbcon.commit() common.addon.log('SQLite rows successfully updated') else: common.addon.log('No SQLite rows requiring update') except Exception, e: common.addon.log('************* Error updating cover and backdrop columns: %s' % e, 4) pass ## !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! def __del__(self): ''' Cleanup db when object destroyed ''' try: self.dbcur.close() self.dbcon.close() except: pass def _cache_create_movie_db(self): ''' Creates the cache tables if they do not exist. ''' # Create Movie table sql_create = "CREATE TABLE IF NOT EXISTS movie_meta ("\ "imdb_id TEXT, "\ "tmdb_id TEXT, "\ "title TEXT, "\ "year INTEGER,"\ "director TEXT, "\ "writer TEXT, "\ "tagline TEXT, cast TEXT,"\ "rating FLOAT, "\ "votes TEXT, "\ "duration TEXT, "\ "plot TEXT,"\ "mpaa TEXT, "\ "premiered TEXT, "\ "genre TEXT, "\ "studio TEXT,"\ "thumb_url TEXT, "\ "cover_url TEXT, "\ "trailer_url TEXT, "\ "backdrop_url TEXT,"\ "imgs_prepacked TEXT,"\ "overlay INTEGER,"\ "UNIQUE(imdb_id, tmdb_id, title, year)"\ ");" if DB == 'mysql': sql_create = sql_create.replace("imdb_id TEXT","imdb_id VARCHAR(10)") sql_create = sql_create.replace("tmdb_id TEXT","tmdb_id VARCHAR(10)") sql_create = sql_create.replace("title TEXT" ,"title VARCHAR(255)") # hack to bypass bug in myconnpy # create table if not exists fails bc a warning about the table # already existing bubbles up as an exception. This suppresses the # warning which would just be logged anyway. # http://stackoverflow.com/questions/1650946/mysql-create-table-if-not-exists-error-1050 sql_hack = "SET sql_notes = 0;" self.dbcur.execute(sql_hack) self.dbcur.execute(sql_create) try: self.dbcur.execute('CREATE INDEX nameindex on movie_meta (title);') except: pass else: self.dbcur.execute(sql_create) self.dbcur.execute('CREATE INDEX IF NOT EXISTS nameindex on movie_meta (title);') common.addon.log('Table movie_meta initialized', 0) # Create TV Show table sql_create = "CREATE TABLE IF NOT EXISTS tvshow_meta ("\ "imdb_id TEXT, "\ "tvdb_id TEXT, "\ "title TEXT, "\ "year INTEGER,"\ "cast TEXT,"\ "rating FLOAT, "\ "duration TEXT, "\ "plot TEXT,"\ "mpaa TEXT, "\ "premiered TEXT, "\ "genre TEXT, "\ "studio TEXT,"\ "status TEXT,"\ "banner_url TEXT, "\ "cover_url TEXT,"\ "trailer_url TEXT, "\ "backdrop_url TEXT,"\ "imgs_prepacked TEXT,"\ "overlay INTEGER,"\ "UNIQUE(imdb_id, tvdb_id, title)"\ ");" if DB == 'mysql': sql_create = sql_create.replace("imdb_id TEXT","imdb_id VARCHAR(10)") sql_create = sql_create.replace("tvdb_id TEXT","tvdb_id VARCHAR(10)") sql_create = sql_create.replace("title TEXT" ,"title VARCHAR(255)") self.dbcur.execute(sql_create) try: self.dbcur.execute('CREATE INDEX nameindex on tvshow_meta (title);') except: pass else: self.dbcur.execute(sql_create) self.dbcur.execute('CREATE INDEX IF NOT EXISTS nameindex on tvshow_meta (title);') common.addon.log('Table tvshow_meta initialized', 0) # Create Season table sql_create = "CREATE TABLE IF NOT EXISTS season_meta ("\ "imdb_id TEXT, "\ "tvdb_id TEXT, " \ "season INTEGER, "\ "cover_url TEXT,"\ "overlay INTEGER,"\ "UNIQUE(imdb_id, tvdb_id, season)"\ ");" if DB == 'mysql': sql_create = sql_create.replace("imdb_id TEXT","imdb_id VARCHAR(10)") sql_create = sql_create.replace("tvdb_id TEXT","tvdb_id VARCHAR(10)") self.dbcur.execute(sql_create) else: self.dbcur.execute(sql_create) common.addon.log('Table season_meta initialized', 0) # Create Episode table sql_create = "CREATE TABLE IF NOT EXISTS episode_meta ("\ "imdb_id TEXT, "\ "tvdb_id TEXT, "\ "episode_id TEXT, "\ "season INTEGER, "\ "episode INTEGER, "\ "title TEXT, "\ "director TEXT, "\ "writer TEXT, "\ "plot TEXT, "\ "rating FLOAT, "\ "premiered TEXT, "\ "poster TEXT, "\ "overlay INTEGER, "\ "UNIQUE(imdb_id, tvdb_id, episode_id, title)"\ ");" if DB == 'mysql': sql_create = sql_create.replace("imdb_id TEXT" ,"imdb_id VARCHAR(10)") sql_create = sql_create.replace("tvdb_id TEXT" ,"tvdb_id VARCHAR(10)") sql_create = sql_create.replace("episode_id TEXT","episode_id VARCHAR(10)") sql_create = sql_create.replace("title TEXT" ,"title VARCHAR(255)") self.dbcur.execute(sql_create) else: self.dbcur.execute(sql_create) common.addon.log('Table episode_meta initialized', 0) # Create Addons table sql_create = "CREATE TABLE IF NOT EXISTS addons ("\ "addon_id TEXT, "\ "movie_covers TEXT, "\ "tv_covers TEXT, "\ "tv_banners TEXT, "\ "movie_backdrops TEXT, "\ "tv_backdrops TEXT, "\ "last_update TEXT, "\ "UNIQUE(addon_id)"\ ");" if DB == 'mysql': sql_create = sql_create.replace("addon_id TEXT", "addon_id VARCHAR(255)") self.dbcur.execute(sql_create) else: self.dbcur.execute(sql_create) common.addon.log('Table addons initialized', 0) # Create Configuration table sql_create = "CREATE TABLE IF NOT EXISTS config ("\ "setting TEXT, "\ "value TEXT, "\ "UNIQUE(setting)"\ ");" if DB == 'mysql': sql_create = sql_create.replace("setting TEXT", "setting VARCHAR(255)") sql_create = sql_create.replace("value TEXT", "value VARCHAR(255)") self.dbcur.execute(sql_create) else: self.dbcur.execute(sql_create) common.addon.log('Table config initialized', 0) def _init_movie_meta(self, imdb_id, tmdb_id, name, year=0): ''' Initializes a movie_meta dictionary with default values, to ensure we always have all fields Args: imdb_id (str): IMDB ID tmdb_id (str): TMDB ID name (str): full name of movie you are searching year (int): 4 digit year Returns: DICT in the structure of what is required to write to the DB ''' if year: int(year) else: year = 0 meta = {} meta['imdb_id'] = imdb_id meta['tmdb_id'] = str(tmdb_id) meta['title'] = name meta['year'] = int(year) meta['writer'] = '' meta['director'] = '' meta['tagline'] = '' meta['cast'] = [] meta['rating'] = 0 meta['votes'] = '' meta['duration'] = '' meta['plot'] = '' meta['mpaa'] = '' meta['premiered'] = '' meta['trailer_url'] = '' meta['genre'] = '' meta['studio'] = '' #set whether that database row will be accompanied by pre-packed images. meta['imgs_prepacked'] = self.classmode meta['thumb_url'] = '' meta['cover_url'] = '' meta['backdrop_url'] = '' meta['overlay'] = 6 return meta def _init_tvshow_meta(self, imdb_id, tvdb_id, name, year=0): ''' Initializes a tvshow_meta dictionary with default values, to ensure we always have all fields Args: imdb_id (str): IMDB ID tvdb_id (str): TVDB ID name (str): full name of movie you are searching year (int): 4 digit year Returns: DICT in the structure of what is required to write to the DB ''' if year: int(year) else: year = 0 meta = {} meta['imdb_id'] = imdb_id meta['tvdb_id'] = tvdb_id meta['title'] = name meta['TVShowTitle'] = name meta['rating'] = 0 meta['duration'] = '' meta['plot'] = '' meta['mpaa'] = '' meta['premiered'] = '' meta['year'] = int(year) meta['trailer_url'] = '' meta['genre'] = '' meta['studio'] = '' meta['status'] = '' meta['cast'] = [] meta['banner_url'] = '' #set whether that database row will be accompanied by pre-packed images. meta['imgs_prepacked'] = self.classmode meta['cover_url'] = '' meta['backdrop_url'] = '' meta['overlay'] = 6 meta['episode'] = 0 meta['playcount'] = 0 return meta def __init_episode_meta(self, imdb_id, tvdb_id, episode_title, season, episode, air_date): ''' Initializes a movie_meta dictionary with default values, to ensure we always have all fields Args: imdb_id (str): IMDB ID tvdb_id (str): TVDB ID episode_title (str): full name of Episode you are searching - NOT TV Show name season (int): episode season number episode (int): episode number air_date (str): air date (premiered data) of episode - YYYY-MM-DD Returns: DICT in the structure of what is required to write to the DB ''' meta = {} meta['imdb_id']=imdb_id meta['tvdb_id']='' meta['episode_id'] = '' meta['season']= int(season) meta['episode']= int(episode) meta['title']= episode_title meta['director'] = '' meta['writer'] = '' meta['plot'] = '' meta['rating'] = 0 meta['premiered'] = air_date meta['poster'] = '' meta['cover_url']= '' meta['trailer_url']='' meta['premiered'] = '' meta['backdrop_url'] = '' meta['overlay'] = 6 return meta def __get_tmdb_language(self): tmdb_language = common.addon.get_setting('tmdb_language') if tmdb_language: return re.sub(".*\((\w+)\).*","\\1",tmdb_language) else: return 'en' def __get_tvdb_language(self) : tvdb_language = common.addon.get_setting('tvdb_language') if tvdb_language and tvdb_language!='': return re.sub(".*\((\w+)\).*","\\1",tvdb_language) else: return 'en' def _string_compare(self, s1, s2): """ Method that takes two strings and returns True or False, based on if they are equal, regardless of case. """ try: return s1.lower() == s2.lower() except AttributeError: common.addon.log("Please only pass strings into this method.", 4) common.addon.log("You passed a %s and %s" % (s1.__class__, s2.__class__), 4) def _clean_string(self, string): """ Method that takes a string and returns it cleaned of any special characters in order to do proper string comparisons """ try: return ''.join(e for e in string if e.isalnum()) except: return string def _convert_date(self, string, in_format, out_format): ''' Helper method to convert a string date to a given format ''' #Legacy check, Python 2.4 does not have strptime attribute, instroduced in 2.5 if hasattr(datetime, 'strptime'): strptime = datetime.strptime else: strptime = lambda date_string, format: datetime(*(time.strptime(date_string, format)[0:6])) #strptime = lambda date_string, format: datetime(*(time.strptime(date_string, format)[0:6])) try: a = strptime(string, in_format).strftime(out_format) except Exception, e: common.addon.log('************* Error Date conversion failed: %s' % e, 4) return None return a def _downloadimages(self, url, path, name): ''' Download images to save locally Args: url (str): picture url path (str): destination path name (str): filename ''' if not xbmcvfs.exists(path): make_dir(path) full_path = os.path.join(path, name) self._dl_code(url, full_path) def _picname(self,url): ''' Get image name from url (ie my_movie_poster.jpg) Args: url (str): full url of image Returns: picname (str) representing image name from file ''' picname = re.split('\/+', url) return picname[-1] def _dl_code(self,url,mypath): ''' Downloads images to store locally Args: url (str): url of image to download mypath (str): local path to save image to ''' common.addon.log('Attempting to download image from url: %s ' % url, 0) common.addon.log('Saving to destination: %s ' % mypath, 0) if url.startswith('http://'): try: data = net.http_GET(url).content fh = open(mypath, 'wb') fh.write(data) fh.close() except Exception, e: common.addon.log('Image download failed: %s ' % e, 4) else: if url is not None: common.addon.log('Not a valid url: %s ' % url, 4) def _valid_imdb_id(self, imdb_id): ''' Check and return a valid IMDB ID Args: imdb_id (str): IMDB ID Returns: imdb_id (str) if valid with leading tt, else None ''' # add the tt if not found. integer aware. if imdb_id: if not imdb_id.startswith('tt'): imdb_id = 'tt%s' % imdb_id if re.search('tt[0-9]{7}', imdb_id): return imdb_id else: return None def _remove_none_values(self, meta): ''' Ensure we are not sending back any None values, XBMC doesn't like them ''' for item in meta: if meta[item] is None: meta[item] = '' return meta def __insert_from_dict(self, table, size): ''' Create a SQL Insert statement with dictionary values ''' sql = 'INSERT INTO %s ' % table if DB == 'mysql': format = ', '.join(['%s'] * size) else: format = ', '.join('?' * size) sql_insert = sql + 'Values (%s)' % format return sql_insert def __set_playcount(self, overlay): ''' Quick function to check overlay and set playcount Playcount info label is required to have > 0 in order for watched flag to display in Frodo ''' if int(overlay) == 7: return 1 else: return 0 def _get_config(self, setting): ''' Query local Config table for values ''' #Query local table first for current values sql_select = "SELECT * FROM config where setting = '%s'" % setting common.addon.log('Looking up in local cache for config data: %s' % setting, 0) common.addon.log('SQL Select: %s' % sql_select, 0) try: self.dbcur.execute(sql_select) matchedrow = self.dbcur.fetchone() except Exception, e: common.addon.log('************* Error selecting from cache db: %s' % e, 4) return None if matchedrow: common.addon.log('Found config data in cache table for setting: %s value: %s' % (setting, dict(matchedrow)), 0) return dict(matchedrow)['value'] else: common.addon.log('No match in local DB for config setting: %s' % setting, 0) return None def _set_config(self, setting, value): ''' Set local Config table for values ''' try: sql_insert = "REPLACE INTO config (setting, value) VALUES(%s,%s)" if DB == 'sqlite': sql_insert = 'INSERT OR ' + sql_insert.replace('%s', '?') common.addon.log('Updating local cache for config data: %s value: %s' % (setting, value), 2) common.addon.log('SQL Insert: %s' % sql_insert, 0) self.dbcur.execute(sql_insert, (setting, value)) self.dbcon.commit() except Exception, e: common.addon.log('************* Error updating cache db: %s' % e, 4) return None def _set_tmdb_config(self): ''' Query config database for required TMDB config values, set constants as needed Validate cache timestamp to ensure it is only refreshed once every 7 days ''' common.addon.log('Looking up TMDB config cache values', 2) tmdb_image_url = self._get_config('tmdb_image_url') tmdb_config_timestamp = self._get_config('tmdb_config_timestamp') #Grab current time in seconds now = time.time() age = 0 #Cache limit is 7 days, value needs to be in seconds: 60 seconds * 60 minutes * 24 hours * 7 days expire = 60 * 60 * 24 * 7 #Check if image and timestamp values are valid if tmdb_image_url and tmdb_config_timestamp: created = float(tmdb_config_timestamp) age = now - created common.addon.log('Cache age: %s , Expire: %s' % (age, expire), 0) #If cache hasn't expired, set constant values if age <= float(expire): common.addon.log('Cache still valid, setting values', 2) common.addon.log('Setting tmdb_image_url: %s' % tmdb_image_url, 0) self.tmdb_image_url = tmdb_image_url else: common.addon.log('Cache is too old, need to request new values', 2) #Either we don't have the values or the cache has expired, so lets request and set them - update cache in the end if (not tmdb_image_url or not tmdb_config_timestamp) or age > expire: common.addon.log('No cached config data found or cache expired, requesting from TMDB', 2) tmdb = TMDB(api_key=self.tmdb_api_key, lang=self.__get_tmdb_language()) config_data = tmdb.call_config() if config_data: self.tmdb_image_url = config_data['images']['base_url'] self._set_config('tmdb_image_url', config_data['images']['base_url']) self._set_config('tmdb_config_timestamp', now) else: self.tmdb_image_url = tmdb_image_url def check_meta_installed(self, addon_id): ''' Check if a meta data pack has been installed for a specific addon Queries the 'addons' table, if a matching row is found then we can assume the pack has been installed Args: addon_id (str): unique name/id to identify an addon Returns: matchedrow (dict) : matched row from addon table ''' if addon_id: sql_select = "SELECT * FROM addons WHERE addon_id = '%s'" % addon_id else: common.addon.log('Invalid addon id', 3) return False common.addon.log('Looking up in local cache for addon id: %s' % addon_id, 2) common.addon.log('SQL Select: %s' % sql_select, 0) try: self.dbcur.execute(sql_select) matchedrow = self.dbcur.fetchone() except Exception, e: common.addon.log('************* Error selecting from cache db: %s' % e, 4) return None if matchedrow: common.addon.log('Found addon id in cache table: %s' % dict(matchedrow), 0) return dict(matchedrow) else: common.addon.log('No match in local DB for addon_id: %s' % addon_id, 0) return False def insert_meta_installed(self, addon_id, last_update, movie_covers='false', tv_covers='false', tv_banners='false', movie_backdrops='false', tv_backdrops='false'): ''' Insert a record into addons table Insert a unique addon id AFTER a meta data pack has been installed Args: addon_id (str): unique name/id to identify an addon last_update (str): date of last meta pack installed - use to check to install meta updates Kwargs: movie_covers (str): true/false if movie covers has been downloaded/installed tv_covers (str): true/false if tv covers has been downloaded/installed movie_backdrops (str): true/false if movie backdrops has been downloaded/installed tv_backdrops (str): true/false if tv backdrops has been downloaded/installed ''' if addon_id: sql_insert = "INSERT INTO addons(addon_id, movie_covers, tv_covers, tv_banners, movie_backdrops, tv_backdrops, last_update) VALUES (?,?,?,?,?,?,?)" else: common.addon.log('Invalid addon id', 3) return common.addon.log('Inserting into addons table addon id: %s' % addon_id, 2) common.addon.log('SQL Insert: %s' % sql_insert, 0) try: self.dbcur.execute(sql_insert, (addon_id, movie_covers, tv_covers, tv_banners, movie_backdrops, tv_backdrops, last_update)) self.dbcon.commit() except Exception, e: common.addon.log('************* Error inserting into cache db: %s' % e, 4) return def update_meta_installed(self, addon_id, movie_covers=False, tv_covers=False, tv_banners=False, movie_backdrops=False, tv_backdrops=False, last_update=False): ''' Update a record into addons table Insert a unique addon id AFTER a meta data pack has been installed Args: addon_id (str): unique name/id to identify an addon Kwargs: movie_covers (str): true/false if movie covers has been downloaded/installed tv_covers (str): true/false if tv covers has been downloaded/installed tv_bannerss (str): true/false if tv banners has been downloaded/installed movie_backdrops (str): true/false if movie backdrops has been downloaded/installed tv_backdrops (str): true/false if tv backdrops has been downloaded/installed ''' if addon_id: if movie_covers: sql_update = "UPDATE addons SET movie_covers = '%s'" % movie_covers elif tv_covers: sql_update = "UPDATE addons SET tv_covers = '%s'" % tv_covers elif tv_banners: sql_update = "UPDATE addons SET tv_banners = '%s'" % tv_banners elif movie_backdrops: sql_update = "UPDATE addons SET movie_backdrops = '%s'" % movie_backdrops elif tv_backdrops: sql_update = "UPDATE addons SET tv_backdrops = '%s'" % tv_backdrops elif last_update: sql_update = "UPDATE addons SET last_update = '%s'" % last_update else: common.addon.log('No update field specified', 3) return else: common.addon.log('Invalid addon id', 3) return common.addon.log('Updating addons table addon id: %s movie_covers: %s tv_covers: %s tv_banners: %s movie_backdrops: %s tv_backdrops: %s last_update: %s' % (addon_id, movie_covers, tv_covers, tv_banners, movie_backdrops, tv_backdrops, last_update), 2) common.addon.log('SQL Update: %s' % sql_update, 0) try: self.dbcur.execute(sql_update) self.dbcon.commit() except Exception, e: common.addon.log('************* Error updating cache db: %s' % e, 4) return def get_meta(self, media_type, name, imdb_id='', tmdb_id='', year='', overlay=6, update=False): ''' Main method to get meta data for movie or tvshow. Will lookup by name/year if no IMDB ID supplied. Args: media_type (str): 'movie' or 'tvshow' name (str): full name of movie/tvshow you are searching Kwargs: imdb_id (str): IMDB ID tmdb_id (str): TMDB ID year (str): 4 digit year of video, recommended to include the year whenever possible to maximize correct search results. overlay (int): To set the default watched status (6=unwatched, 7=watched) on new videos Returns: DICT of meta data or None if cannot be found. ''' common.addon.log('---------------------------------------------------------------------------------------', 2) common.addon.log('Attempting to retreive meta data for %s: %s %s %s %s' % (media_type, name, year, imdb_id, tmdb_id), 2) if imdb_id: imdb_id = self._valid_imdb_id(imdb_id) if not update: if imdb_id: meta = self._cache_lookup_by_id(media_type, imdb_id=imdb_id) elif tmdb_id: meta = self._cache_lookup_by_id(media_type, tmdb_id=tmdb_id) else: meta = self._cache_lookup_by_name(media_type, name, year) else: meta = {} if not meta: if media_type==self.type_movie: meta = self._get_tmdb_meta(imdb_id, tmdb_id, name, year) elif media_type==self.type_tvshow: meta = self._get_tvdb_meta(imdb_id, name, year) self._cache_save_video_meta(meta, name, media_type, overlay) meta = self.__format_meta(media_type, meta, name) return meta def __format_meta(self, media_type, meta, name): ''' Format and massage movie/tv show data to prepare for return to addon Args: media_type (str): 'movie' or 'tvshow' meta (dict): movie / tv show meta data dictionary returned from cache or online name (str): full name of movie/tvshow you are searching Returns: DICT. Data formatted and corrected for proper return to xbmc addon ''' try: #We want to send back the name that was passed in meta['title'] = name #Change cast back into a tuple if meta['cast']: meta['cast'] = eval(str(meta['cast'])) #Return a trailer link that will play via youtube addon try: meta['trailer'] = '' trailer_id = '' if meta['trailer_url']: r = re.match('^[^v]+v=(.{3,11}).*', meta['trailer_url']) if r: trailer_id = r.group(1) else: trailer_id = meta['trailer_url'] if trailer_id: meta['trailer'] = 'plugin://plugin.video.youtube/?action=play_video&videoid=%s' % trailer_id except Exception, e: meta['trailer'] = '' common.addon.log('Failed to set trailer: %s' % e, 3) pass #Ensure we are not sending back any None values, XBMC doesn't like them meta = self._remove_none_values(meta) #Add TVShowTitle infolabel if media_type==self.type_tvshow: meta['TVShowTitle'] = meta['title'] #Set Watched flag for movies if media_type==self.type_movie: meta['playcount'] = self.__set_playcount(meta['overlay']) #if cache row says there are pre-packed images then either use them or create them if meta['imgs_prepacked'] == 'true': #define the image paths if media_type == self.type_movie: root_covers = self.mvcovers root_backdrops = self.mvbackdrops elif media_type == self.type_tvshow: root_covers = self.tvcovers root_backdrops = self.tvbackdrops root_banners = self.tvbanners if meta['cover_url']: cover_name = self._picname(meta['cover_url']) if cover_name: cover_path = os.path.join(root_covers, cover_name[0].lower()) if self.classmode == 'true': self._downloadimages(meta['cover_url'], cover_path, cover_name) meta['cover_url'] = os.path.join(cover_path, cover_name) if meta['backdrop_url']: backdrop_name = self._picname(meta['backdrop_url']) if backdrop_name: backdrop_path=os.path.join(root_backdrops, backdrop_name[0].lower()) if self.classmode == 'true': self._downloadimages(meta['backdrop_url'], backdrop_path, backdrop_name) meta['backdrop_url'] = os.path.join(backdrop_path, backdrop_name) if meta.has_key('banner_url'): if meta['banner_url']: banner_name = self._picname(meta['banner_url']) if banner_name: banner_path=os.path.join(root_banners, banner_name[0].lower()) if self.classmode == 'true': self._downloadimages(meta['banner_url'], banner_path, banner_name) meta['banner_url'] = os.path.join(banner_path, banner_name) #Else - they are online so piece together the full URL from TMDB else: if media_type == self.type_movie: if meta['cover_url'] and len(meta['cover_url']) > 1: if not meta['cover_url'].startswith('http'): meta['cover_url'] = self.tmdb_image_url + common.addon.get_setting('tmdb_poster_size') + meta['cover_url'] else: meta['cover_url'] = '' if meta['backdrop_url'] and len(meta['backdrop_url']) > 1: if not meta['backdrop_url'].startswith('http'): meta['backdrop_url'] = self.tmdb_image_url + common.addon.get_setting('tmdb_backdrop_size') + meta['backdrop_url'] else: meta['backdrop_url'] = '' common.addon.log('Returned Meta: %s' % meta, 0) return meta except Exception, e: common.addon.log('************* Error formatting meta: %s' % e, 4) return meta def update_meta(self, media_type, name, imdb_id, tmdb_id='', new_imdb_id='', new_tmdb_id='', year=''): ''' Updates and returns meta data for given movie/tvshow, mainly to be used with refreshing individual movies. Searches local cache DB for record, delete if found, calls get_meta() to grab new data name, imdb_id, tmdb_id should be what is currently in the DB in order to find current record new_imdb_id, new_tmdb_id should be what you would like to update the existing DB record to, which you should have already found Args: name (int): full name of movie you are searching imdb_id (str): IMDB ID of CURRENT entry Kwargs: tmdb_id (str): TMDB ID of CURRENT entry new_imdb_id (str): NEW IMDB_ID to search with new_tmdb_id (str): NEW TMDB ID to search with year (str): 4 digit year of video, recommended to include the year whenever possible to maximize correct search results. Returns: DICT of meta data or None if cannot be found. ''' common.addon.log('---------------------------------------------------------------------------------------', 2) common.addon.log('Updating meta data: %s Old: %s %s New: %s %s Year: %s' % (name.encode('ascii','replace'), imdb_id, tmdb_id, new_imdb_id, new_tmdb_id, year), 2) if imdb_id: imdb_id = self._valid_imdb_id(imdb_id) if imdb_id: meta = self._cache_lookup_by_id(media_type, imdb_id=imdb_id) elif tmdb_id: meta = self._cache_lookup_by_id(media_type, tmdb_id=tmdb_id) else: meta = self._cache_lookup_by_name(media_type, name, year) #if no old meta found, the year is probably not in the database if not imdb_id and not tmdb_id: year = '' if meta: overlay = meta['overlay'] self._cache_delete_video_meta(media_type, imdb_id, tmdb_id, name, year) else: overlay = 6 common.addon.log('No match found in cache db', 3) if not new_imdb_id: new_imdb_id = imdb_id elif not new_tmdb_id: new_tmdb_id = tmdb_id return self.get_meta(media_type, name, new_imdb_id, new_tmdb_id, year, overlay, True) def _cache_lookup_by_id(self, media_type, imdb_id='', tmdb_id=''): ''' Lookup in SQL DB for video meta data by IMDB ID Args: imdb_id (str): IMDB ID media_type (str): 'movie' or 'tvshow' Kwargs: imdb_id (str): IDMB ID tmdb_id (str): TMDB ID Returns: DICT of matched meta data or None if no match. ''' if media_type == self.type_movie: sql_select = "SELECT * FROM movie_meta" if imdb_id: sql_select = sql_select + " WHERE imdb_id = '%s'" % imdb_id else: sql_select = sql_select + " WHERE tmdb_id = '%s'" % tmdb_id elif media_type == self.type_tvshow: sql_select = ("SELECT a.*, " "CASE " "WHEN b.episode ISNULL THEN 0 " "ELSE b.episode " "END AS episode, " "CASE " "WHEN c.playcount ISNULL THEN 0 " "ELSE c.playcount " "END AS playcount " "FROM tvshow_meta a " "LEFT JOIN " "(SELECT imdb_id, " "count(imdb_id) AS episode " "FROM episode_meta " "WHERE imdb_id = '%s' " "GROUP BY imdb_id) b ON a.imdb_id = b.imdb_id " "LEFT JOIN " "(SELECT imdb_id, " "count(imdb_id) AS playcount " "FROM episode_meta " "WHERE imdb_id = '%s' " "AND OVERLAY=7 " "GROUP BY imdb_id) c ON a.imdb_id = c.imdb_id " "WHERE a.imdb_id = '%s'") % (imdb_id, imdb_id, imdb_id) if DB == 'mysql': sql_select = sql_select.replace("ISNULL", "IS NULL") common.addon.log('Looking up in local cache by id for: %s %s %s' % (media_type, imdb_id, tmdb_id), 0) common.addon.log( 'SQL Select: %s' % sql_select, 0) try: self.dbcur.execute(sql_select) matchedrow = self.dbcur.fetchone() except Exception, e: common.addon.log('************* Error selecting from cache db: %s' % e, 4) return None if matchedrow: common.addon.log('Found meta information by id in cache table: %s' % dict(matchedrow), 0) return dict(matchedrow) else: common.addon.log('No match in local DB', 0) return None def _cache_lookup_by_name(self, media_type, name, year=''): ''' Lookup in SQL DB for video meta data by name and year Args: media_type (str): 'movie' or 'tvshow' name (str): full name of movie/tvshow you are searching Kwargs: year (str): 4 digit year of video, recommended to include the year whenever possible to maximize correct search results. Returns: DICT of matched meta data or None if no match. ''' name = self._clean_string(name.lower()) if media_type == self.type_movie: sql_select = "SELECT * FROM movie_meta WHERE title = '%s'" % name elif media_type == self.type_tvshow: sql_select = "SELECT a.*, CASE WHEN b.episode ISNULL THEN 0 ELSE b.episode END AS episode, CASE WHEN c.playcount ISNULL THEN 0 ELSE c.playcount END as playcount FROM tvshow_meta a LEFT JOIN (SELECT imdb_id, count(imdb_id) AS episode FROM episode_meta GROUP BY imdb_id) b ON a.imdb_id = b.imdb_id LEFT JOIN (SELECT imdb_id, count(imdb_id) AS playcount FROM episode_meta WHERE overlay=7 GROUP BY imdb_id) c ON a.imdb_id = c.imdb_id WHERE a.title = '%s'" % name if DB == 'mysql': sql_select = sql_select.replace("ISNULL", "IS NULL") common.addon.log('Looking up in local cache by name for: %s %s %s' % (media_type, name, year), 0) # movie_meta doesn't have a year column if common.addon.get_setting('year_lock')=='true': if year and media_type == self.type_movie: sql_select = sql_select + " AND year = %s" % year common.addon.log('SQL Select: %s' % sql_select, 0) try: self.dbcur.execute(sql_select) matchedrow = self.dbcur.fetchone() except Exception, e: common.addon.log('************* Error selecting from cache db: %s' % e, 4) return None if matchedrow: common.addon.log('Found meta information by name in cache table: %s' % dict(matchedrow), 0) return dict(matchedrow) else: common.addon.log('No match in local DB', 0) return None def _cache_save_video_meta(self, meta_group, name, media_type, overlay=6): ''' Saves meta data to SQL table given type Args: meta_group (dict/list): meta data of video to be added to database can be a list of dicts (batch insert)or a single dict media_type (str): 'movie' or 'tvshow' Kwargs: overlay (int): To set the default watched status (6=unwatched, 7=watched) on new videos ''' try: if media_type == self.type_movie: table='movie_meta' elif media_type == self.type_tvshow: table='tvshow_meta' for meta in meta_group: #If a list of dicts (batch insert) has been passed in, ensure individual list item is converted to a dict if type(meta_group) is list: meta = dict(meta) name = meta['title'] #Else ensure we use the dict passed in else: meta = meta_group #strip title meta['title'] = self._clean_string(name.lower()) if meta.has_key('cast'): meta['cast'] = str(meta['cast']) #set default overlay - watched status meta['overlay'] = overlay common.addon.log('Saving cache information: %s' % meta, 0) if media_type == self.type_movie: sql_insert = self.__insert_from_dict(table, 22) self.dbcur.execute(sql_insert, (meta['imdb_id'], meta['tmdb_id'], meta['title'], meta['year'], meta['director'], meta['writer'], meta['tagline'], meta['cast'], meta['rating'], meta['votes'], meta['duration'], meta['plot'], meta['mpaa'], meta['premiered'], meta['genre'], meta['studio'], meta['thumb_url'], meta['cover_url'], meta['trailer_url'], meta['backdrop_url'], meta['imgs_prepacked'], meta['overlay'])) elif media_type == self.type_tvshow: sql_insert = self.__insert_from_dict(table, 19) common.addon.log('SQL INSERT: %s' % sql_insert, 0) self.dbcur.execute(sql_insert, (meta['imdb_id'], meta['tvdb_id'], meta['title'], meta['year'], meta['cast'], meta['rating'], meta['duration'], meta['plot'], meta['mpaa'], meta['premiered'], meta['genre'], meta['studio'], meta['status'], meta['banner_url'], meta['cover_url'], meta['trailer_url'], meta['backdrop_url'], meta['imgs_prepacked'], meta['overlay'])) #Break loop if we are dealing with just 1 record if type(meta_group) is dict: break #Commit all transactions self.dbcon.commit() common.addon.log('SQL INSERT Successfully Commited', 0) except Exception, e: common.addon.log('************* Error attempting to insert into %s cache table: %s ' % (table, e), 4) common.addon.log('Meta data: %s' % meta, 4) pass def _cache_delete_video_meta(self, media_type, imdb_id, tmdb_id, name, year): ''' Delete meta data from SQL table Args: media_type (str): 'movie' or 'tvshow' imdb_id (str): IMDB ID tmdb_id (str): TMDB ID name (str): Full movie name year (int): Movie year ''' if media_type == self.type_movie: table = 'movie_meta' elif media_type == self.type_tvshow: table = 'tvshow_meta' if imdb_id: sql_delete = "DELETE FROM %s WHERE imdb_id = '%s'" % (table, imdb_id) elif tmdb_id: sql_delete = "DELETE FROM %s WHERE tmdb_id = '%s'" % (table, tmdb_id) else: name = self._clean_string(name.lower()) sql_delete = "DELETE FROM %s WHERE title = '%s'" % (table, name) if year: sql_delete = sql_delete + ' AND year = %s' % (year) common.addon.log('Deleting table entry: %s %s %s %s ' % (imdb_id, tmdb_id, name, year), 0) common.addon.log('SQL DELETE: %s' % sql_delete, 0) try: self.dbcur.execute(sql_delete) self.dbcon.commit() except Exception, e: common.addon.log('************* Error attempting to delete from cache table: %s ' % e, 4) pass def _get_tmdb_meta(self, imdb_id, tmdb_id, name, year=''): ''' Requests meta data from TMDB and creates proper dict to send back Args: imdb_id (str): IMDB ID name (str): full name of movie you are searching Kwargs: year (str): 4 digit year of movie, when imdb_id is not available it is recommended to include the year whenever possible to maximize correct search results. Returns: DICT. It must also return an empty dict when no movie meta info was found from tmdb because we should cache these "None found" entries otherwise we hit tmdb alot. ''' tmdb = TMDB(api_key=self.tmdb_api_key, lang=self.__get_tmdb_language()) meta = tmdb.tmdb_lookup(name,imdb_id,tmdb_id, year) if meta is None: # create an empty dict so below will at least populate empty data for the db insert. meta = {} return self._format_tmdb_meta(meta, imdb_id, name, year) def _format_tmdb_meta(self, md, imdb_id, name, year): ''' Copy tmdb to our own for conformity and eliminate KeyError. Set default for values not returned Args: imdb_id (str): IMDB ID name (str): full name of movie you are searching Kwargs: year (str): 4 digit year of movie, when imdb_id is not available it is recommended to include the year whenever possible to maximize correct search results. Returns: DICT. It must also return an empty dict when no movie meta info was found from tvdb because we should cache these "None found" entries otherwise we hit tvdb alot. ''' #Intialize movie_meta dictionary meta = self._init_movie_meta(imdb_id, md.get('id', ''), name, year) meta['imdb_id'] = md.get('imdb_id', imdb_id) meta['title'] = md.get('name', name) meta['tagline'] = md.get('tagline', '') meta['rating'] = float(md.get('rating', 0)) meta['votes'] = str(md.get('votes', '')) meta['duration'] = str(md.get('runtime', 0)) meta['plot'] = md.get('overview', '') meta['mpaa'] = md.get('certification', '') meta['premiered'] = md.get('released', '') meta['director'] = md.get('director', '') meta['writer'] = md.get('writer', '') #Do whatever we can to set a year, if we don't have one lets try to strip it from premiered if not year and meta['premiered']: #meta['year'] = int(self._convert_date(meta['premiered'], '%Y-%m-%d', '%Y')) meta['year'] = int(meta['premiered'][:4]) meta['trailer_url'] = md.get('trailers', '') meta['genre'] = md.get('genre', '') #Get cast, director, writers cast_list = [] cast_list = md.get('cast','') if cast_list: for cast in cast_list: char = cast.get('character','') if not char: char = '' meta['cast'].append((cast.get('name',''),char )) crew_list = [] crew_list = md.get('crew','') if crew_list: for crew in crew_list: job=crew.get('job','') if job == 'Director': meta['director'] = crew.get('name','') elif job == 'Screenplay': if meta['writer']: meta['writer'] = meta['writer'] + ' / ' + crew.get('name','') else: meta['writer'] = crew.get('name','') genre_list = [] genre_list = md.get('genres', '') if(genre_list): meta['genre'] = '' for genre in genre_list: if meta['genre'] == '': meta['genre'] = genre.get('name','') else: meta['genre'] = meta['genre'] + ' / ' + genre.get('name','') if md.has_key('tvdb_studios'): meta['studio'] = md.get('tvdb_studios', '') try: meta['studio'] = (md.get('studios', '')[0])['name'] except: try: meta['studio'] = (md.get('studios', '')[1])['name'] except: try: meta['studio'] = (md.get('studios', '')[2])['name'] except: try: meta['studio'] = (md.get('studios', '')[3])['name'] except: common.addon.log('Studios failed: %s ' % md.get('studios', ''), 0) pass meta['cover_url'] = md.get('cover_url', '') meta['backdrop_url'] = md.get('backdrop_url', '') if md.has_key('posters'): # find first thumb poster url for poster in md['posters']: if poster['image']['size'] == 'thumb': meta['thumb_url'] = poster['image']['url'] break # find first cover poster url for poster in md['posters']: if poster['image']['size'] == 'cover': meta['cover_url'] = poster['image']['url'] break if md.has_key('backdrops'): # find first original backdrop url for backdrop in md['backdrops']: if backdrop['image']['size'] == 'original': meta['backdrop_url'] = backdrop['image']['url'] break return meta def _get_tvdb_meta(self, imdb_id, name, year=''): ''' Requests meta data from TVDB and creates proper dict to send back Args: imdb_id (str): IMDB ID name (str): full name of movie you are searching Kwargs: year (str): 4 digit year of movie, when imdb_id is not available it is recommended to include the year whenever possible to maximize correct search results. Returns: DICT. It must also return an empty dict when no movie meta info was found from tvdb because we should cache these "None found" entries otherwise we hit tvdb alot. ''' common.addon.log('Starting TVDB Lookup', 0) tvdb = TheTVDB(language=self.__get_tvdb_language()) tvdb_id = '' try: if imdb_id: tvdb_id = tvdb.get_show_by_imdb(imdb_id) except Exception, e: common.addon.log('************* Error retreiving from thetvdb.com: %s ' % e, 4) tvdb_id = '' pass #Intialize tvshow meta dictionary meta = self._init_tvshow_meta(imdb_id, tvdb_id, name, year) # if not found by imdb, try by name if tvdb_id == '': try: #If year is passed in, add it to the name for better TVDB search results if year: name = name + ' ' + year show_list=tvdb.get_matching_shows(name) except Exception, e: common.addon.log('************* Error retreiving from thetvdb.com: %s ' % e, 4) show_list = [] pass common.addon.log('Found TV Show List: %s' % show_list, 0) tvdb_id='' prob_id='' for show in show_list: (junk1, junk2, junk3) = show #if we match imdb_id or full name (with year) then we know for sure it is the right show if junk3==imdb_id or self._string_compare(self._clean_string(junk2),self._clean_string(name)): tvdb_id=self._clean_string(junk1) if not imdb_id: imdb_id=self._clean_string(junk3) break #if we match just the cleaned name (without year) keep the tvdb_id elif self._string_compare(self._clean_string(junk2),self._clean_string(name)): prob_id = junk1 if not imdb_id: imdb_id = self_clean_string(junk3) if tvdb_id == '' and prob_id != '': tvdb_id = self._clean_string(prob_id) if tvdb_id: common.addon.log('Show *** ' + name + ' *** found in TVdb. Getting details...', 0) try: show = tvdb.get_show(tvdb_id) except Exception, e: common.addon.log('************* Error retreiving from thetvdb.com: %s ' % e, 4) show = None pass if show is not None: meta['imdb_id'] = imdb_id meta['tvdb_id'] = tvdb_id meta['title'] = name if str(show.rating) != '' and show.rating != None: meta['rating'] = float(show.rating) meta['duration'] = show.runtime meta['plot'] = show.overview meta['mpaa'] = show.content_rating meta['premiered'] = str(show.first_aired) #Do whatever we can to set a year, if we don't have one lets try to strip it from show.first_aired/premiered if not year and show.first_aired: #meta['year'] = int(self._convert_date(meta['premiered'], '%Y-%m-%d', '%Y')) meta['year'] = int(meta['premiered'][:4]) if show.genre != '': temp = show.genre.replace("|",",") temp = temp[1:(len(temp)-1)] meta['genre'] = temp meta['studio'] = show.network meta['status'] = show.status if show.actors: for actor in show.actors: meta['cast'].append(actor) meta['banner_url'] = show.banner_url meta['imgs_prepacked'] = self.classmode meta['cover_url'] = show.poster_url meta['backdrop_url'] = show.fanart_url meta['overlay'] = 6 if meta['plot'] == 'None' or meta['plot'] == '' or meta['plot'] == 'TBD' or meta['plot'] == 'No overview found.' or meta['rating'] == 0 or meta['duration'] == 0 or meta['cover_url'] == '': common.addon.log(' Some info missing in TVdb for TVshow *** '+ name + ' ***. Will search imdb for more', 0) tmdb = TMDB(api_key=self.tmdb_api_key, lang=self.__get_tmdb_language()) imdb_meta = tmdb.search_imdb(name, imdb_id) if imdb_meta: imdb_meta = tmdb.update_imdb_meta(meta, imdb_meta) if imdb_meta.has_key('overview'): meta['plot'] = imdb_meta['overview'] if imdb_meta.has_key('rating'): meta['rating'] = float(imdb_meta['rating']) if imdb_meta.has_key('runtime'): meta['duration'] = imdb_meta['runtime'] if imdb_meta.has_key('cast'): meta['cast'] = imdb_meta['cast'] if imdb_meta.has_key('cover_url'): meta['cover_url'] = imdb_meta['cover_url'] return meta else: tmdb = TMDB(api_key=self.tmdb_api_key, lang=self.__get_tmdb_language()) imdb_meta = tmdb.search_imdb(name, imdb_id) if imdb_meta: meta = tmdb.update_imdb_meta(meta, imdb_meta) return meta else: return meta def search_movies(self, name): ''' Requests meta data from TMDB for any movie matching name Args: name (str): full name of movie you are searching Returns: Arry of dictionaries with trimmed down meta data, only returned data that is required: - IMDB ID - TMDB ID - Name - Year ''' common.addon.log('---------------------------------------------------------------------------------------', 2) common.addon.log('Meta data refresh - searching for movie: %s' % name, 2) tmdb = TMDB(api_key=self.tmdb_api_key, lang=self.__get_tmdb_language()) movie_list = [] meta = tmdb.tmdb_search(name) if meta: if meta['total_results'] == 0: common.addon.log('No results found', 2) return None for movie in meta['results']: if movie['release_date']: year = movie['release_date'][:4] else: year = None movie_list.append({'title': movie['title'],'original_title': movie['original_title'], 'imdb_id': '', 'tmdb_id': movie['id'], 'year': year}) else: common.addon.log('No results found', 2) return None common.addon.log('Returning results: %s' % movie_list, 0) return movie_list def similar_movies(self, tmdb_id, page=1): ''' Requests list of similar movies matching given tmdb id Args: tmdb_id (str): MUST be a valid TMDB ID Kwargs: page (int): page number of result to fetch Returns: List of dicts - each movie in it's own dict with supporting info ''' common.addon.log('---------------------------------------------------------------------------------------', 2) common.addon.log('TMDB - requesting similar movies: %s' % tmdb_id, 2) tmdb = TMDB(api_key=self.tmdb_api_key, lang=self.__get_tmdb_language()) movie_list = [] meta = tmdb.tmdb_similar_movies(tmdb_id, page) if meta: if meta['total_results'] == 0: common.addon.log('No results found', 2) return None for movie in meta['results']: movie_list.append(movie) else: common.addon.log('No results found', 2) return None common.addon.log('Returning results: %s' % movie_list, 0) return movie_list def get_episode_meta(self, tvshowtitle, imdb_id, season, episode, air_date='', episode_title='', overlay=''): ''' Requests meta data from TVDB for TV episodes, searches local cache db first. Args: tvshowtitle (str): full name of tvshow you are searching imdb_id (str): IMDB ID season (int): tv show season number, number only no other characters episode (int): tv show episode number, number only no other characters Kwargs: air_date (str): In cases where episodes have no episode number but only an air date - eg. daily talk shows episode_title (str): The title of the episode, gets set to the title infolabel which must exist overlay (int): To set the default watched status (6=unwatched, 7=watched) on new videos Returns: DICT. It must also return an empty dict when no meta info was found in order to save these. ''' common.addon.log('---------------------------------------------------------------------------------------', 2) common.addon.log('Attempting to retreive episode meta data for: imdbid: %s season: %s episode: %s air_date: %s' % (imdb_id, season, episode, air_date), 2) if not season: season = 0 if not episode: episode = 0 if imdb_id: imdb_id = self._valid_imdb_id(imdb_id) #Find tvdb_id for the TVshow tvdb_id = self._get_tvdb_id(tvshowtitle, imdb_id) #Check if it exists in local cache first meta = self._cache_lookup_episode(imdb_id, tvdb_id, season, episode, air_date) #If not found lets scrape online sources if not meta: #I need a tvdb id to scrape The TVDB if tvdb_id: meta = self._get_tvdb_episode_data(tvdb_id, season, episode, air_date) else: common.addon.log("No TVDB ID available, could not find TVshow with imdb: %s " % imdb_id, 0) #If nothing found if not meta: #Init episode meta structure meta = self.__init_episode_meta(imdb_id, tvdb_id, episode_title, season, episode, air_date) #set overlay if used, else default to unwatched if overlay: meta['overlay'] = int(overlay) else: meta['overlay'] = 6 if not meta['title']: meta['title']= episode_title meta['tvdb_id'] = tvdb_id meta['imdb_id'] = imdb_id meta['cover_url'] = meta['poster'] meta = self._get_tv_extra(meta) self._cache_save_episode_meta(meta) #Ensure we are not sending back any None values, XBMC doesn't like them meta = self._remove_none_values(meta) #Set Watched flag meta['playcount'] = self.__set_playcount(meta['overlay']) #Add key for subtitles to work meta['TVShowTitle']= tvshowtitle common.addon.log('Returned Meta: %s' % meta, 0) return meta def _get_tv_extra(self, meta): ''' When requesting episode information, not all data may be returned Fill in extra missing meta information from tvshow_meta table which should have already been populated. Args: meta (dict): current meta dict Returns: DICT containing the extra values ''' if meta['imdb_id']: sql_select = "SELECT * FROM tvshow_meta WHERE imdb_id = '%s'" % meta['imdb_id'] elif meta['tvdb_id']: sql_select = "SELECT * FROM tvshow_meta WHERE tvdb_id = '%s'" % meta['tvdb_id'] else: sql_select = "SELECT * FROM tvshow_meta WHERE title = '%s'" % self._clean_string(meta['title'].lower()) common.addon.log('Retrieving extra TV Show information from tvshow_meta', 0) common.addon.log('SQL SELECT: %s' % sql_select, 0) try: self.dbcur.execute(sql_select) matchedrow = self.dbcur.fetchone() except Exception, e: common.addon.log('************* Error attempting to select from tvshow_meta table: %s ' % e, 4) pass if matchedrow: match = dict(matchedrow) meta['genre'] = match['genre'] meta['duration'] = match['duration'] meta['studio'] = match['studio'] meta['mpaa'] = match['mpaa'] meta['backdrop_url'] = match['backdrop_url'] else: meta['genre'] = '' meta['duration'] = '0' meta['studio'] = '' meta['mpaa'] = '' meta['backdrop_url'] = '' return meta def _get_tvdb_id(self, name, imdb_id): ''' Retrieves TVID for a tv show that has already been scraped and saved in cache db. Used when scraping for season and episode data Args: name (str): full name of tvshow you are searching imdb_id (str): IMDB ID Returns: (str) imdb_id ''' #clean tvshow name of any extras name = self._clean_string(name.lower()) if imdb_id: sql_select = "SELECT tvdb_id FROM tvshow_meta WHERE imdb_id = '%s'" % imdb_id elif name: sql_select = "SELECT tvdb_id FROM tvshow_meta WHERE title = '%s'" % name else: return None common.addon.log('Retrieving TVDB ID', 0) common.addon.log('SQL SELECT: %s' % sql_select, 0) try: self.dbcur.execute(sql_select) matchedrow = self.dbcur.fetchone() except Exception, e: common.addon.log('************* Error attempting to select from tvshow_meta table: %s ' % e, 4) pass if matchedrow: return dict(matchedrow)['tvdb_id'] else: return None def update_episode_meta(self, name, imdb_id, season, episode, tvdb_id='', new_imdb_id='', new_tvdb_id=''): ''' Updates and returns meta data for given episode, mainly to be used with refreshing individual tv show episodes. Searches local cache DB for record, delete if found, calls get_episode_meta() to grab new data Args: name (int): full name of movie you are searching imdb_id (str): IMDB ID season (int): season number episode (int): episode number Kwargs: tvdb_id (str): TVDB ID Returns: DICT of meta data or None if cannot be found. ''' common.addon.log('---------------------------------------------------------------------------------------', 2) common.addon.log('Updating episode meta data: %s IMDB: %s SEASON: %s EPISODE: %s TVDB ID: %s NEW IMDB ID: %s NEW TVDB ID: %s' % (name, imdb_id, season, episode, tvdb_id, new_imdb_id, new_tvdb_id), 2) if imdb_id: imdb_id = self._valid_imdb_id(imdb_id) else: imdb_id = '' #Find tvdb_id for the TVshow tvdb_id = self._get_tvdb_id(name, imdb_id) #Lookup in cache table for existing entry meta = self._cache_lookup_episode(imdb_id, tvdb_id, season, episode) #We found an entry in the DB, so lets delete it if meta: overlay = meta['overlay'] self._cache_delete_episode_meta(imdb_id, tvdb_id, name, season, episode) else: overlay = 6 common.addon.log('No match found in cache db', 0) if not new_imdb_id: new_imdb_id = imdb_id elif not new_tvdb_id: new_tvdb_id = tvdb_id return self.get_episode_meta(name, imdb_id, season, episode, overlay=overlay) def _cache_lookup_episode(self, imdb_id, tvdb_id, season, episode, air_date=''): ''' Lookup in local cache db for episode data Args: imdb_id (str): IMDB ID tvdb_id (str): TheTVDB ID season (str): tv show season number, number only no other characters episode (str): tv show episode number, number only no other characters Kwargs: air_date (str): date episode was aired - YYYY-MM-DD Returns: DICT. Returns results found or None. ''' common.addon.log('Looking up episode data in cache db, imdb id: %s season: %s episode: %s air_date: %s' % (imdb_id, season, episode, air_date), 0) try: sql_select = ('SELECT ' 'episode_meta.title as title, ' 'episode_meta.plot as plot, ' 'episode_meta.director as director, ' 'episode_meta.writer as writer, ' 'tvshow_meta.genre as genre, ' 'tvshow_meta.duration as duration, ' 'episode_meta.premiered as premiered, ' 'tvshow_meta.studio as studio, ' 'tvshow_meta.mpaa as mpaa, ' 'tvshow_meta.title as TVShowTitle, ' 'episode_meta.imdb_id as imdb_id, ' 'episode_meta.rating as rating, ' '"" as trailer_url, ' 'episode_meta.season as season, ' 'episode_meta.episode as episode, ' 'episode_meta.overlay as overlay, ' 'tvshow_meta.backdrop_url as backdrop_url, ' 'episode_meta.poster as cover_url ' 'FROM episode_meta, tvshow_meta ' 'WHERE episode_meta.imdb_id = tvshow_meta.imdb_id AND ' 'episode_meta.tvdb_id = tvshow_meta.tvdb_id AND ' 'episode_meta.imdb_id = "%s" AND episode_meta.tvdb_id = "%s" AND ' ) % (imdb_id, tvdb_id) #If air_date is supplied, select on it instead of season & episode # if air_date: sql_select = sql_select + 'episode_meta.premiered = "%s" ' % air_date else: sql_select = sql_select + 'season = %s AND episode_meta.episode = %s ' % (season, episode) common.addon.log('SQL SELECT: %s' % sql_select, 0) self.dbcur.execute(sql_select) matchedrow = self.dbcur.fetchone() except Exception, e: common.addon.log('************* Error attempting to select from Episode table: %s ' % e, 4) return None if matchedrow: common.addon.log('Found episode meta information in cache table: %s' % dict(matchedrow), 0) return dict(matchedrow) else: return None def _cache_delete_episode_meta(self, imdb_id, tvdb_id, name, season, episode, air_date=''): ''' Delete meta data from SQL table Args: imdb_id (str): IMDB ID tvdb_id (str): TVDB ID name (str): Episode title season (int): Season # episode(int): Episode # Kwargs: air_date (str): Air Date of episode ''' if imdb_id: sql_delete = "DELETE FROM episode_meta WHERE imdb_id = '%s' AND tvdb_id = '%s' AND season = %s" % (imdb_id, tvdb_id, season) if air_date: sql_delete = sql_delete + ' AND premiered = "%s"' % air_date else: sql_delete = sql_delete + ' AND episode = %s' % episode common.addon.log('Deleting table entry: IMDB: %s TVDB: %s Title: %s Season: %s Episode: %s ' % (imdb_id, tvdb_id, name, season, episode), 0) common.addon.log('SQL DELETE: %s' % sql_delete, 0) try: self.dbcur.execute(sql_delete) self.dbcon.commit() except Exception, e: common.addon.log('************* Error attempting to delete from episode cache table: %s ' % e, 4) pass def _get_tvdb_episode_data(self, tvdb_id, season, episode, air_date=''): ''' Initiates lookup for episode data on TVDB Args: tvdb_id (str): TVDB id season (str): tv show season number, number only no other characters episode (str): tv show episode number, number only no other characters Kwargs: air_date (str): Date episode was aired Returns: DICT. Data found from lookup ''' meta = {} tvdb = TheTVDB(language=self.__get_tvdb_language()) if air_date: try: episode = tvdb.get_episode_by_airdate(tvdb_id, air_date) except: common.addon.log('************* Error retreiving from thetvdb.com: %s ' % e, 4) episode = None pass #We do this because the airdate method returns just a part of the overview unfortunately if episode: ep_id = episode.id if ep_id: try: episode = tvdb.get_episode(ep_id) except: common.addon.log('************* Error retreiving from thetvdb.com: %s ' % e, 4) episode = None pass else: try: episode = tvdb.get_episode_by_season_ep(tvdb_id, season, episode) except Exception, e: common.addon.log('************* Error retreiving from thetvdb.com: %s ' % e, 4) episode = None pass if episode is None: return None meta['episode_id'] = episode.id meta['plot'] = self._check(episode.overview) if episode.guest_stars: guest_stars = episode.guest_stars if guest_stars.startswith('|'): guest_stars = guest_stars[1:-1] guest_stars = guest_stars.replace('|', ', ') meta['plot'] = meta['plot'] + '\n\nGuest Starring: ' + guest_stars meta['rating'] = float(self._check(episode.rating,0)) meta['premiered'] = self._check(episode.first_aired) meta['title'] = self._check(episode.name) meta['poster'] = self._check(episode.image) meta['director'] = self._check(episode.director) meta['writer'] = self._check(episode.writer) meta['season'] = int(self._check(episode.season_number,0)) meta['episode'] = int(self._check(episode.episode_number,0)) return meta def _check(self, value, ret=None): if value is None or value == '': if ret == None: return '' else: return ret else: return value def _cache_save_episode_meta(self, meta): ''' Save episode data to local cache db. Args: meta (dict): episode data to be stored ''' if meta['imdb_id']: sql_select = 'SELECT * FROM episode_meta WHERE imdb_id = "%s" AND season = %s AND episode = %s AND premiered = "%s"' % (meta['imdb_id'], meta['season'], meta['episode'], meta['premiered']) sql_delete = 'DELETE FROM episode_meta WHERE imdb_id = "%s" AND season = %s AND episode = %s AND premiered = "%s"' % (meta['imdb_id'], meta['season'], meta['episode'], meta['premiered']) elif meta['tvdb_id']: sql_select = 'SELECT * FROM episode_meta WHERE tvdb_id = "%s" AND season = %s AND episode = %s AND premiered = "%s"' % (meta['tvdb_id'], meta['season'], meta['episode'], meta['premiered']) sql_delete = 'DELETE FROM episode_meta WHERE tvdb_id = "%s" AND season = %s AND episode = %s AND premiered = "%s"' % (meta['tvdb_id'], meta['season'], meta['episode'], meta['premiered']) else: sql_select = 'SELECT * FROM episode_meta WHERE title = "%s" AND season = %s AND episode = %s AND premiered = "%s"' % (self._clean_string(meta['title'].lower()), meta['season'], meta['episode'], meta['premiered']) sql_delete = 'DELETE FROM episode_meta WHERE title = "%s" AND season = %s AND episode = %s AND premiered = "%s"' % (self._clean_string(meta['title'].lower()), meta['season'], meta['episode'], meta['premiered']) common.addon.log('Saving Episode Meta', 0) common.addon.log('SQL Select: %s' % sql_select, 0) try: self.dbcur.execute(sql_select) matchedrow = self.dbcur.fetchone() if matchedrow: common.addon.log('Episode matched row found, deleting table entry', 0) common.addon.log('SQL Delete: %s' % sql_delete, 0) self.dbcur.execute(sql_delete) except Exception, e: common.addon.log('************* Error attempting to delete from cache table: %s ' % e, 4) common.addon.log('Meta data: %' % meta, 4) pass common.addon.log('Saving episode cache information: %s' % meta, 0) try: sql_insert = self.__insert_from_dict('episode_meta', 13) common.addon.log('SQL INSERT: %s' % sql_insert, 0) self.dbcur.execute(sql_insert, (meta['imdb_id'], meta['tvdb_id'], meta['episode_id'], meta['season'], meta['episode'], meta['title'], meta['director'], meta['writer'], meta['plot'], meta['rating'], meta['premiered'], meta['poster'], meta['overlay']) ) self.dbcon.commit() except Exception, e: common.addon.log('************* Error attempting to insert into episodes cache table: %s ' % e, 4) common.addon.log('Meta data: %s' % meta, 4) pass def update_trailer(self, media_type, imdb_id, trailer, tmdb_id=''): ''' Change videos trailer Args: media_type (str): media_type of video to update, 'movie', 'tvshow' or 'episode' imdb_id (str): IMDB ID trailer (str): url of youtube video Kwargs: tmdb_id (str): TMDB ID ''' if media_type == 'movie': table='movie_meta' elif media_type == 'tvshow': table='tvshow_meta' if imdb_id: imdb_id = self._valid_imdb_id(imdb_id) if imdb_id: sql_update = "UPDATE %s set trailer_url='%s' WHERE imdb_id = '%s'" % (table, trailer, imdb_id) elif tmdb_id: sql_update = "UPDATE %s set trailer_url='%s' WHERE tmdb_id = '%s'" % (table, trailer, tmdb_id) common.addon.log('Updating trailer for type: %s, imdb id: %s, tmdb_id: %s, trailer: %s' % (media_type, imdb_id, tmdb_id, trailer), 0) common.addon.log('SQL UPDATE: %s' % sql_update, 0) try: self.dbcur.execute(sql_update) self.dbcon.commit() except Exception, e: common.addon.log('************* Error attempting to update table: %s ' % e, 4) pass def change_watched(self, media_type, name, imdb_id, tmdb_id='', season='', episode='', year='', watched='', air_date=''): ''' Change watched status on video Args: imdb_id (str): IMDB ID media_type (str): type of video to update, 'movie', 'tvshow' or 'episode' name (str): name of video Kwargs: season (int): season number episode (int): episode number year (int): Year watched (int): Can specify what to change watched status (overlay) to ''' common.addon.log('---------------------------------------------------------------------------------------', 2) common.addon.log('Updating watched flag for: %s %s %s %s %s %s %s %s %s' % (media_type, name, imdb_id, tmdb_id, season, episode, year, watched, air_date), 2) if imdb_id: imdb_id = self._valid_imdb_id(imdb_id) tvdb_id = '' if media_type in (self.type_tvshow, self.type_season): tvdb_id = self._get_tvdb_id(name, imdb_id) if media_type in (self.type_movie, self.type_tvshow, self.type_season): if not watched: watched = self._get_watched(media_type, imdb_id, tmdb_id, season=season) if watched == 6: watched = 7 else: watched = 6 self._update_watched(imdb_id, media_type, watched, tmdb_id=tmdb_id, name=self._clean_string(name.lower()), year=year, season=season, tvdb_id=tvdb_id) elif media_type == self.type_episode: if tvdb_id is None: tvdb_id = '' tmp_meta = {} tmp_meta['imdb_id'] = imdb_id tmp_meta['tvdb_id'] = tvdb_id tmp_meta['title'] = name tmp_meta['season'] = season tmp_meta['episode'] = episode tmp_meta['premiered'] = air_date if not watched: watched = self._get_watched_episode(tmp_meta) if watched == 6: watched = 7 else: watched = 6 self._update_watched(imdb_id, media_type, watched, name=name, season=season, episode=episode, tvdb_id=tvdb_id, air_date=air_date) def _update_watched(self, imdb_id, media_type, new_value, tmdb_id='', name='', year='', season='', episode='', tvdb_id='', air_date=''): ''' Commits the DB update for the watched status Args: imdb_id (str): IMDB ID media_type (str): type of video to update, 'movie', 'tvshow' or 'episode' new_value (int): value to update overlay field with Kwargs: name (str): name of video season (str): season number tvdb_id (str): tvdb id of tvshow ''' if media_type == self.type_movie: if imdb_id: sql_update="UPDATE movie_meta SET overlay = %s WHERE imdb_id = '%s'" % (new_value, imdb_id) elif tmdb_id: sql_update="UPDATE movie_meta SET overlay = %s WHERE tmdb_id = '%s'" % (new_value, tmdb_id) else: sql_update="UPDATE movie_meta SET overlay = %s WHERE title = '%s'" % (new_value, name) if year: sql_update = sql_update + ' AND year=%s' % year elif media_type == self.type_tvshow: if imdb_id: sql_update="UPDATE tvshow_meta SET overlay = %s WHERE imdb_id = '%s'" % (new_value, imdb_id) elif tvdb_id: sql_update="UPDATE tvshow_meta SET overlay = %s WHERE tvdb_id = '%s'" % (new_value, tvdb_id) elif media_type == self.type_season: sql_update="UPDATE season_meta SET overlay = %s WHERE imdb_id = '%s' AND season = %s" % (new_value, imdb_id, season) elif media_type == self.type_episode: if imdb_id: sql_update="UPDATE episode_meta SET overlay = %s WHERE imdb_id = '%s'" % (new_value, imdb_id) elif tvdb_id: sql_update="UPDATE episode_meta SET overlay = %s WHERE tvdb_id = '%s'" % (new_value, tvdb_id) else: return None #If we have an air date use that instead of season/episode # if air_date: sql_update = sql_update + " AND premiered = '%s'" % air_date else: sql_update = sql_update + ' AND season = %s AND episode = %s' % (season, episode) else: # Something went really wrong return None common.addon.log('Updating watched status for type: %s, imdb id: %s, tmdb_id: %s, new value: %s' % (media_type, imdb_id, tmdb_id, new_value), 0) common.addon.log('SQL UPDATE: %s' % sql_update, 0) try: self.dbcur.execute(sql_update) self.dbcon.commit() except Exception, e: common.addon.log('************* Error attempting to update table: %s ' % e, 4) pass def _get_watched(self, media_type, imdb_id, tmdb_id, season=''): ''' Finds the watched status of the video from the cache db Args: media_type (str): type of video to update, 'movie', 'tvshow' or 'episode' imdb_id (str): IMDB ID tmdb_id (str): TMDB ID Kwargs: season (int): tv show season number ''' sql_select = '' if media_type == self.type_movie: if imdb_id: sql_select="SELECT overlay FROM movie_meta WHERE imdb_id = '%s'" % imdb_id elif tmdb_id: sql_select="SELECT overlay FROM movie_meta WHERE tmdb_id = '%s'" % tmdb_id elif media_type == self.type_tvshow: sql_select="SELECT overlay FROM tvshow_meta WHERE imdb_id = '%s'" % imdb_id elif media_type == self.type_season: sql_select = "SELECT overlay FROM season_meta WHERE imdb_id = '%s' AND season = %s" % (imdb_id, season) common.addon.log('SQL Select: %s' % sql_select, 0) try: self.dbcur.execute(sql_select) matchedrow = self.dbcur.fetchone() except Exception, e: common.addon.log('************* Error attempting to select from %s table: %s ' % (table, e), 4) pass if matchedrow: return dict(matchedrow)['overlay'] else: return 6 def _get_watched_episode(self, meta): ''' Finds the watched status of the video from the cache db Args: meta (dict): full data of episode ''' if meta['imdb_id']: sql_select = "SELECT * FROM episode_meta WHERE imdb_id = '%s'" % meta['imdb_id'] elif meta['tvdb_id']: sql_select = "SELECT * FROM episode_meta WHERE tvdb_id = '%s'" % meta['tvdb_id'] else: sql_select = "SELECT * FROM episode_meta WHERE title = '%s'" % self._clean_string(meta['title'].lower()) if meta['premiered']: sql_select += " AND premiered = '%s'" % meta['premiered'] else: sql_select += ' AND season = %s AND episode = %s' % (meta['season'], meta['episode']) common.addon.log('Getting episode watched status', 0) common.addon.log('SQL Select: %s' % sql_select, 0) try: self.dbcur.execute(sql_select) matchedrow = self.dbcur.fetchone() except Exception, e: common.addon.log('************* Error attempting to select from episode_meta table: %s ' % e, 4) pass if matchedrow: return dict(matchedrow)['overlay'] else: return 6 def _find_cover(self, season, images): ''' Finds the url of the banner to be used as the cover from a list of images for a given season Args: season (str): tv show season number, number only no other characters images (dict): all images related Returns: (str) cover_url: url of the selected image ''' cover_url = '' for image in images: (banner_url, banner_type, banner_season) = image if banner_season == season and banner_type == 'season': cover_url = banner_url break return cover_url def get_seasons(self, tvshowtitle, imdb_id, seasons, overlay=6): ''' Requests from TVDB a list of images for a given tvshow and list of seasons Args: tvshowtitle (str): TV Show Title imdb_id (str): IMDB ID seasons (str): a list of seasons, numbers only Returns: (list) list of covers found for each season ''' if imdb_id: imdb_id = self._valid_imdb_id(imdb_id) coversList = [] tvdb_id = self._get_tvdb_id(tvshowtitle, imdb_id) images = None for season in seasons: meta = self._cache_lookup_season(imdb_id, tvdb_id, season) if meta is None: meta = {} if tvdb_id is None or tvdb_id == '': meta['cover_url']='' elif images: meta['cover_url']=self._find_cover(season, images ) else: if len(str(season)) == 4: meta['cover_url']='' else: images = self._get_season_posters(tvdb_id, season) meta['cover_url']=self._find_cover(season, images ) meta['season'] = int(season) meta['tvdb_id'] = tvdb_id meta['imdb_id'] = imdb_id meta['overlay'] = overlay meta['backdrop_url'] = self._get_tvshow_backdrops(imdb_id, tvdb_id) #Ensure we are not sending back any None values, XBMC doesn't like them meta = self._remove_none_values(meta) self._cache_save_season_meta(meta) #Set Watched flag meta['playcount'] = self.__set_playcount(meta['overlay']) coversList.append(meta) return coversList def update_season(self, tvshowtitle, imdb_id, season): ''' Update an individual season: - looks up and deletes existing entry, saving watched flag (overlay) - re-scans TVDB for season image Args: tvshowtitle (str): TV Show Title imdb_id (str): IMDB ID season (int): season number to be refreshed Returns: (list) list of covers found for each season ''' #Find tvdb_id for the TVshow tvdb_id = self._get_tvdb_id(tvshowtitle, imdb_id) common.addon.log('---------------------------------------------------------------------------------------', 2) common.addon.log('Updating season meta data: %s IMDB: %s TVDB ID: %s SEASON: %s' % (tvshowtitle, imdb_id, tvdb_id, season), 2) if imdb_id: imdb_id = self._valid_imdb_id(imdb_id) else: imdb_id = '' #Lookup in cache table for existing entry meta = self._cache_lookup_season(imdb_id, tvdb_id, season) #We found an entry in the DB, so lets delete it if meta: overlay = meta['overlay'] self._cache_delete_season_meta(imdb_id, tvdb_id, season) else: overlay = 6 common.addon.log('No match found in cache db', 0) return self.get_seasons(tvshowtitle, imdb_id, season, overlay) def _get_tvshow_backdrops(self, imdb_id, tvdb_id): ''' Gets the backdrop_url from tvshow_meta to be included with season & episode meta Args: imdb_id (str): IMDB ID tvdb_id (str): TVDB ID ''' sql_select = "SELECT backdrop_url FROM tvshow_meta WHERE imdb_id = '%s' AND tvdb_id = '%s'" % (imdb_id, tvdb_id) common.addon.log('SQL Select: %s' % sql_select, 0) try: self.dbcur.execute(sql_select) matchedrow = self.dbcur.fetchone() except Exception, e: common.addon.log('************* Error attempting to select from tvshow_meta table: %s ' % e, 4) pass if matchedrow: return dict(matchedrow)['backdrop_url'] else: return '' def _get_season_posters(self, tvdb_id, season): tvdb = TheTVDB(language=self.__get_tvdb_language()) try: images = tvdb.get_show_image_choices(tvdb_id) except Exception, e: common.addon.log('************* Error retreiving from thetvdb.com: %s ' % e, 4) images = None pass return images def _cache_lookup_season(self, imdb_id, tvdb_id, season): ''' Lookup data for a given season in the local cache DB. Args: imdb_id (str): IMDB ID tvdb_id (str): TVDB ID season (str): tv show season number, number only no other characters Returns: (dict) meta data for a match ''' common.addon.log('Looking up season data in cache db, imdb id: %s tvdb_id: %s season: %s' % (imdb_id, tvdb_id, season), 0) if imdb_id: sql_select = "SELECT a.*, b.backdrop_url FROM season_meta a, tvshow_meta b WHERE a.imdb_id = '%s' AND season =%s and a.imdb_id=b.imdb_id and a.tvdb_id=b.tvdb_id" % (imdb_id, season) elif tvdb_id: sql_select = "SELECT a.*, b.backdrop_url FROM season_meta a, tvshow_meta b WHERE a.tvdb_id = '%s' AND season =%s and a.imdb_id=b.imdb_id and a.tvdb_id=b.tvdb_id" % (tvdb_id, season) else: return None common.addon.log('SQL Select: %s' % sql_select, 0) try: self.dbcur.execute(sql_select) matchedrow = self.dbcur.fetchone() except Exception, e: common.addon.log('************* Error attempting to select from season_meta table: %s ' % e, 4) pass if matchedrow: common.addon.log('Found season meta information in cache table: %s' % dict(matchedrow), 0) return dict(matchedrow) else: return None def _cache_save_season_meta(self, meta): ''' Save data for a given season in local cache DB. Args: meta (dict): full meta data for season ''' try: self.dbcur.execute("SELECT * FROM season_meta WHERE imdb_id = '%s' AND season ='%s' " % ( meta['imdb_id'], meta['season'] ) ) matchedrow = self.dbcur.fetchone() if matchedrow: common.addon.log('Season matched row found, deleting table entry', 0) self.dbcur.execute("DELETE FROM season_meta WHERE imdb_id = '%s' AND season ='%s' " % ( meta['imdb_id'], meta['season'] ) ) except Exception, e: common.addon.log('************* Error attempting to delete from cache table: %s ' % e, 4) common.addon.log('Meta data: %s' % meta, 4) pass common.addon.log('Saving season cache information: %s' % meta, 0) try: sql_insert = self.__insert_from_dict('season_meta', 5) common.addon.log('SQL Insert: %s' % sql_insert, 0) self.dbcur.execute(sql_insert, (meta['imdb_id'],meta['tvdb_id'],meta['season'], meta['cover_url'],meta['overlay']) ) self.dbcon.commit() except Exception, e: common.addon.log('************* Error attempting to insert into seasons cache table: %s ' % e, 4) common.addon.log('Meta data: %s' % meta, 4) pass def _cache_delete_season_meta(self, imdb_id, tvdb_id, season): ''' Delete meta data from SQL table Args: imdb_id (str): IMDB ID tvdb_id (str): TVDB ID season (int): Season # ''' sql_delete = "DELETE FROM season_meta WHERE imdb_id = '%s' AND tvdb_id = '%s' and season = %s" % (imdb_id, tvdb_id, season) common.addon.log('Deleting table entry: IMDB: %s TVDB: %s Season: %s ' % (imdb_id, tvdb_id, season), 0) common.addon.log('SQL DELETE: %s' % sql_delete, 0) try: self.dbcur.execute(sql_delete) self.dbcon.commit() except Exception, e: common.addon.log('************* Error attempting to delete from season cache table: %s ' % e, 4) pass def get_batch_meta(self, media_type, batch_ids): ''' Main method to get meta data for movie or tvshow. Will lookup by name/year if no IMDB ID supplied. Args: media_type (str): 'movie' or 'tvshow' batch_ids (tuple): a list of tuples containing the following in order: - imdb_id (str) - tmdb_id (str) - movie/tvshow name (str) - year (int) Returns: DICT of meta data or None if cannot be found. ''' common.addon.log('---------------------------------------------------------------------------------------', 2) common.addon.log('Starting batch meta grab', 2) common.addon.log('Batch meta information passed in: %s' % batch_ids, 0) #Ensure IMDB ID's are formatted properly first new_batch_ids = [] for i,(imdb_id, tmdb_id, vidname, year) in enumerate(batch_ids): new_batch_ids.append((self._valid_imdb_id(imdb_id), tmdb_id, vidname, year)) #Check each record and determine if should query cache db against ID's or Name & Year batch_ids = [] batch_names = [] for x in new_batch_ids: if x[0] or x[1]: batch_ids.append((x[0], x[1], x[2], x[3])) else: batch_names.append((x[0], x[1], x[2], x[3])) cache_meta = [] #Determine how and then check local cache for meta data if batch_ids: temp_cache = self.__cache_batch_lookup_by_id(media_type, batch_ids) if temp_cache: cache_meta += temp_cache if batch_names: temp_cache = self.__cache_batch_lookup_by_id(media_type, batch_names) if temp_cache: cache_meta += temp_cache print cache_meta #Check if any records were not found in cache, store them in list if not found no_cache_ids = [] if cache_meta: for m in new_batch_ids: try: x = next((i for i,v in enumerate(cache_meta) if v['imdb_id'] == m[0] or v['tmdb_id'] == m[1] or v['name'] == m[2] ), None) except: x = None if x is None: no_cache_ids.append(m) else: cache_meta = [] no_cache_ids = new_batch_ids new_meta = [] for record in no_cache_ids: if media_type==self.type_movie: meta = self._get_tmdb_meta(record[0], record[1], record[2], record[3]) common.addon.log('---------------------------------------------------------------------------------------', 2) elif media_type==self.type_tvshow: meta = self._get_tvdb_meta(record[0], record[1], record[2], record[3]) common.addon.log('---------------------------------------------------------------------------------------', 2) new_meta.append(meta) #If we found any new meta, add it to our cache list if new_meta: cache_meta += new_meta #Save any new meta to cache self._cache_save_video_meta(new_meta, 'test', media_type) #Format and return final list of meta return_meta = [] for meta in cache_meta: if type(meta) is database.Row: meta = dict(meta) meta = self.__format_meta(media_type, meta,'test') return_meta.append(meta) return return_meta def __cache_batch_lookup_by_id(self, media_type, batch_ids): ''' Lookup in SQL DB for video meta data by IMDB ID Args: media_type (str): 'movie' or 'tvshow' batch_ids (tuple): a list of list items containing the following in order: - imdb_id (str)* - tmdb_id (str) - name (str) - year (int) Returns: DICT of matched meta data or None if no match. ''' placeholder= '?' placeholders= ', '.join(placeholder for x in batch_ids) ids = [] if media_type == self.type_movie: sql_select = "SELECT * FROM movie_meta a" #If there is an IMDB ID given then use it for entire operation if batch_ids[0][0]: sql_select = sql_select + " WHERE a.imdb_id IN (%s)" % placeholders for x in batch_ids: ids.append(x[0]) #If no IMDB but TMDB then use that instead elif batch_ids[0][1]: sql_select = sql_select + " WHERE a.tmdb_id IN (%s)" % placeholders for x in batch_ids: ids.append(x[1]) #If no id's given then default to use the name and year elif batch_ids[0][2]: #If we have a year then need to inner join with same table if batch_ids[0][3]: sql_select = sql_select + (" INNER JOIN " "(SELECT title, year FROM movie_meta " "WHERE year IN (%s)) b " "ON a.title = b.title AND a.year = b.year " "WHERE a.title in (%s) ") % (placeholders, placeholders) #If no year then just straight select on name else: sql_select = sql_select + " WHERE a.title IN (%s)" % placeholders for x in batch_ids: ids.append(self._clean_string(x[2].lower())) else: common.addon.log( 'No data given to create SQL SELECT or data types are currently unsupported', 4) return None common.addon.log( 'SQL Select: %s' % sql_select, 0) try: self.dbcur.execute(sql_select, ids) matchedrows = self.dbcur.fetchall() except Exception, e: common.addon.log('************* Error selecting from cache db: %s' % e, 4) return None if matchedrows: for row in matchedrows: common.addon.log('Found meta information by id in cache table: %s' % dict(row), 0) return matchedrows else: common.addon.log('No match in local DB', 0) return None
b3abfd0204518eb7ed54ea70130691f577dfb279
[ "Python" ]
1
Python
mash2k3/MashUpFixes
459454c3f780a58e01a2b4edceb71ad245ee3f5f
0318dc93f960509f436ffd58833542939adf3e35
refs/heads/master
<file_sep># Copyright 2016, <NAME>, mailto:<EMAIL> # # Part of "Nuitka", an optimizing Python compiler that is compatible and # integrates with CPython, but also works on its own. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ Control the flow of optimizations applied to node tree. Applies abstract execution on all so far known modules until no more optimization is possible. Every successful optimization to anything might make others possible. """ import inspect from logging import debug, info, warning from nuitka import ModuleRegistry, Options, VariableRegistry from nuitka.optimizations import TraceCollections from nuitka.plugins.Plugins import Plugins from nuitka.Tracing import printLine from nuitka.utils import MemoryUsage from .Tags import TagSet _progress = Options.isShowProgress() def _attemptRecursion(module): new_modules = module.attemptRecursion() for new_module in new_modules: debug( "{source_ref} : {tags} : {message}".format( source_ref = new_module.getSourceReference().getAsString(), tags = "new_code", message = "Recursed to module package." ) ) tag_set = None def signalChange(tags, source_ref, message): """ Indicate a change to the optimization framework. """ if message is not None: debug( "{source_ref} : {tags} : {message}".format( source_ref = source_ref.getAsString(), tags = tags, message = message() if inspect.isfunction(message) else message ) ) tag_set.onSignal(tags) # Use this globally from there, without cyclic dependency. TraceCollections.signalChange = signalChange graph = None computation_counters = {} def optimizePythonModule(module): if _progress: printLine( "Doing module local optimizations for '{module_name}'.".format( module_name = module.getFullName() ) ) # The tag set is global, so it can react to changes without context. # pylint: disable=W0603 global tag_set tag_set = TagSet() touched = False if _progress: memory_watch = MemoryUsage.MemoryWatch() while True: tag_set.clear() try: module.computeModule() except BaseException: info("Interrupted while working on '%s'." % module) raise if not tag_set: break if graph is not None: computation_counters[module] = computation_counters.get(module, 0) + 1 module_graph = module.asGraph(computation_counters[module]) graph.subgraph(module_graph) touched = True if _progress: memory_watch.finish() printLine( "Memory usage changed during optimization of '%s': %s" % ( module.getFullName(), memory_watch.asStr() ) ) Plugins.considerImplicitImports(module, signal_change = signalChange) return touched def optimizeShlibModule(module): # Pick up parent package if any. _attemptRecursion(module) # The tag set is global, so it can react to changes without context. # pylint: disable=W0603 global tag_set tag_set = TagSet() Plugins.considerImplicitImports(module, signal_change = signalChange) def areEmptyTraces(variable_traces): empty = True for variable_trace in variable_traces: if variable_trace.isAssignTrace(): empty = False break elif variable_trace.isInitTrace(): empty = False break elif variable_trace.isUninitTrace(): if variable_trace.getPrevious(): # A "del" statement can do this, and needs to prevent variable # from being removed. empty = False break elif variable_trace.hasDefiniteUsages(): # Checking definite is enough, the merges, we shall see # them as well. empty = False break elif variable_trace.isUnknownTrace(): if variable_trace.hasDefiniteUsages(): # Checking definite is enough, the merges, we shall see # them as well. empty = False break elif variable_trace.isMergeTrace(): if variable_trace.hasDefiniteUsages(): # Checking definite is enough, the merges, we shall see # them as well. empty = False break elif variable_trace.isEscaped(): assert False, variable_trace # If the value is escape, we still need to keep it for that # escape opportunity. This is only while that is not seen # as a definite usage. empty = False break else: assert False, variable_trace return empty def areReadOnlyTraces(variable_traces): read_only = True for variable_trace in variable_traces: if variable_trace.isAssignTrace(): read_only = False break elif variable_trace.isInitTrace(): read_only = False break return read_only def optimizeUnusedClosureVariables(function_body): for closure_variable in function_body.getClosureVariables(): # print "VAR", closure_variable # Need to take closure of if closure_variable.isParameterVariable() and \ function_body.isExpressionGeneratorObjectBody(): continue if function_body.hasFlag("has_super") and closure_variable.getName() in ("__class__", "self"): continue variable_traces = function_body.constraint_collection.getVariableTraces( variable = closure_variable ) empty = areEmptyTraces(variable_traces) if empty: signalChange( "var_usage", function_body.getSourceReference(), message = "Remove unused closure variable." ) function_body.removeClosureVariable(closure_variable) else: read_only = areReadOnlyTraces(variable_traces) if read_only: global_trace = closure_variable.getGlobalVariableTrace() if global_trace is not None: if not global_trace.hasWritesOutsideOf(function_body): function_body.demoteClosureVariable(closure_variable) signalChange( "var_usage", function_body.getSourceReference(), message = "Turn read-only usage of unassigned closure variable to local variable." ) def optimizeUnusedUserVariables(function_body): for local_variable in function_body.getUserLocalVariables(): variable_traces = function_body.constraint_collection.getVariableTraces( variable = local_variable ) empty = areEmptyTraces(variable_traces) if empty: function_body.removeUserVariable(local_variable) def optimizeUnusedTempVariables(provider): for temp_variable in provider.getTempVariables(): variable_traces = provider.constraint_collection.getVariableTraces( variable = temp_variable ) empty = areEmptyTraces(variable_traces) if empty: provider.removeTempVariable(temp_variable) def optimizeVariables(module): for function_body in module.getUsedFunctions(): if not VariableRegistry.complete: continue optimizeUnusedUserVariables(function_body) optimizeUnusedClosureVariables(function_body) optimizeUnusedTempVariables(function_body) optimizeUnusedTempVariables(module) def optimize(): # This is somewhat complex with many cases, pylint: disable=R0912 # We maintain this globally to make it accessible, pylint: disable=W0603 global graph if Options.shouldCreateGraph(): try: from graphviz import Digraph # pylint: disable=F0401,I0021 graph = Digraph('G') except ImportError: warning("Cannot import graphviz module, no graphing capability.") while True: finished = True ModuleRegistry.startTraversal() while True: current_module = ModuleRegistry.nextModule() if current_module is None: break if _progress: printLine( """\ Optimizing module '{module_name}', {remaining:d} more modules to go \ after that. Memory usage {memory}:""".format( module_name = current_module.getFullName(), remaining = ModuleRegistry.remainingCount(), memory = MemoryUsage.getHumanReadableProcessMemoryUsage() ) ) if current_module.isPythonShlibModule(): optimizeShlibModule(current_module) else: changed = optimizePythonModule(current_module) if changed: finished = False # Unregister collection traces from now unused code. for current_module in ModuleRegistry.getDoneModules(): if not current_module.isPythonShlibModule(): for function in current_module.getUnusedFunctions(): VariableRegistry.updateFromCollection( old_collection = function.constraint_collection, new_collection = None ) function.constraint_collection = None if VariableRegistry.considerCompletion(): finished = False for current_module in ModuleRegistry.getDoneModules(): if not current_module.isPythonShlibModule(): optimizeVariables(current_module) if finished: break if graph is not None: graph.engine = "dot" graph.graph_attr["rankdir"] = "TB" graph.render("something.dot") printLine(graph.source)
b43537f6e251e843b898fdeb38c85d88848a8f0b
[ "Python" ]
1
Python
simdeveloper/Nuitka
2726d28bccb34bd1c0dc94b336df8d3b2fc25539
2d9e268cd8d277526a8650cd70f036566ed033e5
refs/heads/master
<repo_name>TessieDeiza/Firebase-Hosting-DB<file_sep>/functions/index.js const functions = require('firebase-functions'); const express = require('express'); const engines = require('consolidate'); var hbs = require('handlebars'); const admin = require('firebase-admin'); //window.document.write('<script type="text/javascript" src="https://www.gstatic.com/firebasejs/4.1.3/firebase.js" ></script>'); // // Create and Deploy Your First Cloud Functions // // https://firebase.google.com/docs/functions/write-firebase-functions // // exports.helloWorld = functions.https.onRequest((request, response) => { // response.send("Hello from Firebase!"); // }); // const app = express(); app.engine('hbs',engines.handlebars); app.set('views','./views'); app.set('view engine','hbs'); // var serviceAccount = require("./yetu-festival-firebase-adminsdk-<KEY>"); // admin.initializeApp({ // credential: admin.credential.cert(serviceAccount), // databaseURL: "https://yetu-festival.firebaseio.com" // }); admin.initializeApp(functions.config().firebase); async function getFirestore(){ const firestore_con = await admin.firestore(); const writeResult = firestore_con.collection('topImage').doc('url').get().then(doc => { if (!doc.exists) { console.log('No such document!'); } else {return doc.data();}}) .catch(err => { console.log('Error getting document', err);}); return writeResult } app.get('/',async (request,response) =>{ var db_result = await getFirestore(); response.render('index',{db_result}); }); app.get('/login', (request, response) => { response.render('login'); }); app.get('/admin', (request, response) => { response.render('admin'); }); exports.app = functions.https.onRequest(app);<file_sep>/public/scripts/login.js const Config = { apiKey: "<KEY>", authDomain: "yetu-festival.firebaseapp.com", databaseURL: "https://yetu-festival.firebaseio.com", projectId: "yetu-festival", storageBucket: "yetu-festival.appspot.com", messagingSenderId: "969603133155", appId: "1:969603133155:web:c36a5a88a9c5b595c2dfd6", measurementId: "G-8FG0QQRPR6" }; firebase.auth().onAuthStateChanged(function(user) { if (user) { window.location("/admin") } else { window.location("/login") } }); function login(){ const email = document.getElementById("user_email").value; const password = document.getElementById("user_password").value; firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; window.alert("Error" + errorMessage); }); } firebase.auth().onAuthStateChanged(function(user) { if (user) { window.alert(user); window.alert("should not redirect"); //window.location.href = "/admin"; } else { window.alert("supposed to fail"); //window.location.href = "/login"; } });<file_sep>/src/services/firebase.js <!-- The core Firebase JS SDK is always required and must be listed first --> <script src="/__/firebase/7.14.1/firebase-app.js"></script> <!-- TODO: Add SDKs for Firebase products that you want to use https://firebase.google.com/docs/web/setup#available-libraries --> <script src="/__/firebase/7.14.1/firebase-analytics.js"></script> <!-- Initialize Firebase --> <script src="/__/firebase/init.js"></script> const firebaseConfig = { apiKey: "<KEY>", authDomain: "yetu-festival.firebaseapp.com", databaseURL: "https://yetu-festival.firebaseio.com", projectId: "yetu-festival", storageBucket: "yetu-festival.appspot.com", messagingSenderId: "969603133155", appId: "1:969603133155:web:c36a5a88a9c5b595c2dfd6", measurementId: "G-8FG0QQRPR6" };<file_sep>/public/scripts/main.js console.log("reached js block"); var firebaseConfig = { apiKey: "<KEY>", authDomain: "yetu-festival.firebaseapp.com", databaseURL: "https://yetu-festival.firebaseio.com", projectId: "yetu-festival", storageBucket: "yetu-festival.appspot.com", messagingSenderId: "969603133155", appId: "1:969603133155:web:c36a5a88a9c5b595c2dfd6", measurementId: "G-8FG0QQRPR6" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); database = firebase.database(); var topref = database.ref().child('topImage'); var bootomref = database.ref().child('bottomImage'); console.log("reached here now"); //console.log(ref); topref.on('value', gottopData, errtopData); bootomref.on('value', gotbottomData, errbottomData); function gottopData(data){ var value = Object.values(data.val()); var topImgUrl = value[1]; document.getElementsByClassName("image-banner-drinks")[0].setAttribute('src',topImgUrl) console.log(topImgUrl); } function errtopData(err){ console.log(err); } function gotbottomData(data){ var value = Object.values(data.val()); var bottomImgUrl = value[1]; document.getElementsByClassName("image-banner-food")[0].setAttribute('src',bottomImgUrl) console.log(bottomImgUrl); } function errbottomData(err){ console.log(err); } $(document).ready(function(){ setTimeout(showPopup,60000) }); function showPopup() { swal("Hello there!", "To continue watching the video, you are required to pay Ksh 10", "info"); }<file_sep>/README.md # yetu-festival Yetu festival code
736e89e80943f81693485836d24a59f22bed1c9d
[ "JavaScript", "Markdown" ]
5
JavaScript
TessieDeiza/Firebase-Hosting-DB
ce06dea197e2d85a44852d269359d286181e8673
af857703e79c7b5e529f36c7dcf30049a507ad6a
refs/heads/master
<file_sep>#!/usr/bin/expect -f set i 0; foreach el "$argv" { set "exp_[incr i]" "$el" } #Override the execution timeout ... set timeout 60 #The target expected command to execute spawn npm login [lindex $argv 3] [lindex $argv 4] match_max 100000 expect "Username" send "$exp_1\r" expect "<PASSWORD>" send "$exp_2\r" expect "Email" send "$exp_3\r" expect { timeout exit 1 eof } <file_sep># travis-npm-deploy [![license](https://img.shields.io/github/license/mashape/apistatus.svg?style=flat-square)](https://github.com/djanta/travis-npm-deploy/blob/master/LICENSE) [![Gitter](https://img.shields.io/gitter/room/nwjs/nw.js.svg?style=flat-square)](https://gitter.im/djantajs/tools?utm_source=share-link&utm_medium=link&utm_campaign=share-link) > Internal platform shared npm deploy script # Installation You can clone the repository `travis-npm-deploy` at [git](https://github.com/djanta/travis-npm-deploy.git). ```bash git clone https://github.com/djanta/travis-npm-deploy.git ~/travis-npm-deploy ``` Once the repository has been cloned and to be able to invoke our provided npm login tool, the `expect` command must be installed. To do so, you'll have to run the following command. ```bash sh ~/travis-npm-deploy/deploy.sh --install ``` # Usage ## Npm login ```bash sh ~/travis-npm-deploy/deploy.sh login --user=MyNpmUserName --password=<PASSWORD> --email=MyNpmUserEmail ``` ## Npm logout ```bash sh ~/travis-npm-deploy/deploy.sh logout #You pass any mandatory npm arugment here ``` ## Npm publish ```bash sh ~/travis-npm-deploy/deploy.sh #You pass any mandatory npm arugment here ``` # Git Confgiure Usage ```bash sh ~/travis-npm-deploy/deploy.sh --git-config ``` # Contributing I welcome any contributions, enhancements, and bug-fixes. [File an issue](https://github.com/djanta/travis-npm-deploy/issues) on GitHub and [submit a pull request](https://github.com/djanta/travis-npm-deploy/pulls). <file_sep>#!/usr/bin/env bash # --------------------------------------------------------------------------- # deploy.sh - This script will be use to perform travis-ci npm script based deploy # Copyright 2018, <NAME> "Fonder of DJANTA, LLC and djantajs creator" <<EMAIL>> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License at <http://www.gnu.org/licenses/> for more details. # --------------------------------------------------------------------------- set -e # exit with nonzero exit code if anything fails argv0=$(echo "$0" | sed -e 's,\\,/,g') basedir=$(dirname "$(readlink "$0" || echo "$argv0")") case "$(uname -s)" in Linux) basedir=$(dirname "$(readlink -f "$0" || echo "$argv0")");; *CYGWIN*) basedir=`cygpath -w "$basedir"`;; esac echo "Current script dir = $basedir" PROGNAME=${0##*/} V_REGEX='^(v[0-9]+\.){0,2}(\*|[0-9]+)$' LOCK_FILE='~/.npm-lock' #Copied from: https://github.com/fsaintjacques/semver-tool/blob/master/src/semver SEMVER_REGEX="^v(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(\\-[0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)?(\\+[0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)?$" DESCRIBE=`git describe --tags --always` ############################# PRIVATE FUNCTIONS ############################# _clean () { # Perform pre-exit housekeeping return } _error_exit () { echo -e "${PROGNAME}: ${1:-"Unknown Error"}" >&2 _clean exit 1 } _graceful_exit () { _clean exit } _signal_exit () { # Handle trapped signals case $1 in INT) _error_exit "Program interrupted by user" ;; TERM) echo -e "\n$PROGNAME: Program terminated" >&2 _graceful_exit ;; *) _error_exit "$PROGNAME: Terminating on unknown signal" ;; esac } _witch () { _witch "$1" } _isSu () { if [[ $(id -u) != 0 ]]; then _error_exit "You must be the superuser to run this script." fi } ############################# PUBLIC FUNCTIONS ############################# apt_install () { if ! which expect > /dev/null; then sudo apt-get update sudo apt-get install \ expect -y fi } ## # DEFINE TRAVIS GIT CONFIGURATION ## git_confg () { [ -n "${DEFINED_GIT_EMAIL##+([[:space:]])}" ] && GH_USER_EMAIL="$DEFINED_GIT_EMAIL" || GH_USER_EMAIL="$GH_USER_EMAIL" [ -n "${DEFINED_GIT_USER##+([[:space:]])}" ] && GH_USER="$DEFINED_GIT_USER" || GH_USER="$GH_USER" [ -n "${DEFINED_GIT_TOKEN##+([[:space:]])}" ] && GH_TOKEN="$DEFINED_GIT_TOKEN" || GH_TOKEN="$GH_TOKEN" git config user.name "$GDUSER" git config user.email "$GH_USER_EMAIL" git config credential.helper "store --file=.git/credentials" echo "https://$GH_TOKEN:@github.com" > .git/credentials } # Begin of Npm tools npm_login () { if which npm > /dev/null && which expect > /dev/null; then echo "Log into npm registry from ${basedir} ..." expect -f "${basedir}/npm/login.sh" ${@} fi } npm_logout () { if which npm > /dev/null; then echo "Login out from npm registry ..." npm logout ${@} fi } # end of Npm tools publish () { [ -n "${TAG_REG_EXPR##+([[:space:]])}" ] && TAG_REGEX=$TAG_REG_EXPR || TAG_REGEX=$SEMVER_REGEX if [[ "$TRAVIS_TAG" =~ $TAG_REGEX ]] && which npm > /dev/null; then echo "Publishing npm package from tag: $TRAVIS_TAG" npm publish ${@} #npm publish with the given command line option ... else echo "Unexpected tag branch: $TRAVIS_TAG to match with: $TAG_REGEX" _error_exit "Invalid given tag version lavel" #make sure with exit with error fi } #OPTS=${@:1:$#} case "${1}" in login) for O in ${@:2:$#}; do case "${O}" in -u=*|--user=*) USER_NAME="${O#*=}" ;; -p=*|--password=*) USER_PWD="${O#*=}" ;; -e=*|--email=*) USER_EMAIL="${O#*=}" ;; -s=*|--scope=*) NPM_SCOPE="--scope=@${O#*=}" ;; -r=*|--registry=*) NPM_REGISTRY="--registry=${O#*=}" ;; esac done; #npm_login ${@:2:$#} npm_login "$USER_NAME" "$USER_PWD" "$USER_EMAIL" "$NPM_SCOPE" "$NPM_REGISTRY" _graceful_exit ;; logout) npm_logout ${@:2:$#} _graceful_exit ;; -u|--config|--git-config) git_confg ${@:2:$#} _graceful_exit ;; -i|--install) apt_install ${@:2:$#} _graceful_exit ;; *) publish "${@:2:$#}" _graceful_exit ;; esac # Trap signals trap "_signal_exit TERM" TERM HUP trap "_signal_exit INT" INT # vim:set et sts=4 ts=4 tw=0:
ed16cc8d7eadba495dbf3b4ac811b7151fb7111e
[ "Markdown", "Shell" ]
3
Shell
djanta/travis-npm-deploy
7a72451e85d9ebc649d6f2ae466cc7198ab2a2d9
f2dd069ae04e2190ba8c862291bb308d248f722c
refs/heads/master
<repo_name>tmehta2442/toggler<file_sep>/config/initializers/session_store.rb # Be sure to restart your server when you modify this file. Toggler::Application.config.session_store :cookie_store, key: '_toggler_session' # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rails generate session_migration") # Toggler::Application.config.session_store :active_record_store
ff7b7e5e036c43a77445a8915d312ac213c5a3f2
[ "Ruby" ]
1
Ruby
tmehta2442/toggler
704ed25a4b8500e342835af76da3707666542290
a4fe780ae88cb8cf8c6de3cc5e25519cb91d402c
refs/heads/master
<file_sep>var FastClick = FastClick || {}; var GDrinker = GDrinker || {}; $(window).load(function () { new FastClick(document.body); console.log("FastClick Registered on Body (Android)"); }); <file_sep>/* ********************************************** App-Compiled used by GoodDrinker and concatenated to app-angular.min.js using CodeKit: Build Date: --BUILDDATE-- Build Version: --BUILDVERSION-- ********************************************** */ // @codekit-append "../scripts-src/jquery-1.7.2.min.js" // @codekit-append "../scripts-angular/angular-1.0.2.min.js" // @codekit-append "../scripts-src/bootstrap.min.js" // @codekit-append "../scripts-src/moment-1.7.0.min.js" // @codekit-append "../scripts-angular/app.js" // @codekit-append "../scripts-angular/app-services.js" // @codekit-append "../scripts-angular/app-store.js" // @codekit-append "../scripts-angular/app-timer.js" // @codekit-append "../scripts-angular/app-config.js" // @codekit-append "../scripts-src/strings.js" // @codekit-append "../scripts-src/helpers.js" <file_sep>/* ********************************************** App-Compiled used by GoodDrinker and concatenated to home.min.js using CodeKit: Build Date: --BUILDDATE-- Build Version: --BUILDVERSION-- ********************************************** */ // @codekit-append "../scripts-src/jquery-1.7.2.min.js" // @codekit-append "../scripts-src/bootstrap.min.js" <file_sep>GDrinker.Services = angular.module('GDrinker.config', []); GDrinker.Services.factory('config', function() { var settings = localStorage.GDrinkerSettings; if (settings === undefined) { settings = { ConfigVersion: 1, TimeBetweenDrinks: 60, DrinkSize: 2, DrinkDescription: 'Drink', WarningForSoon: 0.95, FirstRun: true, AutoRefreshRate: 100, Language: 'en-us' }; localStorage.GDrinkerSettings = JSON.stringify(settings); } else { settings = JSON.parse(settings); } GDrinker.Languages.Init(settings.Language); return settings; }); <file_sep>var GDrinker = angular.module('GDrinker', ['GDrinker.config', 'GDrinker.services', 'GDrinker.lastDrinkTimer']); GDrinker.Version = "--BUILDVERSION--"; GDrinker.BuildDate = "--BUILDDATE--"; GDrinker.VersionCode = "--VERSIONCODE--"; GDrinker.run(function(drinks, config, lastDrinkTimer) { //console.log("GDrinker.run", drinks, config, lastDrinkTimer); }); GDrinker.AppController = function($scope, drinks) { $scope.drinks = drinks; }; GDrinker.DrinkList = function($scope, drinks) { $scope.predicate = "-time"; $scope.removeDrink = function(drink) { drinks.remove(drink.drink); }; }; GDrinker.HeaderController = function($scope, lastDrinkTimer) { $scope.status = lastDrinkTimer; $scope.$watch('status.lastDrink', function(newVal) { console.log("FIRED", newVal); lastDrinkTimer.update(); }); }; GDrinker.FooterController = function($scope, drinks, config) { $scope.fastAdd = function() { console.log("Fast Add"); var drink = {}; drink.time = Date.now(); drink.amount = config.DrinkSize; drink.description = config.DrinkDescription; drinks.add(drink); }; $scope.showAdd = function() { console.log("Show Add Drink"); GDrinker.AddDialogController.show(); }; $scope.showHistory = function() { console.log("Show History"); }; $scope.showSettings = function() { console.log("Show Settings"); }; }; GDrinker.AddDialogController = function($scope, drinks, config) { $scope.show = function() { }; }; <file_sep>/* ********************************************** App-Compiled used by GoodDrinker and concatenated to app-ios.min.js using CodeKit: Build Date: --BUILDDATE-- Build Version: --BUILDVERSION-- ********************************************** */ // @codekit-append "../scripts-src/cordova-2.1.0-ios.js" // @codekit-append "../scripts-src/jquery-1.7.2.min.js" // @codekit-append "../scripts-src/ember-0.9.8.1.min.js" // @codekit-append "../scripts-src/bootstrap.min.js" // @codekit-append "../scripts-src/lawnchair-0.6.1.min.js" // @codekit-append "../scripts-src/moment-1.7.0.min.js" // @codekit-append "../scripts-src/fastclick.js" // @codekit-append "../scripts-src/fastclick-ios.js" // @codekit-append "../scripts-src/app.js" // @codekit-append "../scripts-src/strings.js" // @codekit-append "../scripts-src/helpers.js" // @codekit-append "../scripts-src/analytics-ios.js" // @codekit-append "../scripts-src/visibility-pg.js" <file_sep>GoodDrinker =========== Keep tabs on how many drinks you've had and when you had your last drink<file_sep>/* analytics.js */ var cordova = cordova || {}; var GDrinker = GDrinker || {}; GDrinker.Analytics = {}; GDrinker.Analytics.init = function() { var id = "UA-9988000-21"; cordova.exec(GDrinker.Analytics.onSuccess, GDrinker.Analytics.onFailure, 'GoogleAnalyticsTracker', 'start', [id]); GDrinker.Analytics.trackPageView("/App/Android/"); GDrinker.Analytics.trackEvent("Version", GDrinker.Version); }; GDrinker.Analytics.trackEvent = function(category, action, label, value) { try { return cordova.exec(GDrinker.Analytics.onSuccess, GDrinker.Analytics.onFailure, 'GoogleAnalyticsTracker', 'trackEvent', [category, action, typeof label === "undefined" ? "" : label, (isNaN(parseInt(value,10))) ? 0 : parseInt(value, 10)]); } catch (ex) { //console.log(ex); } }; GDrinker.Analytics.trackPageView = function(url) { try { return cordova.exec(GDrinker.Analytics.onSuccess, GDrinker.Analytics.onFailure, 'GoogleAnalyticsTracker', 'trackPageView', [url]); } catch (ex) { //console.log(ex); } }; document.addEventListener("deviceready", function() { GDrinker.Analytics.init(); navigator.splashscreen.hide(); }, false); GDrinker.Analytics.onSuccess = function(result) { //console.log("Analytics onSuccess", result); }; GDrinker.Analytics.onFailure = function(result) { //console.log("Analytics onFailure", result); }; <file_sep> var GDrinker = GDrinker || {}; GDrinker.Strings = GDrinker.Strings || {}; GDrinker.Languages = {}; // drink more water GDrinker.Languages.default_strings = { "language": "en-us", "url": "--DEFAULT--", "language_name": "English", "language_version": 1, "default_drink_name": "Drink", "yes": "YES", "no": "NO", "soon": "SOON", "plenty_of_time": "a while", "time_since_last_drink": "It's been <b>{{time}}</b> since your last drink", "wait_until": "You should wait until at least <b>{{time}}</b>", "drink_now": "Be smart, <b>always</b> drink responsibily.", "hours": "hours", "one_hour": "1 hour", "slow_down_title": "Wow, slow down there!", "slow_down_msg": "You didn't leave enough time between your drinks. Be careful!", "switch_language_failed": { "header": "Error", "message": "Unable to get language pack." }, "action_buttons": { "fast_add": "Fast Add", "add": "Add", "history": "History", "settings": "Settings" }, "dialog_add": { "header": "Add a drink", "description": "Description", "amount": "Amount", "time": "Time", "date": "Date" }, "dialog_history": { "header": "History", "last24": "Last 24 hours", "last48": "Last 48 hours", "last72": "Last 72 hours", "lastW": "Last week", "lastM": "Last month", "allTime": "All time" }, "dialog_settings": { "header": "Settings", "time_between": "Time Between Drinks", "default_drink_size": "Default Drink Size", "default_description": "Default Description", "clear_all": "Clear All Data", "clear_all_button": "Erase", "clear_msg": "This will delete all of your settings and is unrecoverable, are you sure?", "clear_title": "Erase everying?", "about": "About", "about_button": "About", "short_time_title": "Slow down!", "short_time_msg": "Be smart, leave more time between drinks and drink in moderation." }, "dialog_about": { "header": "About", "body": "about body", "version": "Version", "build_date": "Build Date" }, "dialog_welcome": { "header": "Welcome", "body": "<p>Welcome to GoodDrinker! Please remember to always drink responsibly. This app is not meant to provide any medical or legal advice about how drunk you are, but instead only to keep track of how many drinks you've had and when your last drink was.</p><p>Please, be smart, <strong class='text-red'>never</strong> drink and drive. And if you're not old enough to drink, please close this app, you should <strong class='text-red'>not</strong> be drinking.</p><p>The developers of GoodDrinker are not liable for any good or bad decisions you make, or the outcome of those decisions. Enjoy responsibility!</p>", "button": "I Got It!" }, "close": "Close", "save": "Save" }; GDrinker.Languages.Init = function(lang) { try { var langPacks = localStorage.LanguagePacks; if (langPacks === undefined) { langPacks = {}; } else { langPacks = JSON.parse(langPacks); } langPacks["en-us"] = GDrinker.Languages.default_strings; if (langPacks[lang]) { if (langPacks[lang].language_version === 1) { GDrinker.Strings = langPacks[lang]; setTimeout(function() { GDrinker.Languages.UpdateUI(); }, 25); } else { GDrinker.Strings = langPacks["en-us"]; } } else { GDrinker.Strings = langPacks["en-us"]; } } catch (ex) { GDrinker.Strings = GDrinker.Languages.default_strings; } }; GDrinker.Languages.UpdateUI = function() { $("#strButFastAdd", "#footerBar").text(GDrinker.Strings.action_buttons.fast_add); $("#strButAdd","#footerBar").text(GDrinker.Strings.action_buttons.add); $("#strButHistory", "#footerBar").text(GDrinker.Strings.action_buttons.history); $("#strButSettings", "#footerBar").text(GDrinker.Strings.action_buttons.settings); $("#strDlgAddHeader", "#dlgAddDrink").text(GDrinker.Strings.dialog_add.header); $("#strDlgAddDesc", "#dlgAddDrink").text(GDrinker.Strings.dialog_add.description); $("#strDlgAddDate", "#dlgAddDrink").text(GDrinker.Strings.dialog_add.date); $("#strDlgAddTime", "#dlgAddDrink").text(GDrinker.Strings.dialog_add.time); $("#strDlgAddAmount", "#dlgAddDrink").text(GDrinker.Strings.dialog_add.amount); $("#strDlgSettingsHeader", "#dlgSettings").text(GDrinker.Strings.dialog_settings.header); $("#strDlgSettingsTimeBetween", "#dlgSettings").text(GDrinker.Strings.dialog_settings.time_between); $("#strDlgSettingsDrinkSize", "#dlgSettings").text(GDrinker.Strings.dialog_settings.default_drink_size); $("#strDlgSettingsDescription", "#dlgSettings").text(GDrinker.Strings.dialog_settings.default_description); $("#strDlgSettingsErase", "#dlgSettings").text(GDrinker.Strings.dialog_settings.clear_all); $("#strDlgSettingsButErase", "#dlgSettings").text(GDrinker.Strings.dialog_settings.clear_all_button); $("#strDlgSettingsAbout", "#dlgSettings").text(GDrinker.Strings.dialog_settings.about); $("#strDlgSettingsButAbout", "#dlgSettings").text(GDrinker.Strings.dialog_settings.about_button); $("#strDlgHistoryHeader", "#dlgHistory").text(GDrinker.Strings.dialog_history.header); $("#strDlgHistoryLast24", "#dlgHistory").text(GDrinker.Strings.dialog_history.last24); $("#strDlgHistoryLast48", "#dlgHistory").text(GDrinker.Strings.dialog_history.last48); $("#strDlgHistoryLast72", "#dlgHistory").text(GDrinker.Strings.dialog_history.last72); $("#strDlgHistoryLastW", "#dlgHistory").text(GDrinker.Strings.dialog_history.lastW); $("#strDlgHistoryLastM", "#dlgHistory").text(GDrinker.Strings.dialog_history.lastM); $("#strDlgHistoryAllTime", "#dlgHistory").text(GDrinker.Strings.dialog_history.allTime); $("#strDlgAboutHeader", "#dlgAbout").text(GDrinker.Strings.dialog_about.header); $("#strDlgAboutBody", "#dlgAbout").html(GDrinker.Strings.dialog_about.body); $("#strDlgAboutVersion", "#dlgAbout").text(GDrinker.Strings.dialog_about.version); $("#strDlgAboutBuild", "#dlgAbout").text(GDrinker.Strings.dialog_about.build_date); $("#strDlgFirstRunHeader", "#dlgFirstRun").text(GDrinker.Strings.dialog_welcome.header); $("#strDlgFirstRunBody", "#dlgFirstRun").html(GDrinker.Strings.dialog_welcome.body); $("#strDlgFirstRunButOK", "#dlgFirstRun").text(GDrinker.Strings.dialog_welcome.button); $(".strButClose").text(GDrinker.Strings.close); $(".strButSave").text(GDrinker.Strings.save); }; GDrinker.Languages.LoadLanguageResources = function(url) { var jqxhr = $.ajax({url: url, cache:false}) .done(function(result) { var langPacks = localStorage.LanguagePacks || {}; console.log(result.language); langPacks[result.language] = result; localStorage.LanguagePacks = JSON.stringify(langPacks); }) .fail(function(result) { GDrinker.Helpers.alert(GDrinker.Strings.switch_language_failed.message, GDrinker.Strings.switch_language_failed.header, function() {}); }); }; <file_sep>#!/bin/bash BUILDDATE=$(date) BUILDVERSION=`cat .version` VERSIONCODE=`cat .versioncode` BUILDTYPE="UNSET" APPENGINEVERSION=$VERSIONCODE-$(date +%y%m%d-%H%M) #IOSAPPID=0 IOSAPPSTORELINK="\<meta name=\'apple-itunes-app\' content=\'$IOSAPPID\'\/\>" IOSAPPSTORELINK="" echo GoodDrinker PhoneGap Builder echo - Build Date: $BUILDDATE echo - Build Version: $BUILDVERSION echo - Version Code: $VERSIONCODE echo - AppEngine Ver: $APPENGINEVERSION echo - iOSApp Store Link: $IOSAPPSTORELINK echo #WEB Version BUILDTYPE="WEB"--$APPENGINEVERSION DIR=../../PhoneGap/GoodDrinker/www MANIFESTFILE=$(date +%Y%m%d-%S).appcache echo Building $BUILDTYPE Version echo Path: $DIR echo -Cleaning old version rm -rf $DIR/* echo -Copying \& updating app.yaml cp app.yaml $DIR/ sed -e 's/xxversioncodexx/'"$APPENGINEVERSION"'/g' \ app.yaml > $DIR/app.yaml echo -Copying \& updating index.html sed -e 's/--BUILDTYPE--/'"$BUILDTYPE"'/g' \ -e 's/--BUILDDATE--/'"$BUILDDATE"'/g' \ -e 's/--VERSIONCODE--/'"$VERSIONCODE"'/g' \ -e 's/--BUILDVERSION--/'"$BUILDVERSION"'/g' \ -e 's/<!-- iOSAppStoreLink -->/'"$IOSAPPSTORELINK"'/g' \ index.html > $DIR/index.html echo -Copying \& updating drinkr.html sed -e 's/--BUILDTYPE--/'"$BUILDTYPE"'/g' \ -e 's/--BUILDDATE--/'"$BUILDDATE"'/g' \ -e 's/--VERSIONCODE--/'"$VERSIONCODE"'/g' \ -e 's/--BUILDVERSION--/'"$BUILDVERSION"'/g' \ -e 's/no-cache.appcache/'"$MANIFESTFILE"'/g' \ -e 's/<!-- iOSAppStoreLink -->/'"$IOSAPPSTORELINK"'/g' \ drinkr.html > $DIR/drinkr.html echo -Copying \& updating Manifest file \[$MANIFESTFILE\] sed -e 's/--BUILDTYPE--/'"$BUILDTYPE"'/g' \ -e 's/--BUILDDATE--/'"$BUILDDATE"'/g' \ -e 's/--VERSIONCODE--/'"$VERSIONCODE"'/g' \ -e 's/--BUILDVERSION--/'"$BUILDVERSION"'/g' \ manifest.appcache > $DIR/$MANIFESTFILE echo -Copying \& updating scripts mkdir $DIR/scripts sed -e 's/--BUILDTYPE--/'"$BUILDTYPE"'/g' \ -e 's/--BUILDDATE--/'"$BUILDDATE"'/g' \ -e 's/--VERSIONCODE--/'"$VERSIONCODE"'/g' \ -e 's/--BUILDVERSION--/'"$BUILDVERSION"'/g' \ scripts/app-web.min.js > $DIR/scripts/app-web.min.js sed -e 's/--BUILDTYPE--/'"$BUILDTYPE"'/g' \ -e 's/--BUILDDATE--/'"$BUILDDATE"'/g' \ -e 's/--VERSIONCODE--/'"$VERSIONCODE"'/g' \ -e 's/--BUILDVERSION--/'"$BUILDVERSION"'/g' \ scripts/home.min.js > $DIR/scripts/home.min.js echo -Copying language files mkdir $DIR/languages cp -R languages/* $DIR/languages echo -Copying styles mkdir $DIR/styles cp -R styles/* $DIR/styles/ echo -Copying images mkdir $DIR/img cp -R img/* $DIR/img/ echo -Copying website files cp 404.html $DIR/ cp main.py $DIR/ mkdir $DIR/web-assets cp -R web-assets/* $DIR/web-assets/ echo Completed. echo #Angular Version DIR=../../PhoneGap/GoodDrinker/Angular BUILDTYPE="ANGULAR" MANIFESTFILE=$(date +%Y%m%d-%S).appcache echo Building $BUILDTYPE Version echo Path: $DIR echo -Cleaning old version rm -rf $DIR/* echo -Copying \& updating app.yaml cp app.yaml $DIR/ sed -e 's/xxversioncodexx/'"$APPENGINEVERSION"'/g' \ app.yaml > $DIR/app.yaml echo -Copying \& updating index.html sed -e 's/--BUILDTYPE--/'"$BUILDTYPE"'/g' \ -e 's/--BUILDDATE--/'"$BUILDDATE"'/g' \ -e 's/--VERSIONCODE--/'"$VERSIONCODE"'/g' \ -e 's/--BUILDVERSION--/'"$BUILDVERSION"'/g' \ -e 's/<!-- iOSAppStoreLink -->/'"$IOSAPPSTORELINK"'/g' \ index.html > $DIR/index.html echo -Copying \& updating drinkr.html sed -e 's/--BUILDTYPE--/'"$BUILDTYPE"'/g' \ -e 's/--BUILDDATE--/'"$BUILDDATE"'/g' \ -e 's/--VERSIONCODE--/'"$VERSIONCODE"'/g' \ -e 's/--BUILDVERSION--/'"$BUILDVERSION"'/g' \ -e 's/no-cache.appcache/'"$MANIFESTFILE"'/g' \ -e 's/<!-- iOSAppStoreLink -->/'"$IOSAPPSTORELINK"'/g' \ angular.html > $DIR/drinkr.html echo -Copying \& updating Manifest file \[$MANIFESTFILE\] sed -e 's/--BUILDTYPE--/'"$BUILDTYPE"'/g' \ -e 's/--BUILDDATE--/'"$BUILDDATE"'/g' \ -e 's/--VERSIONCODE--/'"$VERSIONCODE"'/g' \ -e 's/--BUILDVERSION--/'"$BUILDVERSION"'/g' \ manifest.appcache > $DIR/$MANIFESTFILE echo -Copying \& updating scripts mkdir $DIR/scripts sed -e 's/--BUILDTYPE--/'"$BUILDTYPE"'/g' \ -e 's/--BUILDDATE--/'"$BUILDDATE"'/g' \ -e 's/--VERSIONCODE--/'"$VERSIONCODE"'/g' \ -e 's/--BUILDVERSION--/'"$BUILDVERSION"'/g' \ scripts-angular/app-angular.min.js > $DIR/scripts/app-angular.min.js sed -e 's/--BUILDTYPE--/'"$BUILDTYPE"'/g' \ -e 's/--BUILDDATE--/'"$BUILDDATE"'/g' \ -e 's/--VERSIONCODE--/'"$VERSIONCODE"'/g' \ -e 's/--BUILDVERSION--/'"$BUILDVERSION"'/g' \ scripts/home.min.js > $DIR/scripts/home.min.js echo -Copying language files mkdir $DIR/languages cp -R languages/* $DIR/languages echo -Copying styles mkdir $DIR/styles cp -R styles/* $DIR/styles/ echo -Copying images mkdir $DIR/img cp -R img/* $DIR/img/ echo -Copying website files cp 404.html $DIR/ cp main.py $DIR/ mkdir $DIR/web-assets cp -R web-assets/* $DIR/web-assets/ echo Completed. echo #iOS Version DIR=../../PhoneGap/GoodDrinker/iOS/www BUILDTYPE="iOS" echo Building $BUILDTYPE Version echo -Path: $DIR echo -Cleaning old version rm -rf $DIR/* echo -Copying \& updating drinkr.html sed -e 's/--BUILDTYPE--/'"$BUILDTYPE"'/g' \ -e 's/--BUILDDATE--/'"$BUILDDATE"'/g' \ -e 's/--VERSIONCODE--/'"$VERSIONCODE"'/g' \ -e 's/--BUILDVERSION--/'"$BUILDVERSION"'/g' \ -e 's/ manifest=\"no-cache.appcache\"//g' \ -e 's/app-web.min.js/app-ios.min.js/g' \ -e 's/<!-- iOSAppStoreLink -->//g' \ drinkr.html > $DIR/drinkr.html echo -Copying \& updating scripts mkdir $DIR/scripts sed -e 's/--BUILDTYPE--/'"$BUILDTYPE"'/g' \ -e 's/--BUILDDATE--/'"$BUILDDATE"'/g' \ -e 's/--VERSIONCODE--/'"$VERSIONCODE"'/g' \ -e 's/--BUILDVERSION--/'"$BUILDVERSION"'/g' \ scripts/app-ios.min.js > $DIR/scripts/app-ios.min.js echo -Copying styles mkdir $DIR/styles cp -R styles/* $DIR/styles/ echo -Copying images mkdir $DIR/img cp -R img/* $DIR/img/ echo -Updating GoodDrinker-info.plist LINE=`sed -n '/<key>CFBundleShortVersionString<\/key>/ =' $DIR/../GDrinker/GoodDrinker-info.plist` LINE=$[$LINE+1] sed -e ''"$LINE"' s/<string>.*<\/string>/<string>'"$BUILDVERSION"'<\/string>/g' $DIR/../GDrinker/GoodDrinker-Info.plist > $DIR/../GDrinker/GoodDrinker-info.tmp LINE=`sed -n '/<key>CFBundleVersion<\/key>/ =' $DIR/../GDrinker/GoodDrinker-info.tmp` LINE=$[$LINE+1] sed -e ''"$LINE"' s/<string>.*<\/string>/<string>'"$BUILDVERSION"'<\/string>/g' $DIR/../GDrinker/GoodDrinker-info.tmp > $DIR/../GDrinker/GoodDrinker-info.tmp2 rm $DIR/../GDrinker/GoodDrinker-info.tmp rm $DIR/../GDrinker/GoodDrinker-info.bak mv $DIR/../GDrinker/GoodDrinker-info.plist $DIR/../GDrinker/GoodDrinker-info.bak mv $DIR/../GDrinker/GoodDrinker-info.tmp2 $DIR/../GDrinker/GoodDrinker-info.plist echo Completed. echo #Android Version DIR=../../PhoneGap/GoodDrinker/Android/assets/www BUILDTYPE="ANDROID" echo Building $BUILDTYPE Version echo -Path: $DIR echo -Cleaning old version rm -rf $DIR/* echo -Copying \& updating drinkr.html sed -e 's/--BUILDTYPE--/'"$BUILDTYPE"'/g' \ -e 's/--BUILDDATE--/'"$BUILDDATE"'/g' \ -e 's/--VERSIONCODE--/'"$VERSIONCODE"'/g' \ -e 's/--BUILDVERSION--/'"$BUILDVERSION"'/g' \ -e 's/ manifest=\"no-cache.appcache\"//g' \ -e 's/app-web.min.js/app-android.min.js/g' \ -e 's/<!-- iOSAppStoreLink -->//g' \ drinkr.html > $DIR/drinkr.html echo -Copying \& updating scripts mkdir $DIR/scripts sed -e 's/--BUILDTYPE--/'"$BUILDTYPE"'/g' \ -e 's/--BUILDDATE--/'"$BUILDDATE"'/g' \ -e 's/--VERSIONCODE--/'"$VERSIONCODE"'/g' \ -e 's/--BUILDVERSION--/'"$BUILDVERSION"'/g' \ scripts/app-android.min.js > $DIR/scripts/app-android.min.js echo -Copying styles mkdir $DIR/styles cp -R styles/* $DIR/styles/ echo -Copying images mkdir $DIR/img cp -R img/* $DIR/img/ echo -Updating AndroidManifest.xml sed -e 's/android:versionName=\".*\"/android:versionName=\"'"$BUILDVERSION"'\"/g' \ -e 's/android:versionCode=\".*\"/android:versionCode=\"'"$VERSIONCODE"'\"/g' \ $DIR/../../AndroidManifest.xml > $DIR/../../AndroidManifest.tmp rm $DIR/../../AndroidManifest.bak mv $DIR/../../AndroidManifest.xml $DIR/../../AndroidManifest.bak mv $DIR/../../AndroidManifest.tmp $DIR/../../AndroidManifest.xml echo Completed. echo <file_sep>/* wrappers.js */ var GDrinker = GDrinker || {}; GDrinker.Helpers = {}; GDrinker.Helpers.PadTime = function(val) { if (val <= 9) { return "0" + val.toString(); } else { return val.toString(); } }; GDrinker.Helpers.confirm = function(msg, title, callback) { if (navigator.notification && navigator.notification.confirm) { navigator.notification.confirm(msg, callback, title, "Cancel,OK"); } else { setTimeout(function(){ var response = confirm(msg); if (response) { callback(2); } else { callback(1); } }, 0); } }; GDrinker.Helpers.alert = function(msg, title, callback) { if (navigator.notification && navigator.notification.confirm) { navigator.notification.alert(msg, callback, title, "OK"); } else { setTimeout(function() { var response = alert(msg); if (response) { callback(2); } else { callback(1); } }, 0); } }; GDrinker.Helpers.setErrorOnForm = function(elementId, isValid) { if (isValid) { $(elementId).parents(".control-group").removeClass("error"); $(elementId).parents(".ember-view .modal").find(".btn-primary").removeAttr("disabled"); } else { $(elementId).parents(".control-group").addClass("error"); $(elementId).parents(".ember-view .modal").find(".btn-primary").attr("disabled", "disabled"); } }; GDrinker.Helpers.ValidateNumberInput = function(elementId, setError) { var value = $(elementId).val(); var isValid = (value - 0) == value && value.length > 0; var min = $(elementId).attr("min") || ""; if (min.length > 0) { if (value < parseFloat(min)) { isValid = false; } } var max = $(elementId).attr("max") || ""; if (max.length > 0) { if (value > parseFloat(max)) { isValid = false; } } if (setError) { GDrinker.Helpers.setErrorOnForm(elementId, isValid); } return isValid; }; GDrinker.Helpers.ValidateDateInput = function(elementId, setError) { var value = $(elementId).val(); var isValid = value.length > 0; if (isValid && !moment(value, "YYYY-MM-DD").isValid()) { isValid = false; } if (setError) { GDrinker.Helpers.setErrorOnForm(elementId, isValid); } return isValid; }; GDrinker.Helpers.ValidateTimeInput = function(elementId, setError) { var value = $(elementId).val(); var isValid = value.length > 0; if (isValid && value === 0) { isValid = false; } if (isValid && !moment(value, "HH:mm").isValid()) { isValid = false; } if (setError) { GDrinker.Helpers.setErrorOnForm(elementId, isValid); } return isValid; }; GDrinker.Helpers.ValidateRequiredTextInput = function(elementId, setError) { var value = $(elementId).val(); var isValid = value.length > 0; if (setError) { GDrinker.Helpers.setErrorOnForm(elementId, isValid); } return isValid; }; <file_sep>var FastClick = FastClick || {}; document.addEventListener("deviceready", function() { var buttons = $(".btn"); buttons.each(function(i, item) { new FastClick(item); }); console.log("FastClick Registered (iOS) " + buttons.length.toString()); });
f8733b92587f5635a1b1f7472075008159d31fb3
[ "JavaScript", "Markdown", "Shell" ]
12
JavaScript
knandiwal/GoodDrinker-Archive
fcb4cc200f2702f3d9bec42ef5b9184bb2579bff
2a68d09b96464526562b772f5e99845e683c0fd8
refs/heads/master
<repo_name>armando555/InfoLab<file_sep>/app/Http/Controllers/ReportController.php <?php namespace App\Http\Controllers; use App\Models\Publication; use App\Models\Report; use App\Models\Data; use App\Models\TextData; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Storage; class ReportController extends Controller { public function index() { $reports = Report::get(); return view('/report/reports',compact('reports')); } public function createReport() { return view('/report/addReport'); } public function store(){ request()->validate([ 'titleReport' => 'required', 'author' => 'required', 'description' => 'required', ]); $userIds = Auth::user()->getAuthIdentifier(); Report::create([ 'title' => request('titleReport'), 'author' => request('author'), 'description' => request('description'), 'userId' => $userIds, ]); return redirect()->route('report.show'); } public function edit(Report $report){ $dataController = new DataController(); $numDatas = $dataController->getAllData(); $textData = TextData::get(); $groupData = []; foreach($numDatas as $data){ if ((in_array($data->numeralData, $groupData))){ }else{ array_push($groupData,$data->numeralData); } }//*/ return view('/report/editReport', ['report' => $report,'textData'=> $textData,'groupData' => $groupData],compact('numDatas')); } public function destroy(Report $report){ $report->delete(); return redirect()->route('report.show'); } public function update(Report $report){ $report->update([ 'title' => request('titleReport'), 'author' => request('author'), 'description' => request('description'), ]); return redirect()->route('report.edit',['report' => $report]); } public function saveText(){ $data = request('analiticData'); $numeral = request('numeralAnalitic'); echo $data; echo "<br>"; echo $numeral; TextData:: create([ 'analysisText' => $data, 'numeralData' => $numeral, 'reportId' => request('idReport'), ]);//*/ return redirect()->route('report.show'); } public function saveModalNumData(){ $dataController = new DataController(); $dataController->addData(); return redirect()->route('report.show'); } } <file_sep>/app/Http/Controllers/TextDataController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class TextDataController extends Controller { // } <file_sep>/app/Http/Controllers/MeanController.php <?php namespace App\Http\Controllers; use App\Models\Data; use Illuminate\Http\Request; class MeanController extends Controller implements IOperations { public function calculate(){ $group = request('groupData'); $numDatas = Data::where('numeralData', '=', $group)->get(); $count = Data::where('numeralData', '=', $group)->count(); $acu = 0; foreach($numDatas as $num){ $acu += $num->numData; } return $acu/$count; } } <file_sep>/app/Http/Controllers/IOperations.php <?php namespace App\Http\Controllers; use App\Models\Data; use Illuminate\Http\Request; interface IOperations { public function calculate(); } <file_sep>/app/Http/Controllers/OperationController.php <?php namespace App\Http\Controllers; use App\Models\Data; use Illuminate\Http\Request; class OperationController extends Controller { public function calculateOperation(){ $meanController = new MeanController(); $operation = request('calculus'); $result = 0; if ($operation == 'Promedio'){ $result = $meanController->calculate(); } if($operation == 'Moda'){ $result = 555; } if($operation == 'Mediana'){ $result = 1112; } return view('calculus.calculus',compact('result')); } } <file_sep>/app/Models/Report.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Report extends Model { use HasFactory; protected $fillable = [ 'title', 'description', 'author', 'userId', ]; public function user(){//$Report->report->title return $this->belongsTo(User::class);//Pertenece a un usuario } } <file_sep>/app/Http/Controllers/PublicationController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Publication; use Illuminate\Support\Facades\Storage; class PublicationController extends Controller { public function __construct(){ $this->middleware('auth'); } public function store(){ request()->validate([ 'titlePublication' => 'required', 'author' => 'required', 'detailsPublication' => 'required', 'imageUrl' => 'required|image' ]); $image = request()->file('imageUrl')->store('public/images'); $url = Storage:: url($image); Publication::create([ 'titlePublication' => request('titlePublication'), 'author' => request('author'), 'detailsPublication' => request('detailsPublication'), 'imageUrl' => $url, ]); $publicationes = Publication::get(); return view('/forum/forum',compact('publicationes')); } public function createPublication() { return view('/publication/addPublication'); } public function destroy(Publication $publication){ $publication->delete(); return redirect()->route('forum.show'); } public function edit(Publication $publication){ return view('/publication/editpublication', ['publication' => $publication]); } public function update(Publication $publication){ $image = request()->file('imageUrl')->store('public/images'); $url = Storage:: url($image); $publication->update([ 'titlePublication' => request('titlePublication'), 'author' => request('author'), 'detailsPublication' => request('detailsPublication'), 'imageUrl' => $url, ]); return ; } } <file_sep>/routes/web.php <?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('/home/welcome'); }); Auth::routes(); Route::get('home', [App\Http\Controllers\HomeController::class, 'index'])->name('home')->middleware('auth'); Route::get('forum/',[App\Http\Controllers\ForumController::class, 'index'])->name('forum.show')->middleware('auth'); Route::get('report/',[App\Http\Controllers\ReportController::class, 'index'])->name('report.show')->middleware('auth'); Route::delete('forum/{publication}', [App\Http\Controllers\PublicationController::class, 'destroy'])->where('publication','[0-9]+')->name('publication.destroy'); Route::get('forum/{publication}/editar', [App\Http\Controllers\PublicationController::class, 'edit'])->where('publication','[0-9]+')->name('publication.edit')->middleware('auth'); Route::patch('forum/{publication}', [App\Http\Controllers\PublicationController::class, 'update'])->where('publication','[0-9]+')->name('publication.update'); Route::get('report/{report}/editar', [App\Http\Controllers\ReportController::class, 'edit'])->where('report','[0-9]+')->name('report.edit')->middleware('auth'); Route::patch('report/{report}', [App\Http\Controllers\ReportController::class, 'update'])->where('report','[0-9]+')->name('report.update'); Route::post('report/{report}', [App\Http\Controllers\ReportController::class, 'edit'])->where('report','[0-9]+')->name('report.modal.edit')->middleware('auth'); Route::delete('report/{report}', [App\Http\Controllers\ReportController::class, 'destroy'])->where('report','[0-9]+')->name('report.destroy'); Route::get('forum/addPublication',[App\Http\Controllers\PublicationController::class, 'createPublication'])->name('publication.add')->middleware('auth'); Route::post('forum/addPublication',[App\Http\Controllers\PublicationController::class, 'store'])->name('publication.store'); Route::get('report/addReport',[App\Http\Controllers\ReportController::class, 'createReport'])->name('report.add')->middleware('auth'); Route::post('report/addReport',[App\Http\Controllers\ReportController::class, 'store'])->name('report.store'); Route::post('report/saveData',[App\Http\Controllers\ReportController::class, 'saveModalNumData'])->name('report.modal.add'); Route::post('report/text',[App\Http\Controllers\ReportController::class, 'saveText'])->name('report.data.add'); Route::post('report/mean',[App\Http\Controllers\OperationController::class, 'calculateOperation'])->name('report.operation.select'); <file_sep>/app/Http/Controllers/DataController.php <?php namespace App\Http\Controllers; use App\Models\Data; use Illuminate\Http\Request; class DataController extends Controller implements IDAODataModel { public function addData() { $datos = request('dataGroup'); $cont = 1; $datos1= explode(',',$datos); $numeral = request('numeralDataGroup'); echo "numeral: ".$numeral; echo "<br>"; foreach ($datos1 as $dato){ $dato = $dato + 0.0; echo "Dato ".$cont.": ".$dato."<br>"; $cont ++ ; Data:: create([ 'numData' => $dato, 'numeralData' => $numeral, 'reportId' => request('idReport'), ]); } return redirect()->route('report.show'); } public function getAllData() { $numDatas = Data::get(); return $numDatas; } } <file_sep>/app/Http/Controllers/ForumController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Publication; class ForumController extends Controller { public function __construct(){ $this->middleware('auth'); } public function index() { $publicationes = Publication::get(); return view('/forum/forum',compact('publicationes')); } } <file_sep>/database/migrations/2020_11_16_192123_create_text_data_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateTextDataTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('text_data', function (Blueprint $table) { $table->id(); $table->text('analysisText')->nullable(); $table->integer('numeralData'); $table->integer('reportId')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('text_data'); } } <file_sep>/app/Http/Controllers/IDAODataModel.php <?php namespace App\Http\Controllers; interface IDAODataModel { public function addData(); public function getAllData(); }
795e7837b720a3512a5d32d61c5b04be0deb1f06
[ "PHP" ]
12
PHP
armando555/InfoLab
f2ee37056654614b89c5fed73168eb2254fa45ec
f3bd5345f866ef69c2c7a8aefb00eeb564c2144d
refs/heads/main
<file_sep>from aiogram import Bot, Dispatcher, types, executor import keyboards as nav from aiogram.dispatcher.filters import Command from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters.state import StatesGroup, State Token = '<KEY>' storage = MemoryStorage() bot = Bot(token=Token) dp = Dispatcher(bot, storage=storage) class Admin(StatesGroup): login = State() password = State() markups = State() @dp.message_handler(commands=['start']) async def process_start_command(message: types.Message): await bot.send_message(message.from_user.id, 'Приветствуем Вас, Верешок!', reply_markup=nav.kb_Main) @dp.message_handler(Command('test'), state=None) async def process_input(message: types.Message): print('Ждем логин') await message.answer('Введите логин') print('1') await Admin.login.set() print('2') @dp.message_handler(state=Admin.login) #Принимаем ответ на логин async def answer_login(message: types.Message, state: FSMContext): print('Записали логин') login = message.text if login == '111': print('Ввели правильный логин') await state.update_data({'answer1': login}) await message.answer('Введите пароль') await Admin.password.set() else: print('Ошибка логина') await message.answer('Пользователя с таким логином не существует', reply_markup=nav.kb_Main) await state.finish() @dp.message_handler(state=Admin.password) # Принимаем ответ на пароль async def answer_password(message: types.Message, state: FSMContext): password = message.text if password == '222': print('УРА') await state.update_data({'answer2': password}) await message.answer('Верешок зашел в чат', reply_markup=nav.kb_admin) await Admin.markups.set() else: print('Ошибка пароля') await message.answer('Не верный пароль', reply_markup=nav.kb_Main) await state.finish() @dp.message_handler(state=Admin.markups) # Принимаем ответ на кнопки async def answer_markups(message: types.Message, state: FSMContext): if message.text == 'Главное меню': await message.answer('Главное меню', reply_markup=nav.kb_Main) await state.finish() elif message.text == 'Доставки': await message.answer('Доставки на сегодня: ', reply_markup=nav.kb_admin) elif message.text == 'Ресторан': await message.answer('Заказы на сегодня: ', reply_markup=nav.kb_admin) elif message.text == 'Прибыль': await message.answer('Прибыль составляет: ', reply_markup=nav.kb_admin) elif message.text == 'Отчет': await message.answer('Отчет за сегодня: ', reply_markup=nav.kb_admin) else: await bot.send_message(message.from_user.id, 'Я Вас не понимать', reply_markup=nav.kb_Main) await state.finish() @dp.message_handler() async def process_start_command(message: types.Message): if message.text == '<NAME>': await bot.send_message(message.from_user.id, 'Меню клиента', reply_markup=nav.kb_client) elif message.text == 'На месте': await bot.send_message(message.from_user.id, 'Что Вам принести?', reply_markup=nav.kb_nameste) elif message.text == 'Официант': await bot.send_message(message.from_user.id, 'Официант подойдет в ближайшее время ') elif message.text == 'Меню': await bot.send_message(message.from_user.id, 'Выберете блюдо') elif message.text == 'Счет': await bot.send_message(message.from_user.id, 'Счет') elif message.text == 'С собой': await bot.send_message(message.from_user.id, 'Выберите блюдо из меню', reply_markup=nav.kb_ssoboy) elif message.text == '*Меню': await bot.send_message(message.from_user.id, 'Выберете блюдо') elif message.text == 'Доставка': await bot.send_message(message.from_user.id, 'Доставляем все втечение часа!', reply_markup= nav.kb_dostavka) elif message.text == '*Меню*': await bot.send_message(message.from_user.id, 'Выберете блюдо') elif message.text == 'Посмотреть заказ': await bot.send_message(message.from_user.id, 'Ваш заказ: ') elif message.text == 'Меню админа': await bot.send_message(message.from_user.id, 'Чтобы зайти в меню администратора, нажмите /test', reply_markup=nav.kb_test) elif message.text == 'Главное меню': await bot.send_message(message.from_user.id, 'Главное меню', reply_markup=nav.kb_Main) else: await bot.send_message(message.from_user.id, 'Я Вас не понимать', reply_markup=nav.kb_Main) if __name__ == "__main__": executor.start_polling(dp, skip_updates=True) <file_sep>from aiogram.types import KeyboardButton, ReplyKeyboardMarkup btnMain = KeyboardButton('Главное меню') #Кнопки главного меню b2 = KeyboardButton('Меню Администратора') b1 = KeyboardButton('/test') b3 = KeyboardButton('Меню Клиента') kb_Main = ReplyKeyboardMarkup(resize_keyboard=True).row(b2, b3) kb_test = ReplyKeyboardMarkup(resize_keyboard=True).add(b1).add(btnMain) #Кнопки меню клиента b4 = KeyboardButton('На месте') b5 = KeyboardButton('С собой') b6 = KeyboardButton('Доставка') kb_client = ReplyKeyboardMarkup(resize_keyboard=True).row(b4, b5, b6).add(btnMain) #Кнопки меню На месте b7 = KeyboardButton('Официант') b8 = KeyboardButton('Меню') b9 = KeyboardButton('Счет') kb_nameste = ReplyKeyboardMarkup(resize_keyboard=True).row(b7, b8, b9).add(btnMain) #Кнопки меню С собой b10 = KeyboardButton('*Меню') kb_ssoboy = ReplyKeyboardMarkup(resize_keyboard=True).row(b10).add(btnMain) #Кнопки меню Доставка b11 = KeyboardButton('*Меню*') b12 = KeyboardButton('Посмотреть заказ') kb_dostavka = ReplyKeyboardMarkup(resize_keyboard=True).row(b11, b12).add(btnMain) #Кнопки меню админа b13 = KeyboardButton('Доставки') b14 = KeyboardButton('Ресторан') b15 = KeyboardButton('Прибыль') b16 = KeyboardButton('Отчет') kb_admin = ReplyKeyboardMarkup(resize_keyboard=True).row(b13, b14, b15, b16).add(btnMain)
0c35943e901de0d79d252c9293ea157156097fc4
[ "Python" ]
2
Python
Anna-Veresk/RestaurantBot1
6dce68f33bd11dbe8a08b04eb64c3f26c3333f3d
4e714d69db78cb8cac16e1d891ea114d42628715
refs/heads/master
<repo_name>MaxIvaniuk/testTask<file_sep>/js/main.js "use strict"; const numReg = /^(\s*)?(\+)?([- _():=+]?\d[- _():=+]?){10,14}(\s*)?$/, mailReg = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/, nameReg = /^[а-яА-ЯёЁa-zA-Z]+$/, messgReg = /^[а-яА-ЯёЁa-zA-Z0-9]+$/, form = document.getElementById('contactForm'), alertMsg = document.querySelector('.alert'), temp = document.querySelector('.weather_temp'), conditions = document.querySelector('.weather_conditions'); let userName = document.querySelector('#formName'), userPhone = document.querySelector('#formPhone'), userEmail = document.querySelector('#formMail'), userMessg = document.querySelector('#formMesage'), submitBtn = document.querySelector('#submitButton'), inputs = document.querySelector('.contact_form__input'); // Validation userName.addEventListener('blur', (e) => { e.preventDefault(); validate(nameReg, userName.value, userName); }) userPhone.addEventListener('blur', (e) => { e.preventDefault(); validate(numReg, userPhone.value, userPhone); }) userEmail.addEventListener('blur', (e) => { e.preventDefault(); validate(mailReg, userEmail.value, userEmail); }) userMessg.addEventListener('blur', (e) => { e.preventDefault(); validate(messgReg, userMessg.value, userMessg); }) function validate(regex, input, target) { if(regex.test(input)) { target.classList.remove('is-invalid'); target.classList.add('is-valid'); } else { target.classList.remove('is-valid'); target.classList.add('is-invalid'); validateErr(); } } function validateErr() { alertMsg.classList.remove('d-none'); setTimeout(() => { alertMsg.classList.add('d-none'); },3500); } // Form send let url = 'https://app.form2chat.io/f/2f2f414'; function postData() { fetch(url, {method: 'POST'}).then(response => { if (!response.ok){ throw new Error('Network response was not ok.'); } else { setTimeout(function(){ form.reset(); },3500); } }).catch((err) => { console.log(err); }); } //weather forecast let weatherUrl = 'http://api.openweathermap.org/data/2.5/weather?lat=49.553516&lon=25.594767&units=metric&lang=ua&appid=2a99b17f27fec118e2c633e3b869fab7' fetch(weatherUrl) .then(response => response.json()) .then(function(data){ console.log(data); temp.innerHTML = `+${Math.round(data.main.temp)}`; conditions.innerHTML = data.weather[0].description; }) .catch(() => { console.log('error') }) // init animation new WOW( { boxClass: 'wow', animateClass: 'animated', offset: 1, mobile: true, live: true } ).init();
4e6cdad4503bf5db254e3e7ca8a83e1e5aefbc39
[ "JavaScript" ]
1
JavaScript
MaxIvaniuk/testTask
5170ba9f78179f35340350cef75839b2520b0aeb
a6b46a1ef1cb341d452f50dce58c7615b3137267
refs/heads/master
<file_sep>using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using One_to_many_migration.DAL; using One_to_many_migration.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FiorelloHomeWork.Areas.AdminPanel.Controllers { [Area("AdminPanel")] public class CategoryController : Controller { public AppDbContext _context { get;} public CategoryController(AppDbContext context) { _context = context; } public IActionResult Index() { return View(_context.Categories.Where(c=>c.IsDeleted==false)); } public IActionResult Create() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Create(Category category) { if (!ModelState.IsValid) return View(); bool hascategory = _context.Categories.Any(c => c.Name.ToLower() == category.Name.ToLower()); if (hascategory) { ModelState.AddModelError("Name", "Bele kateqoriya var"); return View(); } _context.Categories.Add(category); _context.SaveChanges(); return RedirectToAction(nameof(Index)); } public IActionResult Update(int? id) { if (id == null) return NotFound(); var category = _context.Categories.FirstOrDefault(c => c.Id == id&&c.IsDeleted==false); if (category == null) return NotFound(); return View(category); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Update(int? id,Category category) { if (id == null) return NotFound(); if (id != category.Id) return BadRequest(); var categoryDb = _context.Categories.FirstOrDefault(c => c.Id == id && c.IsDeleted == false); if (category == null) return NotFound(); bool hascategory = _context.Categories.Any(c => c.Name.ToLower() == category.Name.ToLower()); if (hascategory) { ModelState.AddModelError("Name", "Bele kateqoriya var"); return View(categoryDb); } categoryDb.Name = category.Name; _context.SaveChanges(); return RedirectToAction(nameof(Index)); } public async Task<IActionResult> Delete(int? id) { if (id == null) return NotFound(); var category = await _context.Categories.FindAsync(id); if (category == null) return NotFound(); return View(category); } [HttpPost] [ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeletePost(int? id) { if (id == null) return NotFound(); var category = await _context.Categories.FindAsync(id); if (category == null) return NotFound(); if (category.IsDeleted) { category.IsDeleted = false; } else { category.IsDeleted = true; } await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } } } <file_sep>using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.EntityFrameworkCore; using One_to_many_migration.DAL; using One_to_many_migration.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace FiorelloHomeWork.Areas.AdminPanel.Controllers { [Area("AdminPanel")] public class SlidesController : Controller { public AppDbContext _context { get;} public IWebHostEnvironment _env { get;} public SlidesController(AppDbContext context, IWebHostEnvironment env) { _context = context; _env = env; } public IActionResult Index() { return View( _context.Slides); } public IActionResult Create() { return View(); } [HttpPost] public async Task<IActionResult> Create(Slide slide) { if (ModelState["Photos"].ValidationState==ModelValidationState.Invalid) { return View(); } foreach (var photo in slide.Photos) { if (!photo.ContentType.Contains("image/")) { ModelState.AddModelError("Photo", "sekil lazimdi basqa sey yukleme"); return View(); } if (photo.Length / 1024 > 300) { ModelState.AddModelError("Photo", "sekil cox yer tutur 300kb-i kecme narmalni"); return View(); } string filename = Guid.NewGuid().ToString() + photo.FileName; string pathname = Path.Combine(_env.WebRootPath, "img", filename); using (FileStream fileStream = new FileStream(pathname, FileMode.Create)) { await photo.CopyToAsync(fileStream); } Slide newSlide = new Slide { Image = filename }; _context.Add(newSlide); await _context.SaveChangesAsync(); } return RedirectToAction(nameof(Index)); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Delete(int? id) { if (id == null) { return NotFound(); } var slides = _context.Slides.FirstOrDefault(s => s.Id == id); if (slides == null) { return BadRequest(); } else if (id != slides.Id) { return BadRequest(); } string PathName = Path.Combine(_env.WebRootPath, "img", slides.Image); FileInfo file = new FileInfo(PathName); file.Delete(); _context.Slides.Remove(slides); _context.SaveChanges(); return RedirectToAction(nameof(Index)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FiorelloHomeWork.Models { public class HeaderLogo { public int Id { get; set; } public string LogoImage { get; set; } } } <file_sep>using Microsoft.EntityFrameworkCore.Migrations; namespace One_to_many_migration.Migrations { public partial class CreateFlowerTitleTable : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Title", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), HeaderTitle = table.Column<string>(nullable: true), SmallTitle = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Title", x => x.Id); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Experts", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Fullname = table.Column<string>(type: "nvarchar(max)", nullable: true), Image = table.Column<string>(type: "nvarchar(max)", nullable: true), Position = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Experts", x => x.Id); }); migrationBuilder.CreateTable( name: "ExpertTitle", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), HeaderTitle = table.Column<string>(type: "nvarchar(max)", nullable: true), SmallTitle = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_ExpertTitle", x => x.Id); }); } } } <file_sep>using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using One_to_many_migration.DAL; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FiorelloHomeWork.ViewComponents { public class ProductViewComponent: ViewComponent { public AppDbContext _context { get; } public ProductViewComponent(AppDbContext context) { _context = context; } public async Task<IViewComponentResult> InvokeAsync(int take) { var model = await _context.Products.Include(p => p.ProductImages).Where(p => p.IsDeleted == false). OrderByDescending(p => p.Id).Take(take).ToListAsync(); return View(await Task.FromResult(model)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FiorelloHomeWork.Models { public class FooterSocialMedia { public int Id { get; set; } public string SocialMedia { get; set; } } } <file_sep>using FiorelloHomeWork.Models; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using One_to_many_migration.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace One_to_many_migration.DAL { public class AppDbContext : IdentityDbContext<AppUser> { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } public DbSet<Slide> Slides { get; set; } public DbSet<Introduction> Introduction { get; set; } public DbSet<Product> Products { get; set; } public DbSet<Category> Categories { get; set; } public DbSet<ProductImage> ProductImages { get; set; } public DbSet<FlowerTitle> Title { get; set; } public DbSet<Expert> Experts { get; set; } public DbSet<HeaderLogo> Logo { get; set; } public DbSet<FooterSocialMedia> SocialMedias { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FiorelloHomeWork.Models { public class FlowerTitle { public int Id { get; set; } public string HeaderTitle { get; set; } public string SmallTitle { get; set; } } } <file_sep>using Microsoft.AspNetCore.Mvc; using One_to_many_migration.DAL; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FiorelloHomeWork.ViewComponents { public class FooterSocialMediaViewComponent:ViewComponent { public AppDbContext _context { get; } public FooterSocialMediaViewComponent(AppDbContext context) { _context = context; } public async Task<IViewComponentResult> InvokeAsync() { var model = _context.SocialMedias; return View(await Task.FromResult(model)); } } } <file_sep>using FiorelloHomeWork.ViewModels; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using One_to_many_migration.DAL; using One_to_many_migration.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FiorelloHomeWork.ViewComponents { public class HeaderViewComponent: ViewComponent { public AppDbContext _context { get; } public HeaderViewComponent(AppDbContext context) { _context = context; } public async Task<IViewComponentResult> InvokeAsync() { string basket = HttpContext.Request.Cookies["basket"]; BasketViewModel basketViewModel = new BasketViewModel { basketItemViewModels = new List<BasketItemViewModel>(), TotalPrice = 0, Count=0 }; if (basket!=null) { List<CookieItemViewModel> cookieItemViewModels = JsonConvert.DeserializeObject<List<CookieItemViewModel>>(basket); foreach (var cookie in cookieItemViewModels) { Product product = _context.Products.FirstOrDefault(p => p.Id == cookie.Id); if (product != null) { BasketItemViewModel basketItemViewModel = new BasketItemViewModel { Product = product, Count = cookie.Count }; basketViewModel.basketItemViewModels.Add(basketItemViewModel); basketViewModel.TotalPrice += (decimal)(cookie.Count + product.Price); basketViewModel.Count++; } } } return View(await Task.FromResult(basketViewModel)); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace FiorelloHomeWork.ViewModels { public class LoginViewModel { [Required, StringLength(maximumLength: 100)] public string Username { get; set; } [Required, DataType(DataType.EmailAddress)] public string Password { get; set; } } } <file_sep> using FiorelloHomeWork.ViewModels; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using One_to_many_migration.DAL; using One_to_many_migration.Models; using One_to_many_migration.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; using System.Threading.Tasks; namespace One_to_many_migration.Controllers { public class HomeController : Controller { public AppDbContext _context { get; } public HomeController(AppDbContext context) { _context = context; } public async Task<IActionResult> Index() { HomeViewModel homeviewmodel = new HomeViewModel { Slides = await _context.Slides.ToListAsync(), Introduction = await _context.Introduction.FirstOrDefaultAsync(), Categories = await _context.Categories.Where(c => c.IsDeleted == false).ToListAsync(), Title =await _context.Title.FirstOrDefaultAsync(), Experts=await _context.Experts.ToListAsync(), }; //HttpContext.Session.SetString("name", "ismet"); //List<ProductBasket> baskets = new List<ProductBasket> //{ // new ProductBasket{Id=1,Count=3}, // new ProductBasket{Id=2,Count=2}, // new ProductBasket{Id=3,Count=5}, // new ProductBasket{Id=4,Count=3} //}; //Response.Cookies.Append("basket",JsonSerializer.Serialize(baskets)); return View(homeviewmodel); } public IActionResult AddBasket(int id) { Product product = _context.Products.FirstOrDefault(p => p.Id == id); if (product == null) return NotFound(); string basket = HttpContext.Request.Cookies["basket"]; if (basket==null) { List<CookieItemViewModel> products = new List<CookieItemViewModel>(); products.Add(new CookieItemViewModel { Id=product.Id, Count=1 }); string basketstr = JsonConvert.SerializeObject(products); HttpContext.Response.Cookies.Append("basket", basketstr); } else { List<CookieItemViewModel> products = JsonConvert.DeserializeObject<List<CookieItemViewModel>>(basket); CookieItemViewModel cookieItem = products.FirstOrDefault(p => p.Id == product.Id); if (cookieItem==null) { products.Add(new CookieItemViewModel { Id = product.Id, Count = 1 }); } else { cookieItem.Count++; } string basketstr = JsonConvert.SerializeObject(products); HttpContext.Response.Cookies.Append("basket", basketstr); } return RedirectToAction("Index", "Home"); } public IActionResult ShowBasket() { return Content(HttpContext.Request.Cookies["basket"]); } public IActionResult DeleteCookies(int id) { string basket = HttpContext.Request.Cookies["basket"]; List<CookieItemViewModel> products = JsonConvert.DeserializeObject<List<CookieItemViewModel>>(basket); foreach (var item in products) { if (item.Id==id) { products.Remove(item); break; } } string basketstr = JsonConvert.SerializeObject(products); HttpContext.Response.Cookies.Append("basket", basketstr); return RedirectToAction("Index","Home"); } } } <file_sep>using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace One_to_many_migration.Models { public class Slide { public int Id { get; set; } [Required, StringLength(255)] public string Image { get; set; } [NotMapped,Required] public List<IFormFile> Photos { get; set; } } } <file_sep>using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using One_to_many_migration.DAL; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FiorelloHomeWork.Controllers { public class ProductController : Controller { public AppDbContext _context { get; } public ProductController(AppDbContext context) { _context = context; } public async Task<IActionResult> Index() { ViewBag.ProductCount = _context.Products.Where(p => p.IsDeleted == false).Count(); return View(); } public async Task<IActionResult> ReadMore(int take=8 ,int skip=12) { var model = await _context.Products.Include(p => p.ProductImages).Where(p => p.IsDeleted == false) .OrderByDescending(p=>p.Id).Skip(skip).Take(take).ToListAsync(); return PartialView("_productPartial", model); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace One_to_many_migration.Models { public class Introduction { public int Id { get; set; } public string HeaderTitle { get; set; } public string SmallTitle { get; set; } [Required, StringLength(255)] public string Image { get; set; } } }
86614607c3ae99986bdb44c2f124a6191aba1bcd
[ "C#" ]
15
C#
Ismat227/FiorelloReadMoreButton
3302f1d82ab1066d926114a69e0c0a47d7b48ff5
47229f18e4a3c9498507ce1fc0af0e089ffbd078
refs/heads/master
<file_sep>export class Warning { construcutor( id: number, people: boolean, light: boolean, secure: boolean, comments: string, long: number, lat: number, ){} } <file_sep>import { Component, AfterViewInit, OnInit } from '@angular/core'; import { FormBuilder, FormControl } from '@angular/forms'; import { Warning } from './warning'; import Geolocation from 'ol/Geolocation'; import Projection from 'ol/proj/Projection'; import Proj from 'ol/proj.js'; import 'ol/ol.css'; import Map from 'ol/Map'; import OlXYZ from 'ol/source/XYZ'; import OlTileLayer from 'ol/layer/Tile'; import OlView from 'ol/View'; import OSM from 'ol/source/OSM'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements AfterViewInit, OnInit { title = 'Light Way'; public map: Map; public source: OlXYZ; public layer: OlTileLayer; public view: OlView; public geo: Geolocation; public projection: Projection; public proj: Proj; public osm: OSM; public display_toast : boolean = false; public autohide = true; public form; public destination; latitude: number = 45.188529; longitude: number = 5.724524; constructor(private formBuilder: FormBuilder) { this.form = this.formBuilder.group({ peopleSwitch: '', lightSwitch: '', securePlaceSwitch: '', messageText: '', long: '', lat: '' }); } ngOnInit() { this.source = new OlXYZ({ url: 'https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png' }); this.layer = new OlTileLayer({ source: this.source }); this.view = new OlView({ projection: 'EPSG:4326', center: [6.661594, 50.433237], zoom: 15 }); this.map = new Map({ target: 'map', layers: [this.layer], view: this.view }); this.geo = new Geolocation({ trackingOptions: { enableHighAccuracy: true }, projection: this.view.getProjection() }) } ngAfterViewInit() { this.map.setTarget('map'); this.geo.setTracking(true); this.setCenter(this.longitude, this.latitude); } getPosition() { console.log(this.geo.getPosition()); this.setCenter(this.geo.getPosition()[0], this.geo.getPosition()[1]); } setCenter(long, lat) { var view = this.map.getView(); view.setCenter([long, lat]); view.setZoom(25); } onSubmit(Datas) { // Process checkout data here console.warn('Your order has been submitted', Datas); this.form.reset(); } }
d0b6da1fd339974d28287fa1d73c0f20d84fd47e
[ "TypeScript" ]
2
TypeScript
Scoppeniche/lightmyway
77ff5826ef8adc40ac057c34aa4e56c87d72274f
b6f69b54ea665ff0078f3c665c3bba13bf12ca8b
refs/heads/master
<repo_name>danielvportlandia/ruby-course-udemy<file_sep>/ruby_projects/playground.rb # frozen_string_literal: true # # PART 1 # # greeting = "Hello world" # def say_hello(name) # puts "Hello " + name # end # say_hello "Dan" # String concatenation # single or double quotes allowed # puts first_name + " " + last_name # String interpolation # Doesn't work with single quotes # puts "My first name is #{first_name} and my last name is #{last_name}" # CONSTANTS # FIRST_NAME = 'Dan' # LAST_NAME = 'Shelton' # def get_full_name(first_name, last_name) # "#{first_name} #{last_name}" # end # def say_hello(full_name) # vacation_location = "#{full_name} wants to go to Cuba" # # sub or gsub, gsub is global and replaces all occurances # puts vacation_location.sub('Cuba', 'Bermuda') # end # say_hello get_full_name(FIRST_NAME, LAST_NAME) # # PART 2 # # puts 'What is your first name?' # first_name = gets.chomp # puts "Your first name is #{first_name}" # puts 'Pick a number to multiply by 2' # input = gets.chomp # gets chomp always returns a string # puts "Your value is #{input.to_i * 2}" # Numbers # When dividing integers, make sure one is designated as a float to get a # correct answer. .to_f or 10.0 works # .eql? compares types, not value # elsif for else if statements # if statements also end with "end" # Arrays # arrays begin at 0 # .last returns last value in array # double dots creates a range # .to_a to array # .shuffle, randomizes array indeces # << shovel operator: pushes value onto array # .append # .prepend # .pop and .push, .pop still returns last item # .unshift() adds element to the beginning of an array # .uniq! removes duplicate values # .include() checks if value exists in an array # z = _ : underscore means the last expression used in the terminal # .select, basically .filter # .each is preferred loop # Hashes # test_hash = { a: 1, b: 2, c: 3 } # puts test_hash[:a] # .is_a?(type) # LINTING # question marks # methods that return a boolean should be indicated with a trailing ? # prefix with _ helps identify unused variables for RuboCop # for loops don't introduce a new scope, still use .each instead though # RAILS # COMMANDS # rails routes<file_sep>/ruby_projects/area_codes.rb # frozen_string_literal: true @dial_book = { 'newyork' => '212', 'newbrunswick' => '732', 'edison' => '908', 'plainsboro' => '609', 'sanfrancisco' => '301', 'miami' => '305', 'paloalto' => '650', 'evanston' => '847', 'orlando' => '407', 'lancaster' => '717' } # Get city names from the hash def get_city_names(somehash) somehash.keys.each { |city| puts city.to_s } end # Get area code based on given hash and key def get_area_code(somehash, key) if somehash[key] puts "#area code: #{somehash[key]}" return end puts 'City not found! Please try again.' false end def area_codes puts 'Would you like to retrieve some area codes (Y/N)?' input = gets.chomp.downcase puts loop do input != 'y' && break get_city_names(@dial_book) puts puts 'Press n anytime to quit' print 'Please select a city: ' selected_city = gets.chomp.downcase selected_city == 'n' && break puts "selected_city: #{selected_city}" get_area_code(@dial_book, selected_city) puts end end # Execution flow area_codes <file_sep>/ruby_projects/authenticator.rb # frozen_string_literal: true @users = [ { name: 'jon', password: '<PASSWORD>' }, { name: 'arya', password: '<PASSWORD>' }, { name: 'jaimie', password: '<PASSWORD>' }, { name: 'robert', password: '<PASSWORD>' } ] @attempts = 3 def validate(name, password) @users.each do |item| (item[:name] == name && item[:password] == password) && (return item) end false end def authenticator if @attempts <= 0 puts 75.times { print '-' } puts puts 'Failed to authenticate user no more attempts left' 75.times { print '-' } puts return end inputs = user_inputs credentials = validate(inputs[0], inputs[1]) if credentials puts 75.times { print '-' } puts puts 'You have successfully logged in' puts credentials.to_s 75.times { print '-' } puts else @attempts -= 1 @attempts >= 2 && (puts "#{@attempts} attempts left, try again.") @attempts == 1 && (puts "#{@attempts} attempt left, try again.") authenticator end end def user_inputs print 'User name: ' name = gets.chomp.downcase print 'Password: ' password = gets.chomp [name, password] end =begin ask method, inputs name and password tracks attempts then calls validate() if !attempts return failure message if validate = true then return index value else try again message and call ask method again minus an attempt =end puts 'Welcome to the authenticator!' puts puts 'Press n to quit or any other key to continue' continue_input = gets.chomp.downcase authenticator unless continue_input == 'n' <file_sep>/ruby_projects/analyzer.rb # frozen_string_literal: true # acquire full name # display full name backwards # Sum # of characters in name minus the space # Get name puts 'What is your first name?' first_name = gets.chomp puts 'What is your last name?' last_name = gets.chomp full_name = first_name + last_name # Reverse Name # using a method with an exclamation point is mutable puts "Is your full_name mutated? #{full_name}" # Counting characters in name puts "There are #{full_name.gsub(' ', '').length} characters in your name." <file_sep>/Gemfile gem 'rubocop-rails'<file_sep>/ruby_projects/calculator.rb # frozen_string_literal: true # create a calculator that performs addition, subtraction, division, # multiplication, and modulus # Addition puts 'Lets add 2 numbers' puts 20.times { print '-' } puts puts 'Enter first number' first_num = gets.chomp 20.times { print '-' } puts puts 'Enter second number' second_num = gets.chomp puts 'calculating...' puts first_num.to_i + second_num.to_i puts # Subtraction puts 'Lets subtract 2 numbers' puts 20.times { print '-' } puts puts 'Enter first number' first_num = gets.chomp 20.times { print '-' } puts puts 'Enter second number' second_num = gets.chomp puts 'calculating...' puts first_num.to_i - second_num.to_i puts # Division puts 'Lets divide 2 numbers' puts 20.times { print '-' } puts puts 'Enter first number' first_num = gets.chomp 20.times { print '-' } puts puts 'Enter second number' second_num = gets.chomp puts 'calculating...' puts first_num.to_i / second_num.to_i puts # Multiply puts 'Lets multiply 2 numbers' puts 20.times { print '-' } puts puts 'Enter first number' first_num = gets.chomp 20.times { print '-' } puts puts 'Enter second number' second_num = gets.chomp puts 'calculating...' puts first_num.to_i * second_num.to_i puts # Modulo puts 'Lets find the remainder from 2 numbers divided' puts 20.times { print '-' } puts puts 'Enter first number' first_num = gets.chomp 20.times { print '-' } puts puts 'Enter second number' second_num = gets.chomp puts 'calculating...' puts first_num.to_i % second_num.to_i puts
02009c1e58bc8ec3b5e9a49b4ad856007cd5ce06
[ "Ruby" ]
6
Ruby
danielvportlandia/ruby-course-udemy
bb84434f19d770f753b4dc06eebd43a0cba69967
cf023870f1548b3be2359cd7e4319932bf5a7f01
refs/heads/master
<repo_name>durvalprintes/station-frontend<file_sep>/src/pages/main/index.js import React, {Component} from 'react'; import {Link} from 'react-router-dom'; import api from '../../services/api'; import './styles.css'; export default class Main extends Component { state = { products: [], info: {}, page: 1, } componentDidMount() { this.loadProducts(); } loadProducts = async (page = 1) => { const response = await api.get(`/products?page=${page}`); const {docs, ...info} = response.data; this.setState({products: docs, info, page}); } prevPage = () => { const {page} = this.state; if (page === 1) return; const pageNum = page - 1; this.loadProducts(pageNum); } nextPage = () => { const {page, info} = this.state; if (page === info.pages) return; const pageNum = page + 1; this.loadProducts(pageNum); } render() { const {products, page, info} = this.state; return ( <div className="product-list"> {products.map(product => ( <article key={product._id}> <strong> {product.title}</strong> <p>{product.description}</p> <Link to={`/products/${product._id}`}>Acessar</Link> </article> ))} <div className="actions"> <button disabled={page === 1} onClick={this.prevPage}>Anterior</button> <button disabled={page === info.pages} onClick={this.nextPage}>Próximo</button> </div> </div> ); } }
eed606ef006153d4630c411835ecf9f5cf559763
[ "JavaScript" ]
1
JavaScript
durvalprintes/station-frontend
1b749bedb499f03ef2074b426b0f07959d69bf3a
0a1c33e2742b050f056efc5b5c4c00b0bdcae11e
refs/heads/main
<file_sep>package game; import java.util.Stack; public class Player extends Creature { private int room_id; private int pos_X; private int pos_Y; private Player player; private int startX; private int startY; private int hp; private int hpmoves; //private ArrayList<Integer> PosX = new ArrayList<Integer>(); //private ArrayList<Integer> PosY = new ArrayList<Integer>(); private Item wear_armor; private Item wield_sword; private CreatureAction dropPack; private Stack<Item> item = new Stack<Item>(); private Stack<String> item_string = new Stack<String>(); public void setPlayer(Player _player) { player = _player; System.out.println("Player:" + player); } public void setHp(int HP) { hp = HP; } public void setHpMove(int hpMoves) { hpmoves = hpMoves; } public int getHpMoves() { return hpmoves; } public int getHp() { return hp; } public Player getPlayer() { return player; } public Player( ) { System.out.println("Player"); } public int getRoomID(){ return room_id; } public void setWeapon(Item sword) { item.push(sword); item_string.push(((Sword)sword).getName()); System.out.println("Player:setWeapon"); } public void setArmor(Item armor) { item.push(armor); item_string.push(((Armor)armor).getName()); System.out.println("Player:setArmor"); } public void setScroll(Item scroll) { item.push(scroll); item_string.push(((Scroll)scroll).getName()); System.out.println("Player:setScroll"); } public Stack<Item> getItem() { System.out.println("Player:getItem"); return item; } public Stack<String> getStrItem(){ System.out.println("Player:getStrItem"); return item_string; } public void setID(int room, int serial) { room_id = room; System.out.println("Player:setID"+room + "\n" +serial); } public void wearArmor(Item armour){ wear_armor = armour; System.out.println("Player:wearArmour"); } public Item getWornArmor(){ System.out.println("Player:getWornArmor"); return wear_armor; } public void wieldSword(Item sword){ System.out.println("Player:wieldSword"); wield_sword = sword; } public Item getWieldSword(){ System.out.println("Player:getWieldSword"); return wield_sword; } public void setDropPack(CreatureAction dp){ System.out.println("Player:setDropPack"); dropPack = dp; } public CreatureAction getDropPack(){ System.out.println("Player:getDropPack"); return dropPack; } public int getX() { pos_X = getPosX().get(0); return pos_X; } public int getY() { pos_Y = getPosY().get(0); return pos_Y; } public int getstartingX() { return startX; } public int getstartingY() { return startY; } public void setstartingX(int x) { startX = getPosX().get(0) + x; } public void setstartingY(int y) { startY = getPosY().get(0) + y; } } <file_sep>public class Automobile{ private int id; //vehicle identification number private float miles; //miles driven private String date; //date of last maintenance private int day; //day in int type private int month; //month in int type private int year; //year in int type public Automobile(int _id, float _miles, int _day, int _month, int _year){ id = _id; miles = _miles; day = _day; month = _month; year = _year; } public int getDay(){ return day; } public void setDayAsString(int _day){ day = _day; } public int getMonth(){ return month; } public void setMonthAsString(int _month){ month = _month; } public int getYear(){ return year; } public void setYearAsString(int _year){ year = _year; } public String form_date(){ date = ""+month+"/"+day+"/"+year; return date; } public void print_values(){ System.out.println("Vehicle Identification Number: " + id); System.out.println("Miles driven: " + miles); } } <file_sep>package game; import java.util.ArrayList; public class Dungeon { private String _name; private int _width; private int _gameHeight; private int _bottomheight; private int _topheight; private ArrayList<Displayable> rooms = new ArrayList<Displayable>(); private ArrayList<Displayable> creatures = new ArrayList<Displayable>(); private ArrayList<Displayable> items = new ArrayList<Displayable>(); private ArrayList<Displayable> passages = new ArrayList<Displayable>(); private ArrayList<ArrayList<Displayable>> list = new ArrayList<ArrayList<Displayable>>(); public void getDungeon(String name, int width, int gameHeight, int topheight, int bottomheight) { _name = name; _width = width; _gameHeight = gameHeight; _bottomheight = bottomheight; _topheight = topheight; System.out.println("Dungeon:getDungeon" + _name + "\n" + _width +"\n" + _gameHeight); } public ArrayList<ArrayList<Displayable>> getList() { list.add(rooms); list.add(creatures); list.add(items); list.add(passages); return list; } public ArrayList<Displayable> getRooms(){ return rooms; } public int get_gameHeight() { return _gameHeight; } public int get_width() { return _width; } public void addRoom(Room r1) { System.out.println("Dungeon:addRoom"); rooms.add(r1); } public void addCreature(Creature c1) { System.out.println("Dungeon:addCreature"); creatures.add(c1); } public ArrayList<Displayable> getCreatures() { return creatures; } public void addPassage(Passage p1) { System.out.println("Dungeon:addPassage"); passages.add(p1); } public void addItem(Item it) { System.out.println("Dungeon:addItem"); items.add(it); } public int gettopheight() { return _topheight; } public int getBottomheight() { return _bottomheight; } }<file_sep>package game; public class DropPack extends CreatureAction{ private String _name; public DropPack(String name, Creature owner){ super(owner); _name = name; System.out.println("DropPack" + _name); } public String getname() { return _name; } } <file_sep>package game; import java.util.ArrayList; public class Creature extends Displayable { private int hp; private int HpMoves; private int maxHit; private ArrayList<CreatureAction> cact = new ArrayList<CreatureAction>(); // private Creature c = new Creature(); private CreatureAction changeDisplay; private CreatureAction updateDisplay; private CreatureAction youWin; private CreatureAction dact; private CreatureAction teleport; private CreatureAction endgame; //private Item weapon; //private Item armor; public Creature() { System.out.println("Creature"); } public void setHp(int h) { hp = h; } public int getHp() { return hp; } @Override public void setMaxHit(int _maxHit) { maxHit = _maxHit; } public int getMaxHit() { return maxHit; } public void setHpMoves(int hpm) { System.out.println("Creature:setHpMoves" + hpm); HpMoves = hpm; } public int getHpMoves() { return HpMoves; } public void setDeathAction(CreatureAction da) { System.out.println("Creature:setDeathAction"); dact = da; } public CreatureAction getDact() { return dact; } public void setHitAction(CreatureAction ha) { System.out.println("Creature:setHitAction"); cact.add(ha); } public ArrayList<CreatureAction> getCact() { return cact; } public void setChangeDisplay(CreatureAction ca){ changeDisplay = ca; System.out.println("Creature:setChangeDisplay"); } public CreatureAction getChangeDisplay(){ System.out.println("Creature:gerChangeDisplay"); return changeDisplay; } public void setEndAction(CreatureAction ea){ System.out.println("Creature:setEndAction"); endgame = ea; } public CreatureAction getEndAction(){ System.out.println("Creature:getEndAction"); return endgame; } public void setYouWinAction(CreatureAction yw){ System.out.println("Creature:setYouWinAction"); youWin = yw; } public CreatureAction getYouWinAction(){ System.out.println("Creature:getYouWinAction"); return youWin; } public void setUpdateDisplay(CreatureAction ud){ System.out.println("Creature:setUpdateDisplay"); updateDisplay = ud; } public CreatureAction getUpdateDisplay(){ System.out.println("Creature:getupdateDisplay"); return updateDisplay; } public void setTeleport(CreatureAction tele){ System.out.println("Creature:setUpdateDisplay"); teleport = tele; } public CreatureAction getTeleport(){ System.out.println("Creature:getupdateDisplay"); return teleport; } } <file_sep>package game; public class UpdateDisplay extends CreatureAction{ private String _name; public UpdateDisplay(String name, Creature owner){ super(owner); _name = name; System.out.println("UpdateDisplay" + _name); } public String getname() { return _name; } } <file_sep>public class HW1{ public static void main(String args[]){ Automobile vehicle1 = new Automobile(20, 3.14f, 19, 8, 2020); //object for first vehicle Automobile vehicle2 = new Automobile(5, 6.32f, 24, 5, 2020); //object for second vehicle vehicle1.print_values(); System.out.print("\n"); vehicle2.print_values(); } }<file_sep>package game; public class CreatureAction extends Action{ public CreatureAction(Creature owner) { System.out.println("CreatureAction:CreationAction"); } } <file_sep>package game; public class Hallucinate extends ItemAction{ private Creature owner; Hallucinate(Creature _owner){ super(_owner); owner = _owner; System.out.println("Hallucinate"); } public Creature getOwner() { return owner; } } <file_sep>public class ComparableArray { protected int[ ] ary; public ComparableArray(int[ ] data) { ary = data; } /* * do a deep copy of source, i.e., the source ary * and the ary of the object being constructed * should contain the same values but be different * arrays occupying different storage. */ public ComparableArray(ComparableArray source) { ary = new int[source.getLength( )]; for (int i = 0; i < ary.length; i++) { ary[i] = source.getElement(i); } } /* \ * return -1 if this < a, 0 if this equals a, 1 if this > a * based on the values of the ary members of this and a. * * Given an array x, x[0] = v0, x[0] = v2, ..., x[n] = vN * A prefix of length n of x is leading elements x[0] .. x[n-1] * * Consider the case where ary for this and a are the same length L * if some for some prefix of this.ary and a.ary of length k, k+1 < L, * (1) if this.ary[k+1] > a.ary[k+1], then this > a * (2) if this.ary[k+1] < a.ary[k+1], then this < a * (3) if this.ary[k+1] == a.ary[k+1] for all such prefix, this == a. * * (4) If one of this.ary and a.ary is shorter than the other, and the shorter * ary has length L, then (1) and (2) apply. * (5) If (3) applies for this L, then if the longer array has non-zero * elements in positions L or greater, the longer array is greatest, * (6) otherwise they are equal. * * Examples: * this.ary = [0, 1, 2, 4] and a.ary = [0, 1, 2, 3], this > a by (1) (k+1 is 3) * this.ary = [0, 1, 1, 3] and a.ary = [0, 1, 2, 3], this < a by (2) (k+1 is 2) * this.ary = [0, 1, 1, 2] and a.ary = [0, 1, 1, 2], this == a by (3) * this.ary = [0, 1] and a.ary = [0, 1, 1], this < a by (3) * this.ary = [0, 1, 2, 0, 0] and a.ary = [0, 1, 2], this == a by (3) * this.ary = [0, 1, 2, 0, 0] and a.ary = [0, 1, 2], this == a by (6) * this.ary = [0, 4, 1] and a.ary = [0, 1, 1, 1, 1], this > a by (4), (k+1 = 1) */ public int compareTo(ComparableArray a){ if(this.getLength() == a.getLength()){ for(int i = 0; i < this.getLength(); i++){ if(this.getElement(i) > a.getElement(i)){ return 1; } else if(this.getElement(i) < a.getElement(i)){ return -1; } } return 0; } else if(a.getLength() > this.getLength()){ int[] temp1 = new int[a.getLength()]; for(int n = 0; n < this.getLength(); n++){ temp1[n] = this.getElement(n); } for(int o = this.getLength() + 1; o < a.getLength(); o++){ temp1[o] = 0; } for(int j = 0; j < a.getLength(); j++){ if(temp1[j] > a.getElement(j)){ return 1; } else if(temp1[j] < a.getElement(j)){ return -1; } } return 0; } int[] temp2 = new int[this.getLength()]; for(int k = 0; k < a.getLength(); k++){ temp2[k] = a.getElement(k); } for(int v = a.getLength() + 1; v < this.getLength(); v++){ temp2[v] = 0; } for(int s = 0; s < this.getLength(); s++){ if(this.getElement(s) > temp2[s]){ return 1; } else if(this.getElement(s) < temp2[s]){ return -1; } } return 0; } public int getElement(int i){ return ary[i]; } // return the length of ary public int getLength(){ return ary.length; } // set all elements of ary to n public void makeNumber(int n){ int length = ary.length; for(int i = 0; i < length; i++){ ary[i] = n; } } // print out the elements of ary public String toString( ) { String elements = "["; for(int i = 0; i < ary.length; i++){ if(i == ary.length - 1){ elements = elements + String.valueOf(ary[i]); } else{ elements = elements + String.valueOf(ary[i]) + ","; } } elements = elements + "]"; return elements; } private int min(int i, int j){ if (j < i){ return j; } return i; } // I used this for compareTo, for cases 5 and 6 private int trailingNonZero(ComparableArray a, int i) { int comp = 0; for (; (comp == 0) && (i < a.getLength( )); i++) { if (a.getElement(i) > 0) comp = 1; if (a.getElement(i) < 0) comp = -1; } return comp; } } <file_sep>package game; public class Monster extends Creature{ private int room_id; private int startX; private int startY; private int maxhit; public Monster( ) { System.out.println("Monster"); } // @Override public int getRoomID(){ return room_id; } public void setName(String name) { System.out.println("Monster:setName"+name); } public void setID(int room, int serial) { room_id = room; // System.out.println("Monster:setID"+room + "\n" +serial); } public void setMaxHit(int _maxHit) { maxhit = _maxHit; } @Override public int getMaxHit() { return maxhit; } public int getstartingX() { return startX; } public int getstartingY() { return startY; } public void setstartingX(int x) { startX = x; } public void setstartingY(int y) { startY = y; } } <file_sep># ECE-39595J ## Rogue-Game Project This is a text-based game written in Java for my Object Oriented Programming class. The game is based off of the Rogue Game which was originally developed in the 1980s. ## Relevant Files ### Action.java A parent class consisting of functions which assist actions of the player and monster ### Armor.java A class dedicated to all the armours available in the game ### Char.java Class that displays all the characters in a message to the user interface ### Creature.java A parent class that consists of functions describing the characteristics of monsters and player ### CreatureAction.java Child class of the Action class for all monsters and player ### Displayable.java Parent class consisting of functions dedicated to displayable objects ### DropPack.java A class dedicated to the curse of dropping items from the player's pack each time player attacks a monster ### Dungeon.java Class to build and add all the monsters, player, rooms, and passages ### DungeonXMLHandler.java File that parses xml files to gather all information regarding the dungeon ### EndGame.java Ends the game when player wants to quit or player dies ### Hallucinate.java A class dedicated to having the player hallucinate once they read the scroll ### Item.java Parent class that encompasses all the necessary information for each item available in the game ### ItemAction.java Child class of the Action class for all items in the game ### KeyStrokePrinter.java Class that executes all the functions related to the keyboard inputs ### Monster.java Child class for the creature class and is dedicated to the monsters ### ObjectDisplayGrid.java Displays all the objects onto the user interface ### Passage.java Class responsible for storing information about all the passages in the game ### Player.java Child class for the creature class and is dedicated to the player ### Rogue.java Main file ### Room.java Functions dedicated to storing information about the items and creatures in the room ### Scroll.java Child class of items dedicated to scrolls ### Sword.java Child class of items dedicated to swords ### Teleport.java Monster teleports each time you attack him ### Final.mp4 Demo of game <file_sep>public class Test { public static final int[ ] values = {5, 1, 7, 15}; public static void main(String[ ] args) { Node rootInt = new Node<>(Integer.valueOf(10)); for (int i = 0; i < values.length; i++) { rootInt.insertNode(Integer.valueOf(values[i])); // facotry produces Integer w/value of ... } System.out.println(rootInt); // Q Node rootDouble = new Node<>(Double.valueOf((double) 10)); for (int i = 0; i < values.length; i++) { rootDouble.insertNode(Double.valueOf((double) values[i])); // facotry produces Integer w/value of ... } System.out.println(rootDouble); // Q } } <file_sep>public class LongList implements MyList{ private long _data; private LongList next; public LongList(LongList n, long data){ _data = data; next = n; } public long getData(){ return _data; } public LongList next(){ return next; } public void printNode(){ System.out.println("LongList Node, data is: " + _data); } } <file_sep>package game; public class EndGame extends CreatureAction{ private String _name; public EndGame(String name, Creature owner){ super(owner); _name = name; System.out.println("EndGame" + _name); } }
c0039bfbd8d3e7ef4944c65f1b299f4f72387f98
[ "Markdown", "Java" ]
15
Java
nikkiravi/ECE-39595J-OOP-Java
dd8ea2a6cf38c78fe46a4ec5230913b59775a8c1
03015f652d3fbd9f00331887e855bfcb12b7b778
refs/heads/master
<file_sep># Commit Service Сервис, который хранит коммиты по публичному репозиторию. ## Установка ``` 1. Склонируйте репозитории git clone https://github.com/koreicnurs/commit_service.git 2. Войдите в папку с проектом cd commit_service/ 3. Установите виртуальное окружение virtualenv --python `which python3` env 4. Активируйте виртуальное окружение . env/bin/activate 5. Установите REDIS глобально sudo apt-get install redis-server (Linux Ubuntu) brew install redis (macOS) 6. Установите все компоненты проекта pip install -r requirements.txt 7. Сделайте миграцию ./manage.py migrate 8. Создайте супер юзара для админки ./manage.py createsuperuser 9. Запустите сам проект ./manage.py runserver 10. Запустите Celery в 2 разных теминалах celery -A commit_service worker -l info celery -A commit_service beat -l info ``` ## Как работает проект Для начала нужно указать в админке репозитории, это может быть GitLab или GitHub В Админ панели указать путь к репозиторию для GitLab обзятаельно заполнить строку Project_id, а для GitHub обязательно заполнить строки Author_name и Repository_name Каждый день в 10 00 утра, запускается таск Таск в свою очередь вытаскивает все коммиты по указанным репозиториям <file_sep>amqp==2.6.1 arrow==0.17.0 asgiref==3.2.10 billiard==3.6.3.0 celery==4.4.7 certifi==2020.6.20 chardet==3.0.4 click==7.1.2 click-didyoumean==0.0.3 click-repl==0.1.6 Django==3.1.2 django-timezone-field==4.0 djangorestframework==3.12.1 idna==2.10 kombu==4.6.11 pkg-resources==0.0.0 prompt-toolkit==3.0.7 python-crontab==2.5.1 python-dateutil==2.8.1 pytz==2020.1 redis==3.5.3 requests==2.24.0 six==1.15.0 sqlparse==0.4.1 urllib3==1.25.10 vine==1.3.0 wcwidth==0.2.5 <file_sep># Generated by Django 3.1.2 on 2020-10-09 11:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('commits', '0003_auto_20201009_1016'), ] operations = [ migrations.RemoveField( model_name='repository', name='author_of_repo', ), migrations.RemoveField( model_name='repository', name='repo_name', ), migrations.AddField( model_name='repository', name='author_name', field=models.CharField(blank=True, max_length=50, verbose_name='Владелец репозитория'), ), migrations.AddField( model_name='repository', name='repository_name', field=models.CharField(blank=True, max_length=50, verbose_name='Название репозитория'), ), ] <file_sep># Generated by Django 3.1.2 on 2020-10-09 09:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('commits', '0001_initial'), ] operations = [ migrations.AlterField( model_name='repository', name='project_id', field=models.IntegerField(blank=True, null=True, verbose_name='Project ID'), ), migrations.AlterField( model_name='repository', name='url', field=models.CharField(blank=True, help_text='В это поле необходим URL репозитория в следующем формате https://github.com/author_name/repository_name', max_length=50, verbose_name='Путь'), ), ] <file_sep>from django.test import TestCase from commits.models import Repository from commits.serializers import RepositorySerializer class RepositorySerializerTestCase(TestCase): def test_get_list_repos(self): repo_1 = Repository.objects.create(type='github', url='https://github.com/Liazzz/my-first-blog') repo_2 = Repository.objects.create(type='gitlab', url='https://gitlab.com/mayan-edms/mayan-edms') data = RepositorySerializer([repo_1, repo_2], many=True).data expected_data = [ { 'id': repo_1.id, 'type': 'github', 'url': 'https://github.com/Liazzz/my-first-blog', }, { 'id': repo_2.id, 'type': 'gitlab', 'url': "https://gitlab.com/mayan-edms/mayan-edms", }, ] self.assertEqual(expected_data, data) <file_sep># Generated by Django 3.1.2 on 2020-10-08 15:25 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Repository', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('type', models.CharField(choices=[('gitlab', 'GitLab.com'), ('github', 'GitHub.com')], max_length=10, verbose_name='Тип репозитория')), ('url', models.CharField(max_length=50, verbose_name='Путь')), ('project_id', models.IntegerField(null=True, verbose_name='Project ID')), ], options={ 'verbose_name': 'репозитория', 'verbose_name_plural': 'репозитории', }, ), migrations.CreateModel( name='Commit', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('sha', models.CharField(max_length=50, verbose_name='Commit ID')), ('author', models.CharField(max_length=50, verbose_name='Автор')), ('message', models.CharField(max_length=100, verbose_name='Сообщение')), ('commit_time', models.DateTimeField(verbose_name='Дата создания')), ('repo', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='commits.repository', verbose_name='Репозитории')), ], options={ 'verbose_name': 'коммит', 'verbose_name_plural': 'коммиты', 'ordering': ['-commit_time'], }, ), ] <file_sep>from rest_framework import generics from .models import Repository, Commit from .serializers import RepositorySerializer, CommitSerializer class RepositoryListView(generics.ListAPIView): queryset = Repository.objects.all() serializer_class = RepositorySerializer class CommitListView(generics.ListAPIView): queryset = Commit.objects.all() serializer_class = CommitSerializer <file_sep>from django.db import models repo_url_help_text = 'В это поле необходим URL репозитория в следующем формате ' \ 'https://github.com/author_name/repository_name' project_id_help_text = 'Номер репозитория необходим для GitLab' author_name_help_text = 'Автор репозитория необходим для GitHub' repository_name = 'Название репозитория необходим для GitHub' class Repository(models.Model): REPO_CHOICES = [ ('gitlab', 'GitLab.com'), ('github', 'GitHub.com'), ] type = models.CharField('Тип репозитория', max_length=10, choices=REPO_CHOICES, null=False, blank=False) url = models.CharField('Путь', max_length=50, help_text=repo_url_help_text, blank=True) project_id = models.IntegerField('Project ID', help_text=project_id_help_text, null=True, blank=True) author_name = models.CharField('<NAME>', max_length=50, help_text=author_name_help_text, blank=True, null=True) repository_name = models.CharField('Название репозитория', max_length=50, help_text=repository_name, blank=True, null=True) def __str__(self): return f'{self.get_type_display()} - {self.url}' class Meta: verbose_name = 'репозитория' verbose_name_plural = 'репозитории' class Commit(models.Model): repo = models.ForeignKey(Repository, on_delete=models.CASCADE, verbose_name='Репозитории') sha = models.CharField('Commit ID', max_length=50) author = models.CharField('Автор', max_length=50) message = models.CharField('Сообщение', max_length=100) commit_time = models.DateTimeField('Дата коммита') def __str__(self): return self.sha + self.message class Meta: ordering = ['-commit_time'] verbose_name = 'коммит' verbose_name_plural = 'коммиты' <file_sep>from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from commits.models import Repository from commits.serializers import RepositorySerializer, Commit, CommitSerializer class RepositoriesTestCase(APITestCase): def test_get_list_repos(self): repo_1 = Repository.objects.create(type='github', url='https://github.com/Liazzz/my-first-blog', author_name='Liazzz', repository_name='my-first-blog') repo_2 = Repository.objects.create(type='gitlab', url='https://gitlab.com/mayan-edms/mayan-edms', project_id=155777) url = reverse('repositories_list') response = self.client.get(url) serializer_data = RepositorySerializer([repo_1, repo_2], many=True).data self.assertEqual(status.HTTP_200_OK, response.status_code) self.assertEqual(serializer_data, response.data) class CommitsTestCase(APITestCase): def setUp(self): self.repos = Repository.objects.create(type='github', url='https://github.com/Liazzz/my-first-blog', author_name='Liazzz', repository_name='my-first-blog') self.commit_1 = Commit.objects.create(repo=self.repos, sha='3c2ab2596de7c950ff6e8cfc528667e9da3ae01f', author='Liazzz', message='create project', commit_time='2020-10-09T10:59:00Z') self.commit_2 = Commit.objects.create(repo=self.repos, sha='3c2ab2596de7c950ff6e8cfc528667e9da3ae123', author='Liazzz', message='create project', commit_time='2020-10-09T10:59:00Z') def test_get_list_commits(self): url = reverse('commits_list') response = self.client.get(url) serializer_data = CommitSerializer([self.commit_1, self.commit_2], many=True).data self.assertEqual(status.HTTP_200_OK, response.status_code) self.assertEqual(serializer_data, response.data) <file_sep>gitlab_mock_data = [ { "id": "0b3d69e3559bc731b703179097907912a17f43f4", "short_id": "0b3d69e3", "created_at": "2020-10-10T10:27:12.000+00:00", "parent_ids": [ "fc560baf0118db59e57eb8a987c5e71f893248f7", "3bb27e94dc3fe20a051d23ff16ad5cb4f904b539" ], "title": "Merge branch '250571-jumping-button-on-the-environments-page' into 'master'", "message": "Merge branch '250571-jumping-button-on-the-environments-page' into 'master'\n\nAvoid New Environment button glitching when changing tabs\n\nSee merge request gitlab-org/gitlab!44603", "author_name": "<NAME>", "author_email": "<EMAIL>", "authored_date": "2020-10-10T10:27:12.000+00:00", "committer_name": "<NAME>", "committer_email": "<EMAIL>", "committed_date": "2020-10-10T10:27:12.000+00:00", "web_url": "https://gitlab.com/gitlab-org/gitlab/-/commit/0b3d69e3559bc731b703179097907912a17f43f4" }, { "id": "fc560baf0118db59e57eb8a987c5e71f893248f7", "short_id": "fc560baf", "created_at": "2020-10-10T00:25:14.000+00:00", "parent_ids": [ "5b7a8f2031bf3e9534c620577151105880d6af86", "632434f9549e126c9fecb3ea452f6bcdc6d2aeee" ], "title": "Merge branch 'pl-spec-factries-perf' into 'master'", "message": "Merge branch 'pl-spec-factries-perf' into 'master'\n\nSpeed up factories spec by using FactoryDefault\n\nSee merge request gitlab-org/gitlab!44561", "author_name": "<NAME>", "author_email": "<EMAIL>", "authored_date": "2020-10-10T00:25:14.000+00:00", "committer_name": "<NAME>", "committer_email": "<EMAIL>", "committed_date": "2020-10-10T00:25:14.000+00:00", "web_url": "https://gitlab.com/gitlab-org/gitlab/-/commit/fc560baf0118db59e57eb8a987c5e71f893248f7" }, { "id": "<KEY>", "short_id": "632434f9", "created_at": "2020-10-10T00:25:12.000+00:00", "parent_ids": [ "e0e5ab3c17175b6a63ccaa21f6133b7b66e59aac" ], "title": "Speed up factories spec by using FactoryDefault", "message": "Speed up factories spec by using FactoryDefault\n", "author_name": "<NAME>", "author_email": "<EMAIL>", "authored_date": "2020-10-10T00:25:12.000+00:00", "committer_name": "<NAME>", "committer_email": "<EMAIL>", "committed_date": "2020-10-10T00:25:12.000+00:00", "web_url": "https://gitlab.com/gitlab-org/gitlab/-/commit/632434f9549e126c9fecb3ea452f6bcdc6d2aeee" }, ] github_mock_data = [ { "sha": "f1f24539d8c86f60d1e2951a19eb3178e15d6399", "node_id": "MDY6Q29tbWl0NDE2NDQ4MjpmMWYyNDUzOWQ4Yzg2ZjYwZDFlMjk1MWExOWViMzE3OGUxNWQ2Mzk5", "commit": { "author": { "name": "<NAME>", "email": "<EMAIL>", "date": "2020-10-08T18:41:22Z" }, "committer": { "name": "<NAME>", "email": "<EMAIL>", "date": "2020-10-09T10:59:00Z" }, "message": "Fixed #32094 -- Fixed flush() calls on management command self.stdout/err proxies.", "tree": { "sha": "016b59db4abb1e7c5337ace176a21e908dc564ce", "url": "https://api.github.com/repos/django/django/git/trees/016b59db4abb1e7c5337ace176a21e908dc564ce" }, "url": "https://api.github.com/repos/django/django/git/commits/f1f24539d8c86f60d1e2951a19eb3178e15d6399", "comment_count": 0, "verification": { "verified": False, "reason": "unsigned", "signature": None, "payload": None } }, "url": "https://api.github.com/repos/django/django/commits/f1f24539d8c86f60d1e2951a19eb3178e15d6399", "html_url": "https://github.com/django/django/commit/f1f24539d8c86f60d1e2951a19eb3178e15d6399", "comments_url": "https://api.github.com/repos/django/django/commits/f1f24539d8c86f60d1e2951a19eb3178e15d6399/comments", "author": { "login": "thomas-riccardi", "id": 1730297, "node_id": "MDQ6VXNlcjE3MzAyOTc=", "avatar_url": "https://avatars2.githubusercontent.com/u/1730297?v=4", "gravatar_id": "", "url": "https://api.github.com/users/thomas-riccardi", "html_url": "https://github.com/thomas-riccardi", "followers_url": "https://api.github.com/users/thomas-riccardi/followers", "following_url": "https://api.github.com/users/thomas-riccardi/following{/other_user}", "gists_url": "https://api.github.com/users/thomas-riccardi/gists{/gist_id}", "starred_url": "https://api.github.com/users/thomas-riccardi/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/thomas-riccardi/subscriptions", "organizations_url": "https://api.github.com/users/thomas-riccardi/orgs", "repos_url": "https://api.github.com/users/thomas-riccardi/repos", "events_url": "https://api.github.com/users/thomas-riccardi/events{/privacy}", "received_events_url": "https://api.github.com/users/thomas-riccardi/received_events", "type": "User", "site_admin": False }, "committer": { "login": "felixxm", "id": 2865885, "node_id": "MDQ6VXNlcjI4NjU4ODU=", "avatar_url": "https://avatars2.githubusercontent.com/u/2865885?v=4", "gravatar_id": "", "url": "https://api.github.com/users/felixxm", "html_url": "https://github.com/felixxm", "followers_url": "https://api.github.com/users/felixxm/followers", "following_url": "https://api.github.com/users/felixxm/following{/other_user}", "gists_url": "https://api.github.com/users/felixxm/gists{/gist_id}", "starred_url": "https://api.github.com/users/felixxm/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/felixxm/subscriptions", "organizations_url": "https://api.github.com/users/felixxm/orgs", "repos_url": "https://api.github.com/users/felixxm/repos", "events_url": "https://api.github.com/users/felixxm/events{/privacy}", "received_events_url": "https://api.github.com/users/felixxm/received_events", "type": "User", "site_admin": False }, "parents": [ { "sha": "b7da588e883e12b8ac3bb8a486e654e30fc1c6c8", "url": "https://api.github.com/repos/django/django/commits/b7da588e883e12b8ac3bb8a486e654e30fc1c6c8", "html_url": "https://github.com/django/django/commit/b7da588e883e12b8ac3bb8a486e654e30fc1c6c8" } ] }, { "sha": "b7da588e883e12b8ac3bb8a486e654e30fc1c6c8", "node_id": "MDY6Q29tbWl0NDE2NDQ4MjpiN2RhNTg4ZTg4M2UxMmI4YWMzYmI4YTQ4NmU2NTRlMzBmYzFjNmM4", "commit": { "author": { "name": "<NAME>", "email": "<EMAIL>", "date": "2020-10-08T19:44:34Z" }, "committer": { "name": "<NAME>", "email": "<EMAIL>", "date": "2020-10-09T09:39:22Z" }, "message": "Fixed #32091 -- Fixed admin search bar width on filtered admin page.", "tree": { "sha": "342a9c00d0c1cccedaddd3c2018e2b7e6af7897c", "url": "https://api.github.com/repos/django/django/git/trees/342a9c00d0c1cccedaddd3c2018e2b7e6af7897c" }, "url": "https://api.github.com/repos/django/django/git/commits/b7da588e883e12b8ac3bb8a486e654e30fc1c6c8", "comment_count": 0, "verification": { "verified": False, "reason": "unsigned", "signature": None, "payload": None } }, "url": "https://api.github.com/repos/django/django/commits/b7da588e883e12b8ac3bb8a486e654e30fc1c6c8", "html_url": "https://github.com/django/django/commit/b7da588e883e12b8ac3bb8a486e654e30fc1c6c8", "comments_url": "https://api.github.com/repos/django/django/commits/b7da588e883e12b8ac3bb8a486e654e30fc1c6c8/comments", "author": { "login": "tim-schilling", "id": 1281215, "node_id": "MDQ6VXNlcjEyODEyMTU=", "avatar_url": "https://avatars0.githubusercontent.com/u/1281215?v=4", "gravatar_id": "", "url": "https://api.github.com/users/tim-schilling", "html_url": "https://github.com/tim-schilling", "followers_url": "https://api.github.com/users/tim-schilling/followers", "following_url": "https://api.github.com/users/tim-schilling/following{/other_user}", "gists_url": "https://api.github.com/users/tim-schilling/gists{/gist_id}", "starred_url": "https://api.github.com/users/tim-schilling/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/tim-schilling/subscriptions", "organizations_url": "https://api.github.com/users/tim-schilling/orgs", "repos_url": "https://api.github.com/users/tim-schilling/repos", "events_url": "https://api.github.com/users/tim-schilling/events{/privacy}", "received_events_url": "https://api.github.com/users/tim-schilling/received_events", "type": "User", "site_admin": False }, "committer": { "login": "felixxm", "id": 2865885, "node_id": "MDQ6VXNlcjI4NjU4ODU=", "avatar_url": "https://avatars2.githubusercontent.com/u/2865885?v=4", "gravatar_id": "", "url": "https://api.github.com/users/felixxm", "html_url": "https://github.com/felixxm", "followers_url": "https://api.github.com/users/felixxm/followers", "following_url": "https://api.github.com/users/felixxm/following{/other_user}", "gists_url": "https://api.github.com/users/felixxm/gists{/gist_id}", "starred_url": "https://api.github.com/users/felixxm/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/felixxm/subscriptions", "organizations_url": "https://api.github.com/users/felixxm/orgs", "repos_url": "https://api.github.com/users/felixxm/repos", "events_url": "https://api.github.com/users/felixxm/events{/privacy}", "received_events_url": "https://api.github.com/users/felixxm/received_events", "type": "User", "site_admin": False }, "parents": [ { "sha": "de81676b51e4dad510ef387c3ae625f9091fe57f", "url": "https://api.github.com/repos/django/django/commits/de81676b51e4dad510ef387c3ae625f9091fe57f", "html_url": "https://github.com/django/django/commit/de81676b51e4dad510ef387c3ae625f9091fe57f" } ] }, ] <file_sep>from unittest import mock from django.test import TestCase from commits.models import Repository, Commit from commits.tasks import parsing_gitlab_repositories, parsing_github_repositories from commits.tests.mock_data import gitlab_mock_data, github_mock_data def mocked_requests_get(*args, **kwargs): class MockResponse: def __init__(self, json_data, status_code): self.json_data = json_data self.status_code = status_code def json(self): return self.json_data if args[0] == 'https://gitlab.com/api/v4/projects/155566/repository/commits': return MockResponse(gitlab_mock_data, 200) elif args[0] == 'https://api.github.com/repos/django/django/commits': return MockResponse(github_mock_data, 200) return MockResponse(None, 404) class GitLabTestCase(TestCase): @mock.patch('requests.get', side_effect=mocked_requests_get) def test_gitlab(self, *args): repo = Repository.objects.create(type='gitlab', url='https://gitlab.com/mayan-edms/mayan-edms', project_id=155566) parsing_gitlab_repositories() commits = Commit.objects.filter(repo=repo).all() self.assertEqual(commits.count(), 3) @mock.patch('requests.get', side_effect=mocked_requests_get) def test_gitlab_bad_response(self, *args): repo = Repository.objects.create(type='gitlab', url='https://gitlab.com/mayan-edms/mayan-edms', project_id=1551231) parsing_gitlab_repositories() commits = Commit.objects.filter(repo=repo).all() self.assertEqual(commits.count(), 0) class GitHubTestCase(TestCase): @mock.patch('requests.get', side_effect=mocked_requests_get) def test_gitlab(self, *args): repo = Repository.objects.create(type='github', url='https://github.com/django/django', author_name='django', repository_name='django') parsing_github_repositories() commits = Commit.objects.filter(repo=repo).all() self.assertEqual(commits.count(), 2) @mock.patch('requests.get', side_effect=mocked_requests_get) def test_gitlab_bad_response(self, *args): repo = Repository.objects.create(type='github', url='https://github.com/django/django', author_name='qwerty', repository_name='qwerty') parsing_github_repositories() commits = Commit.objects.filter(repo=repo).all() self.assertEqual(commits.count(), 0) <file_sep>from django.contrib import admin from commits.models import Repository, Commit @admin.register(Repository) class RepoAdmin(admin.ModelAdmin): list_display = ('get_type', 'url', 'project_id') list_filter = ('type',) search_fields = ('url',) def get_type(self, obj): return obj.get_type_display() @admin.register(Commit) class CommitAdmin(admin.ModelAdmin): list_display = ('repo', 'author', 'sha', 'message', 'commit_time') readonly_fields = ('repo', 'author', 'sha', 'message', 'commit_time') list_filter = ('repo', 'author', 'commit_time') search_fields = ('author', 'sha', 'message') <file_sep># Generated by Django 3.1.2 on 2020-10-09 12:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('commits', '0004_auto_20201009_1159'), ] operations = [ migrations.AlterField( model_name='repository', name='author_name', field=models.CharField(blank=True, help_text='Автор репозитория необходим для GitHub', max_length=50, null=True, verbose_name='Владелец репозитория'), ), migrations.AlterField( model_name='repository', name='project_id', field=models.IntegerField(blank=True, help_text='Номер репозитория необходим для GitLab', null=True, verbose_name='Project ID'), ), migrations.AlterField( model_name='repository', name='repository_name', field=models.CharField(blank=True, help_text='В это поле необходим URL репозитория в следующем формате https://github.com/author_name/repository_name', max_length=50, null=True, verbose_name='Название репозитория'), ), ] <file_sep># Generated by Django 3.1.2 on 2020-10-09 10:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('commits', '0002_auto_20201009_0934'), ] operations = [ migrations.AddField( model_name='repository', name='author_of_repo', field=models.CharField(blank=True, max_length=50), ), migrations.AddField( model_name='repository', name='repo_name', field=models.CharField(blank=True, max_length=50), ), ] <file_sep>import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'commit_service.settings') app = Celery('commit_service') app.conf.broker_url = 'redis://localhost:6379/0' app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.beat_schedule = { 'pars_gitlab_repositories_every_day': { 'task': 'commits.tasks.parsing_gitlab_repositories', 'schedule': crontab(minute=0, hour=10), }, 'pars_github_repositories_every_day': { 'task': 'commits.tasks.parsing_github_repositories', 'schedule': crontab(minute=0, hour=10), }, } <file_sep>from celery import shared_task import arrow import requests from commits.models import Repository, Commit gl_url = 'https://gitlab.com/api/v4/projects/{}/repository/commits' gh_url = 'https://api.github.com/repos/{}/{}/commits' @shared_task def parsing_gitlab_repositories(): repos = Repository.objects.all() gl_repos = repos.filter(type='gitlab') for repo in gl_repos: url = gl_url.format(repo.project_id) res = requests.get(url) if res.status_code != 200: print(f'Fail to get commits of this Project id: {repo.project_id}') continue for commit in res.json(): commit_time = arrow.get(commit["committed_date"]) Commit.objects.get_or_create( repo=repo, sha=commit["id"], author=commit["author_name"], message=commit["message"], commit_time=commit_time.datetime, ) @shared_task def parsing_github_repositories(): repos = Repository.objects.all() gh_repos = repos.filter(type='github') for repo in gh_repos: url = gh_url.format(repo.author_name, repo.repository_name) res = requests.get(url) if res.status_code != 200: print(f'Fail to get commits of this Project') continue for commit in res.json(): commit_time = arrow.get(commit["commit"]["author"]["date"]) Commit.objects.get_or_create( repo=repo, sha=commit["sha"], author=commit["commit"]["author"]["name"], message=commit["commit"]["message"], commit_time=commit_time.datetime, )
823f71f831d3282eba084d81a54f76446e860f1f
[ "Markdown", "Python", "Text" ]
16
Markdown
koreicnurs/commit_service
3513e1ba7a858709d9e0ba3ebc9f62d46e238aa5
25d59ba9b85ce82cfaebb671b459bbfd0bae4e5f
refs/heads/main
<repo_name>DanYesmagulov/go-phone-book<file_sep>/pkg/repository/postgres.go package repository import ( "fmt" "github.com/jmoiron/sqlx" ) const ( contactTable = "contacts" ) type Config struct { Host string Port string Username string Password string DBName string SSLMode string } func NewPgDB(config Config) (*sqlx.DB, error) { db, err := sqlx.Open("postgres", fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s sslmode=%s", config.Host, config.Port, config.Username, config.DBName, config.Password, config.SSLMode)) if err != nil { return nil, err } err = db.Ping() if err != nil { return nil, err } return db, nil } <file_sep>/pkg/service/contact.go package service import ( phonebook "github.com/DanYesmagulov/go-phone-book" "github.com/DanYesmagulov/go-phone-book/pkg/repository" ) type ContactService struct { repo repository.Contacts } func NewContactService(repo repository.Contacts) *ContactService { return &ContactService{repo: repo} } func (s *ContactService) Create(contact phonebook.Contact) (int, error) { return s.repo.Create(contact) } func (s *ContactService) GetAll() ([]phonebook.Contact, error) { return s.repo.GetAll() } func (s *ContactService) GetById(id int) (phonebook.Contact, error) { return s.repo.GetById(id) } func (s *ContactService) DeleteById(id int) error { return s.repo.DeleteById(id) } func (s *ContactService) UpdateById(id int, input phonebook.UpdateContact) error { if err := input.Validate(); err != nil { return err } return s.repo.UpdateById(id, input) } <file_sep>/contact.go package phonebook import "errors" type Contact struct { Id int `json:"id" db:"id"` Phone *string `json:"phone" db:"phone" binding:"required"` Name *string `json:"name" db:"name" binding:"required"` } type UpdateContact struct { Phone *string `json:"phone"` Name *string `json:"name"` } func (i UpdateContact) Validate() error { if i.Name == nil && i.Phone == nil { return errors.New("поля измения пустые") } return nil } <file_sep>/pkg/handler/handler.go package handler import ( "github.com/DanYesmagulov/go-phone-book/pkg/service" "github.com/gin-gonic/gin" ) type Handler struct { services *service.Service } func NewHandler(services *service.Service) *Handler { return &Handler{services: services} } func (h *Handler) InitRoutes() *gin.Engine { router := gin.New() api := router.Group("/api") { contacts := api.Group("/contacts") { contacts.POST("/", h.createContact) contacts.GET("/", h.getAllContacts) contacts.GET("/:id", h.getContactById) contacts.PUT("/:id", h.updateContactById) contacts.DELETE("/:id", h.deleteContactById) } } return router } <file_sep>/pkg/repository/contact_postgres.go package repository import ( "fmt" "strings" phonebook "github.com/DanYesmagulov/go-phone-book" "github.com/jmoiron/sqlx" ) type ContactPostgres struct { db *sqlx.DB } func NewContactPostgres(db *sqlx.DB) *ContactPostgres { return &ContactPostgres{db: db} } func (r *ContactPostgres) Create(contact phonebook.Contact) (int, error) { tx, err := r.db.Begin() if err != nil { return 0, err } var id int createContactQuery := fmt.Sprintf("INSERT INTO %s (phone, name) VALUES ($1, $2) RETURNING id", contactTable) row := tx.QueryRow(createContactQuery, contact.Phone, contact.Name) if err := row.Scan(&id); err != nil { tx.Rollback() return 0, err } return id, tx.Commit() } func (r *ContactPostgres) GetAll() ([]phonebook.Contact, error) { var contacts []phonebook.Contact query := fmt.Sprintf("SELECT * FROM %s", contactTable) err := r.db.Select(&contacts, query) return contacts, err } func (r *ContactPostgres) GetById(id int) (phonebook.Contact, error) { var contacts phonebook.Contact query := fmt.Sprintf(`SELECT * FROM %s WHERE id = $1`, contactTable) err := r.db.Get(&contacts, query, id) return contacts, err } func (r *ContactPostgres) DeleteById(id int) error { query := fmt.Sprintf("DELETE FROM %s WHERE id=$1", contactTable) _, err := r.db.Exec(query, id) return err } func (r *ContactPostgres) UpdateById(id int, input phonebook.UpdateContact) error { setValues := make([]string, 0) args := make([]interface{}, 0) argId := 1 if input.Name != nil { setValues = append(setValues, fmt.Sprintf("name=$%d", argId)) args = append(args, *input.Name) argId++ } if input.Phone != nil { setValues = append(setValues, fmt.Sprintf("phone=$%d", argId)) args = append(args, *input.Phone) argId++ } setQuery := strings.Join(setValues, ", ") query := fmt.Sprintf("UPDATE %s SET %s WHERE id = $%d", contactTable, setQuery, argId) args = append(args, id) _, err := r.db.Exec(query, args...) return err } <file_sep>/cmd/main.go package main import ( "log" "os" phonebook "github.com/DanYesmagulov/go-phone-book" "github.com/DanYesmagulov/go-phone-book/pkg/handler" "github.com/DanYesmagulov/go-phone-book/pkg/repository" "github.com/DanYesmagulov/go-phone-book/pkg/service" "github.com/joho/godotenv" _ "github.com/lib/pq" ) func main() { if err := godotenv.Load(); err != nil { log.Fatalf("Ошибка во время инициализации переменных окружения: %s", err.Error()) } db, err := repository.NewPgDB(repository.Config{ Host: os.Getenv("DB_HOST"), Port: os.Getenv("DB_PORT"), Username: os.Getenv("DB_USERNAME"), Password: os.Getenv("DB_PASSWORD"), DBName: os.Getenv("DB_DBNAME"), SSLMode: os.Getenv("DB_SSLMODE"), }) if err != nil { log.Fatalf("Ошибка во время инициализации бд: %s", err.Error()) } repos := repository.NewRepository(db) services := service.NewService(repos) handlers := handler.NewHandler(services) server := new(phonebook.Server) if err := server.Run("9000", handlers.InitRoutes()); err != nil { log.Fatalf("Ошибка во время запуска сервера: %s", err.Error()) } } <file_sep>/pkg/handler/contact.go package handler import ( "net/http" "strconv" phonebook "github.com/DanYesmagulov/go-phone-book" "github.com/gin-gonic/gin" ) func (h *Handler) createContact(c *gin.Context) { var input phonebook.Contact if err := c.BindJSON(&input); err != nil { newErrorResponse(c, http.StatusBadRequest, err.Error()) return } id, err := h.services.Contacts.Create(input) if err != nil { newErrorResponse(c, http.StatusInternalServerError, err.Error()) return } c.JSON(http.StatusOK, map[string]interface{}{ "id": id, }) } type getAllContactsResponse struct { Data []phonebook.Contact `json:"data"` } func (h *Handler) getAllContacts(c *gin.Context) { contacts, err := h.services.Contacts.GetAll() if err != nil { newErrorResponse(c, http.StatusInternalServerError, err.Error()) return } c.JSON(http.StatusOK, getAllContactsResponse{ Data: contacts, }) } func (h *Handler) getContactById(c *gin.Context) { id, err := strconv.Atoi(c.Param("id")) if err != nil { newErrorResponse(c, http.StatusBadRequest, "Неправильный параметр id") return } contact, err := h.services.Contacts.GetById(id) if err != nil { newErrorResponse(c, http.StatusInternalServerError, err.Error()) return } c.JSON(http.StatusOK, contact) } func (h *Handler) updateContactById(c *gin.Context) { id, err := strconv.Atoi(c.Param("id")) if err != nil { newErrorResponse(c, http.StatusBadRequest, "Неправильный параметр id") return } var input phonebook.UpdateContact if err := c.BindJSON(&input); err != nil { newErrorResponse(c, http.StatusBadRequest, err.Error()) return } if err := h.services.Contacts.UpdateById(id, input); err != nil { newErrorResponse(c, http.StatusInternalServerError, err.Error()) return } c.JSON(http.StatusOK, statusResponse{ "ok", }) } func (h *Handler) deleteContactById(c *gin.Context) { id, err := strconv.Atoi(c.Param("id")) if err != nil { newErrorResponse(c, http.StatusBadRequest, "Неправильный параметр id") return } err = h.services.Contacts.DeleteById(id) if err != nil { newErrorResponse(c, http.StatusInternalServerError, err.Error()) return } c.JSON(http.StatusOK, statusResponse{ Status: "ok", }) } <file_sep>/pkg/service/service.go package service import ( phonebook "github.com/DanYesmagulov/go-phone-book" "github.com/DanYesmagulov/go-phone-book/pkg/repository" ) type Contacts interface { Create(contact phonebook.Contact) (int, error) GetAll() ([]phonebook.Contact, error) GetById(id int) (phonebook.Contact, error) DeleteById(id int) error UpdateById(id int, input phonebook.UpdateContact) error } type Service struct { Contacts } func NewService(repos *repository.Repository) *Service { return &Service{ Contacts: NewContactService(repos.Contacts), } } <file_sep>/pkg/repository/repository.go package repository import ( phonebook "github.com/DanYesmagulov/go-phone-book" "github.com/jmoiron/sqlx" ) type Contacts interface { Create(contact phonebook.Contact) (int, error) GetAll() ([]phonebook.Contact, error) GetById(id int) (phonebook.Contact, error) DeleteById(id int) error UpdateById(id int, input phonebook.UpdateContact) error } type Repository struct { Contacts } func NewRepository(db *sqlx.DB) *Repository { return &Repository{ Contacts: NewContactPostgres(db), } } <file_sep>/schema/000001_init.up.sql CREATE TABLE contacts ( id serial not null unique, phone varchar(255) not null unique, name varchar(255) not null );
7a270c4a15989667c64128ef8ab755c4bfa46412
[ "SQL", "Go" ]
10
Go
DanYesmagulov/go-phone-book
1ef5b1b6898a8210293d9606fb9c2aaca2dca112
4b205697f7cd14736b3f88d1952d6f5df112b94f
refs/heads/master
<file_sep>#include "GraphicWidget.h" GraphicWidget::GraphicWidget(std::shared_ptr<AbstractBusinessLogic> logic, QWidget *parent) : QWidget(parent),pLogic(logic){ pCbxCurrency=new QComboBox; pCbxCurrency->addItems(convertToQList(pLogic->getAllCurrencies())); QVBoxLayout* pVbx=new QVBoxLayout; pVbx->addWidget(pCbxCurrency); setLayout(pVbx); } QStringList GraphicWidget::convertToQList(const std::list<std::string>& list) const{ QStringList qList; for(const auto& i:list) qList.push_back(QString::fromStdString(i)); return qList; } <file_sep>#pragma once #include "SRC/DataBase/Data.h" #include "SRC/BusinessLogic/RecordString.h" #include "SRC/BusinessLogic/RecordsOperations.h" #include <list> #include <memory> class BalanceCalculator{ public: BalanceCalculator(std::shared_ptr<AbstractData>& data,std::shared_ptr<RecordsOperations>& operations); std::string getBalance(const std::string& date); private: std::shared_ptr<AbstractData> pData; std::shared_ptr<RecordsOperations> pOperations; std::string currentDate; enum class Time{ year,month,allTime }; const char* loss="Убыток"; const char* profit="Прибыль"; std::string balance(const BalanceCalculator::Time period, const std::string& currency)const; std::string minusYear()const; std::string minusMonth()const; std::string balanceCalculate(const std::string& dateFrom, const std::string &currency)const; }; <file_sep>#pragma once #include <string> #include "SRC/BusinessLogic/Report.h" #include "SRC/BusinessLogic/RecordString.h" #include <sstream> #include "hpdf.h" #include <fstream> class ReportSavePdf{ public: ReportSavePdf(const std::shared_ptr<Report>& rep); void savePDF(const std::string& filename, const std::string& userName, const std::string& currentDate); private: std::shared_ptr<Report> pReport; std::string doubleToString(const double value)const; void printVector(const std::vector<std::string>& vec, std::string& str, HPDF_REAL& yPosition, HPDF_Doc &pdf); HPDF_REAL reportHeader(const std::string& userName, const std::string& currentDate, HPDF_Doc& pdf); void report(HPDF_Doc& pdf, HPDF_REAL& yPos); void tableHeader(const HPDF_Page& page,HPDF_REAL& yPosition)const; void calculateParameters(const HPDF_REAL& pageWidth, const HPDF_REAL &pageHeight); HPDF_Page newPage(HPDF_Doc& pdf); const HPDF_REAL leading=20; const double kLeftBorder=0.12; const double kRightBorder=0.024; const double kVerticalBorder=0.017; const char* pathFont="fonts/arial.ttf"; const char* encoding="UTF-8"; const HPDF_REAL fontSize=12; HPDF_Font font; HPDF_REAL pageWidth; HPDF_REAL pageHeight; HPDF_REAL leftBorder; HPDF_REAL rightBorder; HPDF_REAL verticalBorder; HPDF_REAL xType; HPDF_REAL xCategory; HPDF_REAL xDescription; HPDF_REAL xSum; HPDF_REAL xCurrency; }; <file_sep>#include "Data.h" void Data::clear(){ data.clear(); } unsigned int Data::rows()const{ return data.size(); } unsigned int Data::columns()const{ Record temp; return temp.columns(); } void Data::remove(const int row){ data.erase(data.begin()+row); } void Data::sort(){ std::sort(data.begin(),data.end()); } const RecordString Data::getRecord(const unsigned int row)const{ return data[row].convertToString(); } void Data::setRecord(const unsigned int row,const RecordString& record){ if((row+1)>data.size()) data.push_back(record); else data[row]=record; } std::list<std::string> Data::getAllCurrencies()const{ Record rec; return rec.getAllCurrencies(); } std::list<std::string> Data::getAllTypes()const{ Record rec; return rec.getAllTypes(); } <file_sep>#include "MoneyRepositaryWidget.h" MoneyRepositaryWidget::MoneyRepositaryWidget(std::shared_ptr<AbstractBusinessLogic> logic, QWidget* parent): QWidget(parent),pLogic(logic){ drawWindow(); connectButtons(); setWorkView(); } void MoneyRepositaryWidget::drawWindow(){ pTable=new QTableWidget; pTable->installEventFilter(this); pBtnSave=new QPushButton(tr("Сохранить кошелек")); pBtnAdd=new QPushButton(tr("Добавить запись")); pBtnEdit=new QPushButton(tr("Редактировать запись")); pBtnDelete=new QPushButton(tr("Удалить запись")); pBtnCnacel=new QPushButton(tr("Отмена")); pTimeEdit=new QDateEdit(QDate::currentDate()); pCbxType=new QComboBox; pCbxType->addItems(convertToQList(pLogic->getAllTypes())); pCbxCategory=new QComboBox; pCbxCategory->setEditable(true); pCbxDescription=new QComboBox; pCbxDescription->setEditable(true); pLineEditSum=new QLineEdit; pCbxCurrency=new QComboBox; pCbxCurrency->addItems(convertToQList(pLogic->getAllCurrencies())); QHBoxLayout* pHbxEdit=new QHBoxLayout; pHbxEdit->addWidget(pTimeEdit,1); pHbxEdit->addWidget(pCbxType,1); pHbxEdit->addWidget(pCbxCategory,3); pHbxEdit->addWidget(pCbxDescription,3); pHbxEdit->addWidget(pLineEditSum,1); pHbxEdit->addWidget(pCbxCurrency,1); QVBoxLayout* pVbxTable=new QVBoxLayout; pVbxTable->addWidget(pTable); pVbxTable->addLayout(pHbxEdit); QVBoxLayout* pVbxButtons=new QVBoxLayout; pVbxButtons->addStretch(1); pVbxButtons->addWidget(pBtnSave); pVbxButtons->addSpacing(10); pVbxButtons->addWidget(pBtnDelete); pVbxButtons->addWidget(pBtnEdit); pVbxButtons->addWidget(pBtnCnacel); pVbxButtons->addSpacing(10); pVbxButtons->addWidget(pBtnAdd); QHBoxLayout* pHbxMain=new QHBoxLayout; pHbxMain->addLayout(pVbxTable); pHbxMain->addLayout(pVbxButtons); setLayout(pHbxMain); } void MoneyRepositaryWidget::connectButtons(){ QObject::connect(pBtnSave,SIGNAL(clicked()),SLOT(saveData())); QObject::connect(pBtnAdd,SIGNAL(clicked()),SLOT(addRecord())); QObject::connect(pBtnDelete,SIGNAL(clicked()),SLOT(deleteRecord())); QObject::connect(pBtnEdit,SIGNAL(clicked()),SLOT(editRecord())); QObject::connect(pBtnCnacel,SIGNAL(clicked()),SLOT(cancelEditRecord())); QObject::connect(pCbxType,SIGNAL(textActivated(const QString&)),SLOT(updateCbxCategory())); QObject::connect(pCbxCategory,SIGNAL(textActivated(const QString&)),SLOT(categoryChanged())); } bool MoneyRepositaryWidget::eventFilter(QObject*, QEvent *pEvent){ if(pEvent->type() == QEvent::Resize) setTableDimensions(); return false; } void MoneyRepositaryWidget::addRecord(){ unsigned int row=0; if(isEdit) row=pTable->selectionModel()->currentIndex().row(); else row=pLogic->rowsCount(); RecordString rec( pTimeEdit->date().toString("yyyy-MM-dd").toStdString(), pCbxType->currentText().toStdString(), pCbxCategory->currentText().toStdString(), pCbxDescription->currentText().toStdString(), pLineEditSum->text().toDouble(), pCbxCurrency->currentText().toStdString()); pLogic->setData(row,rec); pLogic->sortData(); isEdit=false; pLineEditSum->clear(); setWorkView(); dataIsLoaded(); } void MoneyRepositaryWidget::deleteRecord(){ pLogic->removeRow(pTable->selectionModel()->currentIndex().row()); dataIsLoaded(); } void MoneyRepositaryWidget::editRecord(){ isEdit=true; setEditView(); } void MoneyRepositaryWidget::setEditView(){ pBtnCnacel->setEnabled(true); pBtnSave->setEnabled(false); pBtnEdit->setEnabled(false); pBtnDelete->setEnabled(false); pBtnAdd->setText(tr("Сохранить изменения")); unsigned int row=0; if(pTable->selectionModel()->hasSelection()) row=pTable->selectionModel()->currentIndex().row(); RecordString rec=pLogic->getData(row); pTimeEdit->setDate(QDate::fromString(QString::fromStdString(rec.getDate()),"yyyy-MM-dd")); pCbxType->setCurrentText(QString::fromStdString(rec.getType())); pCbxCategory->setCurrentText(QString::fromStdString(rec.getCategory())); pCbxDescription->setCurrentText(QString::fromStdString(rec.getDescription())); pLineEditSum->setText(QString::number(rec.getSum())); pCbxCurrency->setCurrentText(QString::fromStdString(rec.getCurrency())); } void MoneyRepositaryWidget::setWorkView(){ pBtnCnacel->setEnabled(false); pBtnSave->setEnabled(true); pBtnEdit->setEnabled(true); pBtnDelete->setEnabled(true); pBtnAdd->setText(tr("Добавить запись")); } void MoneyRepositaryWidget::cancelEditRecord(){ isEdit=false; setWorkView(); } void MoneyRepositaryWidget::dataIsLoaded(){ updateTable(); pTimeEdit->setDate(QDate::currentDate()); updateCbxCategory(); emit tableChanged(); } void MoneyRepositaryWidget::updateCbxCategory(){ pCbxCategory->clear(); pCbxCategory->addItems(convertToQList(pLogic->getDataCategories(pCbxType->currentText().toStdString()))); categoryChanged(); } QStringList MoneyRepositaryWidget::convertToQList(const std::list<std::string>& list) const{ QStringList qList; for(const auto& i:list) qList.push_back(QString::fromStdString(i)); return qList; } void MoneyRepositaryWidget::categoryChanged(){ pCbxDescription->clear(); pCbxDescription->addItems(convertToQList(pLogic->getDataDescriptions(pCbxCategory->currentText().toStdString()))); } void MoneyRepositaryWidget::updateTable(){ unsigned int rows=pLogic->rowsCount(); pTable->setRowCount(rows); pTable->setColumnCount(pLogic->columnsCount()); for(unsigned int row = 0; row<rows; row++){ RecordString rec=pLogic->getData(row); QTableWidgetItem* item0 = new QTableWidgetItem(QString::fromStdString(rec.getDate())); pTable->setItem(row,0,item0); QTableWidgetItem* item1 = new QTableWidgetItem(QString::fromStdString(rec.getType())); pTable->setItem(row,1,item1); QTableWidgetItem* item2 = new QTableWidgetItem(QString::fromStdString(rec.getCategory())); pTable->setItem(row,2,item2); QTableWidgetItem* item3 = new QTableWidgetItem(QString::fromStdString(rec.getDescription())); pTable->setItem(row,3,item3); QTableWidgetItem* item4 = new QTableWidgetItem(QString::number(rec.getSum())); pTable->setItem(row,4,item4); QTableWidgetItem* item5 = new QTableWidgetItem(QString::fromStdString(rec.getCurrency())); pTable->setItem(row,5,item5); } setTableHeader(); setTableDimensions(); } void MoneyRepositaryWidget::setTableHeader(){ std::vector<std::string> header{"Дата","Тип","Категория","Описание","Сумма","Валюта"}; int columnsCount=header.size(); for(int i=0;i<columnsCount;i++){ QTableWidgetItem* item=new QTableWidgetItem(header[i].c_str()); pTable->setHorizontalHeaderItem(i,item); } pTable->verticalHeader()->hide(); } void MoneyRepositaryWidget::setTableDimensions(){ pTable->setColumnWidth(0, pTable->width() * 0.1); pTable->setColumnWidth(1, pTable->width() * 0.1); pTable->setColumnWidth(2, pTable->width() * 0.28); pTable->setColumnWidth(3, pTable->width() * 0.3); pTable->setColumnWidth(4, pTable->width() * 0.1); pTable->setColumnWidth(5, pTable->width() * 0.1); } void MoneyRepositaryWidget::saveData(){ pLogic->saveData(); } <file_sep>#pragma once #include <QtWidgets> #include <memory> #include <QDate> #include "SRC/BusinessLogic/BusinessLogic.h" #include "SRC/GUI/MoneyRepositaryWidget.h" #include "SRC/GUI/ReportWidget.h" #include "SRC/GUI/UserWidget.h" class MainWindow : public QWidget{ Q_OBJECT public: MainWindow(std::shared_ptr<AbstractBusinessLogic> logic); private slots: void moneyShow()const; void userShow()const; void reportShow(); void dataIsLoaded(); void exitUser()const; void balance(); private: std::shared_ptr<AbstractBusinessLogic> pLogic; QPushButton* pBtnUser; QPushButton* pBtnMoney; QPushButton* pBtnReport; QLabel* pLblBalance; MoneyRepositaryWidget* pWdgMoney; ReportWidget* pWdgReport; UserWidget* pWdgUser; void createWindows(); void drawMainWindow(); void connectWindows(); }; <file_sep>#pragma once #include <wchar.h> #include <string> #include <fstream> #include <codecvt> #include "SRC/BusinessLogic/Report.h" #include "SRC/BusinessLogic/RecordString.h" #include <sstream> #include <locale> class ReportSaveTxt{ public: ReportSaveTxt(const std::shared_ptr<Report>& rep); void saveTxt(const std::string& filename, const std::string& userName, const std::string& currentDate); private: std::shared_ptr<Report> pReport; int fieldTypeLength=7; //size of "Прибыль" int fieldCategoryLength=9; //size of "Категория" int fieldDescriptionLength=8; //size of "Описание" int fieldSumLength=5; //size of "Сумма" int stringLength(const std::string& str)const; std::string row(const int row)const; void maxLengthFields(); std::string doubleToString(const double value)const; std::string headerReport(const std::string& userName,const std::string& currentDate)const; std::string stringFromVector(const std::vector<std::string>& vec)const; }; <file_sep>#include "RecordsOperations.h" RecordsOperations::RecordsOperations(std::shared_ptr<AbstractData>& data) : pData(data){ } std::list<std::string> RecordsOperations::getCategories(const std::string& type) const{ std::list<std::string> list; unsigned int rows=pData->rows(); for(unsigned int i=0;i<rows;i++){ RecordString rec=pData->getRecord(i); if(type==rec.getType()){ std::string category=rec.getCategory(); bool isUnique=true; for(const auto& j:list){ if(j==category) isUnique=false; } if(isUnique) list.push_back(category); } } list.sort(); return list; } std::list<std::string> RecordsOperations::getDescriptions(const std::string& category) const{ std::list<std::string> list; unsigned int rows=pData->rows(); for(unsigned int i=0;i<rows;i++){ RecordString rec=pData->getRecord(i); if(category==rec.getCategory()){ std::string description=rec.getDescription(); bool isUnique=true; for(const auto& j:list){ if(j==description) isUnique=false; } if(isUnique) list.push_back(description); } } list.sort(); return list; } std::list<std::string> RecordsOperations::getCurrencies()const { std::list<std::string> list; unsigned int rows=pData->rows(); for(unsigned int i=0;i<rows;i++){ RecordString rec=pData->getRecord(i); std::string currency=rec.getCurrency(); bool isUnique=true; for(const auto& j:list){ if(j==currency) isUnique=false; } if(isUnique) list.push_back(currency); } list.sort(); return list; } <file_sep>#pragma once #include <QtWidgets> class PasswordWidget : public QDialog{ Q_OBJECT public: PasswordWidget(); signals: void clickedOk(const QString&,const QString&,PasswordWidget*); private slots: void slotClickedOk(); private: QPushButton* pBtnOK; QLineEdit* pLeName; QLineEdit* pLePassword; QLineEdit* pLePasswordConfirmation; void drawWindow(); }; <file_sep>#pragma once #include <QComboBox> #include <QtWidgets> #include <QVBoxLayout> #include "SRC/BusinessLogic/AbstractBusinessLogic.h" class GraphicWidget : public QWidget { Q_OBJECT public: GraphicWidget(std::shared_ptr<AbstractBusinessLogic> logic,QWidget *parent); signals: private: std::shared_ptr<AbstractBusinessLogic> pLogic; QComboBox* pCbxCurrency; QStringList convertToQList(const std::list<std::string>& list)const; }; <file_sep>#pragma once #include "SRC/DataBase/Data.h" #include "SRC/BusinessLogic/RecordString.h" #include <list> #include <memory> class Report{ public: explicit Report(std::shared_ptr<AbstractData>& data); RecordString getRow(const int row) const; int rowsCount()const; std::list<std::string> getCategories(const bool profit,const bool loss)const; std::list<std::string> getDescriptions(const std::vector<std::string>& categories)const; void filterDB(const std::string& dateFrom, const std::string& dateTo, const std::pair<bool, bool>& type, const std::vector<std::string>& category, const std::vector<std::string>& description, const double &sumFrom, const double &sumTo, const std::vector<std::string> &currency); std::pair<std::string,std::string> dateMinMax()const; std::pair<double, double> sumMinMax()const; void update(); std::string getDateFrom()const; std::string getDateTo()const; std::pair<bool,bool> getType()const; std::vector<std::string> getCategory()const; std::vector<std::string> getDescription()const; double getSumFrom()const; double getSumTo()const; std::vector<std::string> getCurrency()const; private: int size; std::shared_ptr<AbstractData> pData; std::vector<bool> filter; void sizeReport(); bool dateInRange(const std::string& date,const std::string& dateFrom,const std::string& dateTo)const; bool typeInRange(const std::string& type, const std::pair<bool,bool> typeFilter)const; bool valueInRange(const std::string& category,const std::vector<std::string>& categoryFilter)const; bool sumInRange(const double &sum, const double &sumFrom, const double &sumTo)const; std::string dateFrom; std::string dateTo; std::pair<bool,bool> type; std::vector<std::string> category; std::vector<std::string> description; double sumFrom; double sumTo; std::vector<std::string> currency; }; <file_sep>#include "User.h" constexpr char separator='~'; User::User(const std::string &log, const std::string &pass):login(log),password(pass){ } bool User::operator==(const User& rhs) const{ return (login==rhs.login)&&(password==rhs.password); } bool User::operator!=(const User& rhs) const{ return !(*this==rhs); } bool User::operator<(const User& rhs)const{ return login<rhs.login; } void User::clear(){ login.clear(); password.clear(); } bool User::isNotEmpty() const{ return (login.size()==0)?false:true; } std::string User::getLogin() const{ return login; } std::istream& operator>>(std::istream& stream,User& user){ user.clear(); char c; while(stream.get(c) && c!=separator){ user.login += c; } while(stream.get(c) && c!=separator){ user.password += c; } return stream; } std::ostream& operator<<(std::ostream& stream,const User& user){ stream<<user.login<<separator<<user.password<<separator; return stream; } <file_sep>#pragma once #include <memory> #include <QtPrintSupport> #include <QPainter> #include <QFont> #include <QComboBox> #include <QObject> #include "SRC/BusinessLogic/Report.h" #include "SRC/BusinessLogic/RecordString.h" class ReportPrint:public QObject{ Q_OBJECT public: explicit ReportPrint(std::shared_ptr<Report>& report); ~ReportPrint(); void printReport(const std::string& userName,const std::string& currentDate); private slots: void printReport(); private: std::shared_ptr<Report> pReport; QPrinter* printer; QPainter* painter; QPrintPreviewDialog* printDialog; void calculatePageParameters(); void printHeader(double& yPosition,const std::string& userName,const std::string& currentDate); void printTable(double& yPosition); void nextRow(double& yPosition)const; /*print settings*/ double leading; const std::string font="Arial"; const int fontSize=12; double pageWidth; double pageHeight; double leftBorder; double rightBorder; double verticalBorder; }; <file_sep>Программа должна решать следующие проблемы: 1. Учет расходов. 2. Учет доходов. 3. Планирование. 4. Составление отчетов. Требования к программе: 1. Поддержка работы с несколькими пользователями. 2. Поддержка разных валют. 3. Запись доход состоит из 5 полей: дата, сумма, валюта, категория, описание 4. Запись расход состоит из 5 полей: дата, сумма, валюта, категория, описание 5. Начальная сумма. 6. Текущий баланс. 7. Защита данных паролем. 8. Отчеты: временные, по категориям, по доходы/расходы, валюта, суммарный. 9. Для одного клиенты разные счета в валютах и безнал. С возможностью отчета суммарных или выборочных. 10. Планирование: предполагаемые доходы (зарплата), расходы (кредит,рассрочка, долг). Периодические. 11. Напоминания. 12. Печать и сохранять отчеты в читабельном виде. 13. Графичекое отображение информации. Действующий субъект: пользователь. Сценарии: 1. Ввод данных расходов. 2. Ввод данных доходов. 3. Задание условий отчета. 4. Печать отчета. 5. Сохранение отчета. 6. Ввод пароля. 7. Создание учетной записи пользователя. 8. Создание валютного счета пользователя. 9. Создание категории доходов пользователя. 10. Создание категории расходов пользователя. 11. Сохранение данных в бинарный файл. 12. Получение актуальных курсов. 13. Установка напоминаний. 14. Установка планируемых доходов. 15. Установка планируемых расходов. 16. Подтверждение или коррекция запланированого дохода с фактическим. 17. Подтверждение или коррекция запланированого расхода с фактическим. 18. Вывод отчета в графическом представлении. 19. Экспортирование данных в эксель. Список существительных: Слой представления Window "Main" Экран интерфейса пользователя. Window "Money Repository" Экран доходов/расходов. Window "User Registration" Экран создания учетной записи пользователя. Window "Currency Account" Экран создания/редактирования валютного счета пользователя. Window "Data Input" Экран ввода доходов/расходов. Window "Planning" Экран планирования доходов/расходов Window "Password" Экран ввода пароля. Window "Report" Экран отчета. Window "Chart Report" Экран графика отчета. Window "Category" Экран создания и правка категории доходов/расходов. Window "Setting Reminder" Экран установки напоминаний. Window "Reminder" Экран напоминаний. Window "Correction" Экран подтверждения или коррекции запланированного дохода/расхода с фактическим. Window "Print Report" Экран печати отчета. Window "Save Report" Экран сохранения отчета. Слой данных Record Дата. Сумма. Валюта. Категория. Описание. Слой бизнес-логики Money Repository Ввод доходов. Ввод расходов. Правка расходов. Правка доходов. Report Builder Формирование отчета. Chart Builder Построение графика отчета. Report Repository Сохранение отчета. Report Printer Печать отчета. Report Importer Экспорт отчета/данных в эксель. Balance Calculator Отображение текущего баланса за месяц (или за этот месяц). Currency Rate Repository Ввод курса на текущее число. Currency Rate Loader Загрузка курсов с ресурса. <file_sep>#pragma once #include "SRC/DataBase/Data.h" #include "SRC/DataBase/DataOperations.h" #include "SRC/BusinessLogic/BusinessLogic.h" #include "SRC/GUI/MainWindow.h" class ApplicationBuilder{ public: ApplicationBuilder(); private: //std::shared_ptr<Data> makeData(); std::shared_ptr<Data> pData; std::shared_ptr<DataFileOperations> pOperations; std::shared_ptr<BusinessLogic> pLogic; std::unique_ptr<MainWindow> pMainWindow; }; <file_sep>#pragma once #include <vector> #include <algorithm> #include "SRC/DataBase/AbstractData.h" #include "SRC/DataBase/Record.h" class Data:public AbstractData{ public: unsigned int rows()const override; unsigned int columns()const override; void remove(const int row) override; void sort() override; const RecordString getRecord(const unsigned int row)const override; void setRecord(const unsigned int row,const RecordString& record) override; void clear()override; private: std::vector<Record> data; std::list<std::string> getAllCurrencies()const override; std::list<std::string> getAllTypes()const override; }; <file_sep>#include "UserWidget.h" UserWidget::UserWidget(std::shared_ptr<AbstractBusinessLogic> logic, QWidget* parent) : QWidget(parent), pLogic(logic){ drawWindow(); connectButtons(); setStartView(); } void UserWidget::drawWindow(){ pBtnNewUser=new QPushButton(tr("Регистрация")); pBtnLogIn=new QPushButton(tr("Войти")); pBtnDeleteUser=new QPushButton(tr("Удалить пользователя")); pBtnChangeUser=new QPushButton(tr("Выйти/Сменить пользователя")); pBtnChangePassword=new QPushButton(tr("Сменить пароль")); pCbxUserName=new QComboBox; pLedPassword=new QLineEdit; pLedPassword->setEchoMode(QLineEdit::Password); pLblUserName=new QLabel(tr("Выберите имя из списка:")); pLblPassword=new QLabel(tr("Введите пароль:")); QGridLayout* pGrdMain=new QGridLayout; pGrdMain->addWidget(pLblUserName,1,1,Qt::AlignRight); pGrdMain->addWidget(pLblPassword,2,1,Qt::AlignRight); pGrdMain->addWidget(pCbxUserName,1,2); pGrdMain->addWidget(pLedPassword,2,2); pGrdMain->addWidget(pBtnNewUser,1,3); pGrdMain->addWidget(pBtnLogIn,2,3); pGrdMain->addWidget(pBtnChangeUser,4,2); pGrdMain->addWidget(pBtnDeleteUser,4,1); pGrdMain->addWidget(pBtnChangePassword,4,3); pGrdMain->setRowStretch(3,1); pGrdMain->setColumnStretch(4,3); pGrdMain->setRowStretch(5,12); pGrdMain->setColumnStretch(0,1); pGrdMain->setRowStretch(0,4); setLayout(pGrdMain); } void UserWidget::connectButtons(){ QObject::connect(pBtnNewUser,SIGNAL(clicked()),SLOT(newUserClicked())); QObject::connect(pBtnLogIn,SIGNAL(clicked()),SLOT(logIn())); QObject::connect(pBtnChangeUser,SIGNAL(clicked()),SLOT(changeUser())); QObject::connect(pBtnDeleteUser,SIGNAL(clicked()),SLOT(deleteUser())); QObject::connect(pBtnChangePassword,SIGNAL(clicked()),SLOT(changePassword())); QObject::connect(pCbxUserName,SIGNAL(currentIndexChanged(int)),SLOT(clearPassword())); } void UserWidget::clearPassword(){ pLedPassword->clear(); } void UserWidget::setStartView(){ emit exitUser(); pCbxUserName->clear(); pCbxUserName->addItems(convertToQstringList(pLogic->getUsersNames())); if(!pCbxUserName->count()) pBtnLogIn->setEnabled(false); else pBtnLogIn->setEnabled(true); pBtnNewUser->setEnabled(true); pBtnDeleteUser->setEnabled(true); pCbxUserName->setEnabled(true); pLedPassword->setEnabled(true); pBtnChangeUser->setEnabled(false); pBtnChangePassword->setEnabled(false); } void UserWidget::newUserClicked(){ PasswordWidget wdgPassword; wdgPassword.show(); QObject::connect(&wdgPassword,SIGNAL(clickedOk(const QString&,const QString&,PasswordWidget*)), SLOT(addUser(const QString&,const QString&))); wdgPassword.exec(); } void UserWidget::addUser(const QString& login,const QString& password){ if(pLogic->isUserCreated(login.toStdString(),password.toStdString())){ pCbxUserName->clear(); pCbxUserName->addItems(convertToQstringList(pLogic->getUsersNames())); setWorkView(); emit dataIsLoaded(); } else { QMessageBox::information(this,tr("Сообщение"),tr("Пользователь с таким именем уже существует")); newUserClicked(); } } void UserWidget::logIn(){ if(pLogic->loadData(pCbxUserName->currentText().toStdString(),pLedPassword->text().toStdString())){ setWorkView(); emit dataIsLoaded(); } else { QMessageBox::information(this,tr("Сообщение"),tr("Неверный пароль!")); pLedPassword->clear(); } } void UserWidget::setWorkView(){ pBtnChangeUser->setEnabled(true); pBtnNewUser->setEnabled(false); pBtnLogIn->setEnabled(false); pBtnDeleteUser->setEnabled(false); pCbxUserName->setEnabled(false); pLedPassword->setEnabled(false); pBtnChangePassword->setEnabled(true); } void UserWidget::changeUser(){ pLogic->clearData(); clearPassword(); setStartView(); } void UserWidget::deleteUser(){ if(pLogic->deleteUser(pCbxUserName->currentText().toStdString(),pLedPassword->text().toStdString())) setStartView(); else { QMessageBox::information(this,tr("Сообщение"),tr("Неверный пароль!")); pLedPassword->clear(); } } void UserWidget::changePassword(){ ChangePasswordWidget wdgChangePassword; wdgChangePassword.show(); QObject::connect(&wdgChangePassword,SIGNAL(clickedOk(const QString&,const QString&)), SLOT(changingPassword(const QString&,const QString&))); wdgChangePassword.exec(); } void UserWidget::changingPassword(const QString &oldPassword, const QString &newPassword){ if(pLogic->changePassword(pCbxUserName->currentText().toStdString(),oldPassword.toStdString(),newPassword.toStdString())){ QMessageBox::information(this,tr("Сообщение"),tr("Пароль изменен")); } else { QMessageBox::information(this,tr("Сообщение"),tr("Неверный пароль!")); } } QStringList UserWidget::convertToQstringList(const std::list<std::string>& listStd) const{ QStringList list; for(const auto& i:listStd) list.push_back(QString::fromStdString(i)); return list; } <file_sep>#pragma once #include <fstream> #include <memory> #include <string> #include "SRC/DataBase/Data.h" #include "SRC/DataBase/AbstractDataFileOperations.h" class DataFileOperations: public AbstractDataFileOperations{ public: explicit DataFileOperations(std::shared_ptr<AbstractData> data):pData(data){} void saveToFile(std::string fileName)const override; void loadFromFile(std::string fileName) override; void deleteFile(std::string fileName) override; private: std::shared_ptr<AbstractData> pData; const char separatorRecord='~'; void save(std::ofstream& dataStream,const Record&) const; Record load(std::ifstream& dataStream); }; <file_sep>#pragma once #include <string> #include <iostream> class User{ public: User(){} User(const std::string& log,const std::string& pass); bool operator==(const User& rhs) const; bool operator!=(const User& rhs) const; bool operator<(const User& rhs)const; bool isNotEmpty() const; std::string getLogin() const; friend std::istream& operator>>(std::istream& stream,User& user); friend std::ostream& operator<<(std::ostream& stream,const User& user); private: std::string login; std::string password; void clear(); }; <file_sep>#include "ReportSavePdf.h" ReportSavePdf::ReportSavePdf(const std::shared_ptr<Report> &rep) : pReport(rep){ } std::string ReportSavePdf::doubleToString(const double value)const{ std::stringstream ss; std::string string; ss<<value; ss>>string; return string; } void ReportSavePdf::savePDF(const std::string& filename, const std::string& userName, const std::string& currentDate){ /* creating and settings pdf*/ HPDF_Doc pdf=HPDF_New(NULL,NULL); HPDF_SetCompressionMode (pdf, HPDF_COMP_ALL); HPDF_UseUTFEncodings(pdf); HPDF_SetCurrentEncoder(pdf, encoding); const char* fontName = HPDF_LoadTTFontFromFile (pdf, pathFont, HPDF_TRUE); font = HPDF_GetFont (pdf, fontName,encoding); newPage(pdf); HPDF_REAL yPosition=reportHeader(userName,currentDate,pdf); report(pdf,yPosition); HPDF_SaveToFile (pdf, filename.c_str()); HPDF_Free (pdf); } void ReportSavePdf::printVector(const std::vector<std::string>& vec, std::string& str, HPDF_REAL& yPosition, HPDF_Doc& pdf){ HPDF_Page page=HPDF_GetCurrentPage(pdf); if(vec[0]=="Все") { if(yPosition<verticalBorder){ page = newPage(pdf); yPosition=pageHeight-verticalBorder-leading; } str+="все"; HPDF_Page_BeginText (page); HPDF_Page_TextOut (page,leftBorder,yPosition,str.c_str()); HPDF_Page_EndText (page); yPosition-=leading; return; } HPDF_Page_BeginText (page); HPDF_Page_TextOut (page,leftBorder,yPosition,str.c_str()); yPosition-=leading; for(auto i:vec){ if(yPosition<verticalBorder){ HPDF_Page_EndText (page); page = newPage(pdf); yPosition=pageHeight-verticalBorder-leading; HPDF_Page_BeginText (page); } HPDF_Page_TextOut (page,leftBorder+leading,yPosition,i.c_str()); yPosition-=leading; } HPDF_Page_EndText (page); return; } HPDF_Page ReportSavePdf::newPage(HPDF_Doc& pdf){ HPDF_Page page = HPDF_AddPage (pdf); HPDF_Page_SetSize (page, HPDF_PAGE_SIZE_A4, HPDF_PAGE_PORTRAIT); HPDF_Page_SetFontAndSize (page, font, fontSize); HPDF_Page_SetTextLeading(page,leading); pageWidth=HPDF_Page_GetWidth(page); pageHeight=HPDF_Page_GetHeight(page); calculateParameters(pageWidth,pageHeight); return page; } HPDF_REAL ReportSavePdf::reportHeader(const std::string& userName,const std::string& currentDate,HPDF_Doc& pdf){ HPDF_Page page=HPDF_GetCurrentPage(pdf); HPDF_Page_BeginText (page); HPDF_REAL yPosition=pageHeight-verticalBorder-leading; HPDF_REAL tw=HPDF_Page_TextWidth(page,"Отчет"); HPDF_Page_TextOut (page,(pageWidth-tw+leftBorder-rightBorder)/2,yPosition,"Отчет"); yPosition-=leading; std::string str="Пользователь: "+userName; HPDF_Page_TextOut (page,leftBorder,yPosition,str.c_str()); yPosition-=leading; str="Дата отчета: "+currentDate; HPDF_Page_TextOut (page,leftBorder,yPosition,str.c_str()); yPosition-=leading; tw=HPDF_Page_TextWidth(page,"Установки фильтра"); HPDF_Page_TextOut (page,(pageWidth-tw+leftBorder-rightBorder)/2,yPosition,"Установки фильтра"); yPosition-=leading; str="Дата от: "+pReport->getDateFrom()+" Дата до: "+pReport->getDateTo(); HPDF_Page_TextOut (page,leftBorder,yPosition,str.c_str()); yPosition-=leading; str="Тип: "; if((pReport->getType().first==true)&&(pReport->getType().second==false)) str+="Прибыль"; if((pReport->getType().first==false)&&(pReport->getType().second==true)) str+="Убыток"; if((pReport->getType().first==true)&&(pReport->getType().second==true)) str+="все"; HPDF_Page_TextOut (page,leftBorder,yPosition,str.c_str()); yPosition-=leading; str="Сумма от: "+doubleToString(pReport->getSumFrom())+" Сумма до: "+doubleToString(pReport->getSumTo()); HPDF_Page_TextOut (page,leftBorder,yPosition,str.c_str()); yPosition-=leading; HPDF_Page_EndText (page); str="Валюты: "; printVector(pReport->getCurrency(),str,yPosition,pdf); str="Категории: "; printVector(pReport->getCategory(),str,yPosition,pdf); str="Описания: "; printVector(pReport->getDescription(),str,yPosition,pdf); return yPosition; } void ReportSavePdf::report(HPDF_Doc& pdf, HPDF_REAL& yPosition){ HPDF_Page page=HPDF_GetCurrentPage(pdf); HPDF_Page_BeginText (page); tableHeader(page,yPosition); for(int row=0;row<pReport->rowsCount();++row){ if(yPosition<verticalBorder){ HPDF_Page_EndText (page); page = newPage(pdf); yPosition=pageHeight-verticalBorder-leading; HPDF_Page_BeginText (page); tableHeader(page,yPosition); } RecordString recordString=pReport->getRow(row); HPDF_Page_TextOut (page,leftBorder,yPosition,recordString.getDate().c_str()); HPDF_Page_TextOut (page,xType,yPosition,recordString.getType().c_str()); HPDF_Page_TextOut (page,xCategory,yPosition,recordString.getCategory().c_str()); HPDF_Page_TextOut (page,xDescription,yPosition,recordString.getDescription().c_str()); HPDF_Page_TextOut (page,xSum,yPosition,doubleToString(recordString.getSum()).c_str()); HPDF_Page_TextOut (page,xCurrency,yPosition,recordString.getCurrency().c_str()); yPosition-=leading; } HPDF_Page_EndText (page); } void ReportSavePdf::tableHeader(const HPDF_Page &page, HPDF_REAL& yPosition)const{ HPDF_Page_TextOut (page,leftBorder,yPosition,"Дата"); HPDF_Page_TextOut (page,xType,yPosition,"Тип"); HPDF_Page_TextOut (page,xCategory,yPosition,"Категория"); HPDF_Page_TextOut (page,xDescription,yPosition,"Описание"); HPDF_Page_TextOut (page,xSum,yPosition,"Сумма"); HPDF_Page_TextOut (page,xCurrency,yPosition,"Валюта"); yPosition-=leading; } void ReportSavePdf::calculateParameters(const HPDF_REAL& pageWidth,const HPDF_REAL& pageHeight){ leftBorder=static_cast<HPDF_REAL>(kLeftBorder*pageWidth); rightBorder=static_cast<HPDF_REAL>(kRightBorder*pageWidth); xType=static_cast<HPDF_REAL>(0.24*pageWidth); xCategory=static_cast<HPDF_REAL>(0.35*pageWidth); xDescription=static_cast<HPDF_REAL>(0.56*pageWidth); xSum=static_cast<HPDF_REAL>(0.78*pageWidth); xCurrency=static_cast<HPDF_REAL>(0.88*pageWidth); verticalBorder=static_cast<HPDF_REAL>(kVerticalBorder*pageHeight); } <file_sep>#pragma once #include <QtWidgets> #include <QPageSize> #include "SRC/BusinessLogic/BusinessLogic.h" #include <QtPrintSupport/QPrinter> #include <QtPrintSupport/QPrintPreviewDialog> #include "SRC/GUI/GraphicWidget.h" class ReportWidget : public QWidget{ Q_OBJECT public: ReportWidget(std::shared_ptr<AbstractBusinessLogic> logic,QWidget* parent); bool eventFilter(QObject*, QEvent*)override; void updateTable(); void fillFields(); private slots: void filter(); void fillComboBoxDescription(); void fillComboBoxCategory(); void categoryChecked(QStandardItem *item); void descriptionChecked(QStandardItem *item); void currencyChecked(QStandardItem *item); void resetFilter(); void saveTxt(); void savePDF(); void printReport(); void btnPrintClicked(); void btnChartClicked(); private: std::shared_ptr<AbstractBusinessLogic> pLogic; GraphicWidget* pGraphicWidget; QTableWidget* pTable; QPushButton* pBtnSaveTxt; QPushButton* pBtnSavePDF; QPushButton* pBtnPrint; QPushButton* pBtnChart; QPushButton* pBtnReset; QDateEdit* pTimeEditTo; QDateEdit* pTimeEditFrom; QCheckBox *pChbxTypeProfit; QCheckBox *pChbxTypeLoss; QComboBox* pCbxCategory; QStandardItemModel* pModelCategory; QComboBox* pCbxDescription; QStandardItemModel* pModelDescription; QLineEdit* pLineEditSumFrom; QLineEdit* pLineEditSumTo; QComboBox* pCbxCurrency; QStandardItemModel* pModelCurrency; void drawWindow(); void connectButtons(); std::pair<bool,bool> typeToReport()const; std::vector<std::string> getComboBoxCheckedList(const QComboBox *combobox)const; void setTableDimensions(); void setTableHeader(); void fillDate(); void fillSum(); void fillComboBoxCurrency(); void checkControl(QStandardItemModel* model,QStandardItem* item); void setCheckAll(QStandardItemModel* model,Qt::CheckState state); void fillComboBox(QStandardItemModel* model,std::list<std::string>& list); /*print functions*/ void printHeader(QPainter& painter, double &yPosition); void printTable(QPainter& painter, double &yPosition); void calculatePageParameters(); void printComboBoxCheckedList(const QComboBox* combobox,QPainter& painter,double& yPosition) const; void nextRow(double& yPosition) const; /*print settings*/ std::unique_ptr<QPrinter> printer; double leading; const QString font="Arial"; const int fontSize=12; double pageWidth; double pageHeight; double leftBorder; double rightBorder; double verticalBorder; }; <file_sep>#pragma once #include <string> class AbstractDataFileOperations{ public: virtual void saveToFile(std::string fileName)const=0; virtual void loadFromFile(std::string fileName)=0; virtual void deleteFile(std::string fileName)=0; }; <file_sep>#pragma once #include <QtWidgets> #include <memory> #include <QString> #include <QStringList> #include <list> #include <string> #include "SRC/BusinessLogic/BusinessLogic.h" #include "SRC/GUI/PasswordWidget.h" #include "SRC/GUI/ChangePasswordWidget.h" class UserWidget : public QWidget{ Q_OBJECT public: UserWidget(std::shared_ptr<AbstractBusinessLogic> logic,QWidget* parent); signals: void exitUser(); void dataIsLoaded(); private slots: void newUserClicked(); void logIn(); void changeUser(); void addUser(const QString& login,const QString& password); void deleteUser(); void changePassword(); void changingPassword(const QString& oldPassword, const QString& newPassword); void clearPassword(); private: std::shared_ptr<AbstractBusinessLogic> pLogic; QPushButton* pBtnNewUser; QPushButton* pBtnLogIn; QPushButton* pBtnDeleteUser; QPushButton* pBtnChangeUser; QPushButton* pBtnChangePassword; QLineEdit* pLedPassword; QComboBox* pCbxUserName; QLabel* pLblUserName; QLabel* pLblPassword; void drawWindow(); void connectButtons(); void setStartView(); void setWorkView(); QStringList convertToQstringList(const std::list<std::string>& listStd)const; }; <file_sep>#pragma once #include <string> #include <sstream> #include <list> #include "SRC/BusinessLogic/RecordString.h" class Record{ public: Record():sum(0){}; Record(const RecordString&); enum class Type{ PROFIT=1, LOSS }; enum class Currency{ USD=1, BYR, RUB, EUR }; unsigned int columns()const; std::string getDate()const; Type getType()const; std::string getCategory()const; std::string getDescription()const; double getSum()const; Record::Currency getCurrency()const; void setDate(const std::string& d); void setType(const Record::Type t); void setCategory(const std::string& c); void setDescription(const std::string& d); void setSum(const double s); void setCurrency(const Record::Currency c); bool operator<(const Record& rhs) const; RecordString convertToString()const; std::list<std::string> getAllCurrencies()const; std::list<std::string> getAllTypes()const; private: std::string date; Type type; std::string category; std::string description; double sum; Currency currency; }; <file_sep>#include "UserFileOperations.h" UserFileOperations::UserFileOperations(){ loadUsers(); } bool UserFileOperations::isUserCreated(const std::string& login, const std::string& password){ User user(login,password); if(userIsOnList(user)){ return false; } users.push_back(user); saveUsers(); currentUser=user; return true; } void UserFileOperations::saveUsers(){ std::sort(users.begin(),users.end()); std::ofstream settings{settingsFileName}; if(!settings) throw "File wasn't created"; for(const User& i:users) settings<<i; } bool UserFileOperations::userIsOnList(const User& user) const{ for(const auto& i:users) if(user.getLogin()==i.getLogin()) return true; return false; } void UserFileOperations::loadUsers(){ users.clear(); std::ifstream settings{settingsFileName}; if(settings){ while(!settings.eof()){ User userRead; settings>>userRead; if(userRead.isNotEmpty()) users.push_back(userRead); } } //else throw "File doesn't exist"; } std::list<std::string> UserFileOperations::getUsersNames() const{ std::list<std::string> usersList; for(const auto& i:users) usersList.push_back(i.getLogin()); return usersList; } bool UserFileOperations::checkPassword(const User& userChecking){ for(const auto& i:users){ if(userChecking==i){ currentUser=userChecking; return true; } } return false; } bool UserFileOperations::deleteUser(const std::string& login,const std::string& password){ User userDeleting(login,password); if (checkPassword(userDeleting)){ unsigned int countUsers=users.size(); for(unsigned int i=0;i<countUsers;i++){ if(userDeleting==users[i]){ users.erase(users.begin()+i); saveUsers(); return true; } } } return false; } bool UserFileOperations::changedPassword(const std::string &login, const std::string &oldPassword, const std::string &newPassword){ User userOldPassword(login,oldPassword); User userNewPassword(login,newPassword); unsigned int countUsers=users.size(); for(unsigned int i=0; i<countUsers;i++){ if(users[i]==userOldPassword){ users[i]=userNewPassword; saveUsers(); currentUser=userNewPassword; return true; } } return false; } std::string UserFileOperations::getUserName()const{ return currentUser.getLogin(); } <file_sep>#pragma once #include <list> #include <string> #include "SRC/BusinessLogic/RecordString.h" class AbstractData{ public: virtual unsigned int rows()const=0; virtual unsigned int columns()const=0; virtual void remove(const int row)=0; virtual void sort()=0; virtual const RecordString getRecord(const unsigned int row)const=0; virtual void setRecord(const unsigned int row,const RecordString& record)=0; virtual void clear()=0; virtual std::list<std::string> getAllCurrencies()const=0; virtual std::list<std::string> getAllTypes()const=0; }; <file_sep>#include "SRC/ApplicationBuilder.h" #include <QApplication> int main(int argc, char *argv[]){ QApplication a(argc, argv); ApplicationBuilder ab; return a.exec(); } <file_sep>#include "BalanceCalculator.h" BalanceCalculator::BalanceCalculator(std::shared_ptr<AbstractData>& data,std::shared_ptr<RecordsOperations>& operations): pData(data),pOperations(operations){} std::string BalanceCalculator::balance(const BalanceCalculator::Time period, const std::string& currency)const{ std::string balance; if(period==BalanceCalculator::Time::allTime) balance=balanceCalculate(pData->getRecord(0).getDate(),currency); if(period==BalanceCalculator::Time::year) balance=balanceCalculate(minusYear(),currency); if(period==BalanceCalculator::Time::month) balance=balanceCalculate(minusMonth(),currency); return balance; } std::string BalanceCalculator::minusYear() const{ std::stringstream ss; ss<<currentDate.substr(0,4); int currentYear; ss>>currentYear; currentYear--; ss.clear(); ss<<currentYear; std::string dateMinusYear; ss>>dateMinusYear; dateMinusYear+=currentDate.substr(4,6); return dateMinusYear; } std::string BalanceCalculator::balanceCalculate(const std::string& dateFrom,const std::string& currency)const{ double balanceDouble=0; unsigned int rows=pData->rows(); for(unsigned int i=0;i<rows;i++){ RecordString rec=pData->getRecord(i); std::string date=rec.getDate(); if((dateFrom<=date && date<=currentDate)&&(currency==rec.getCurrency())){ if(rec.getType()==profit) balanceDouble+=rec.getSum(); if(rec.getType()==loss) balanceDouble-=rec.getSum(); } } std::string balance; std::stringstream ss; ss<<balanceDouble; ss>>balance; return balance; } std::string BalanceCalculator::minusMonth()const{ std::stringstream ss; ss<<currentDate.substr(5,2); int currentMonth; ss>>currentMonth; if(currentMonth==1) currentMonth=12; else currentMonth--; ss.clear(); ss<<currentMonth; std::string str; ss>>str; if(str.size()==1) str.insert(0,"0"); return currentDate.substr(0,5)+str+currentDate.substr(7,3); } std::string BalanceCalculator::getBalance(const std::string &date){ currentDate=date; std::list<std::string> list=pOperations->getCurrencies(); std::string result="Баланс за месяц:\n\n"; for(const auto& i:list) result+=i+": "+balance(BalanceCalculator::Time::month,i)+"\n"; result+="\nБаланс за год:\n\n"; for(const auto& i:list) result+=i+": "+balance(BalanceCalculator::Time::year,i)+"\n"; result+="\nБаланс за все время:\n\n"; for(const auto& i:list) result+=i+": "+balance(BalanceCalculator::Time::allTime,i)+"\n"; return result; } <file_sep>#pragma once #include <memory> #include "SRC/BusinessLogic/AbstractBusinessLogic.h" #include "SRC/DataBase/Data.h" #include "SRC/DataBase/DataOperations.h" #include "SRC/BusinessLogic/BalanceCalculator.h" #include "SRC/BusinessLogic/RecordsOperations.h" #include "SRC/BusinessLogic/Report.h" #include "SRC/BusinessLogic/ReportSaveTxt.h" #include "SRC/BusinessLogic/UserFileOperations.h" #include "SRC/BusinessLogic/ReportSaveTxt.h" //#include "SRC/BusinessLogic/ReportSavePdf.h" #include "SRC/BusinessLogic/GraphicBuilder.h" #include "SRC/BusinessLogic/ReportPrint.h" class BusinessLogic:public AbstractBusinessLogic{ public: BusinessLogic(std::shared_ptr<AbstractData> data,std::shared_ptr<AbstractDataFileOperations> operations); unsigned int rowsCount()const override; unsigned int columnsCount()const override; void setData(const unsigned int, const RecordString&)override; RecordString getData(const unsigned int)const override; void removeRow(const unsigned int)override; void sortData()override; std::list<std::string> getAllCurrencies()const override; std::list<std::string> getAllTypes()const override; std::list<std::string> getDataCategories(const std::string&)const override; std::list<std::string> getDataDescriptions(const std::string&)const override; std::list<std::string> getCurrencies()const override; unsigned int rowsCountReport()const override; RecordString getReport(const unsigned int)const override; void filter(const std::string &dateFrom, const std::string &dateTo, const std::pair<bool, bool> &type, const std::vector<std::string> &category, const std::vector<std::string> &description, const double &sumFrom, const double &sumTo, const std::vector<std::string> &currency)override; std::list<std::string> getReportCategories(const bool profit,const bool loss)const override; std::list<std::string> getReportDescriptions(const std::vector<std::string>& categories)const override; std::pair<std::string,std::string> dateMinMax()const override; std::pair<double, double> sumMinMax()const override; void saveReportTxt(const std::string&, const std::string &currentDate)const override; void saveReportPDF(const std::string&, const std::string &currentDate)const override; void updateReport()override; std::string getBalance(const std::string&)const override; std::list<std::string> getUsersNames()const override; bool isUserCreated(const std::string& login, const std::string& password)override; bool loadData(const std::string& login, const std::string& password)override; void saveData()const override; void clearData()override; bool deleteUser(const std::string& login,const std::string& password)override; bool changePassword(const std::string& login,const std::string& oldPassword,const std::string& newPassword)override; std::string getUserName()const override; std::pair<double,double> getMinMaxSum() override; std::vector<std::pair<std::string,double>> getPoints() override; void printReport(const std::string& currentDate) override; private: std::shared_ptr<AbstractData> pData; std::shared_ptr<AbstractDataFileOperations> pDataOperations; std::unique_ptr<BalanceCalculator> pCalculator; std::shared_ptr<RecordsOperations> pOperations; std::shared_ptr<Report> pReport; std::unique_ptr<UserFileOperations> pUserFileOperations; std::unique_ptr<ReportSaveTxt> pReportSaveTxt; //std::unique_ptr<ReportSavePdf> pReportSavePdf; std::unique_ptr<GraphicBuilder> pGraphicBuilder; }; <file_sep>#include "ReportPrint.h" ReportPrint::ReportPrint(std::shared_ptr<Report>& report):pReport(report){ printer=new QPrinter; printDialog=new QPrintPreviewDialog(printer); printDialog->setModal(true); printDialog->showMaximized(); QObject::connect(printDialog,SIGNAL(paintRequested(QPrinter*)),SLOT(ReportPrint())); } ReportPrint::~ReportPrint(){ delete printDialog; delete painter; delete printer; } void ReportPrint::calculatePageParameters(){ leading=2*QFont(font.c_str(),fontSize).pointSize(); pageWidth=printer->pageLayout().paintRect().width(); pageHeight=printer->pageLayout().paintRect().height(); leftBorder=0.12*pageWidth; rightBorder=0.024*pageWidth; verticalBorder=0.017*pageHeight; } // printer=std::make_unique<QPrinter>(QPrinter::PrinterResolution); // QPrintPreviewDialog printDialog(printer.get()); // QObject::connect(&printDialog,SIGNAL(paintRequested(QPrinter*)),SLOT(ReportPrint())); // printDialog.showMaximized(); // printDialog.exec(); // printer.reset(nullptr); //void ReportWidget::ReportPrint(){ // QPainter painter(printer.get()); // painter.setFont(QFont(font,fontSize)); // calculatePageParameters(); // double yPosition=0; // printHeader(painter,yPosition); // printTable(painter,yPosition); //} void ReportPrint::printReport(const std::string& userName,const std::string& currentDate){ //QPrintPreviewDialog printDialog(printer); //printDialog.showMaximized(); //QObject::connect(&printDialog,SIGNAL(paintRequested(QPrinter*)),SLOT(ReportPrint())); double yPosition=0; printHeader(yPosition,userName,currentDate); printTable(yPosition); // printDialog->exec(); } void ReportPrint::printReport(){ painter=new QPainter(printer); painter->setFont(QFont(font.c_str(),fontSize)); calculatePageParameters(); } void ReportPrint::printHeader(double& yPosition,const std::string& userName,const std::string& currentDate){ yPosition=verticalBorder+leading; painter->drawText(0.48*pageWidth,yPosition,"Отчет"); nextRow(yPosition); QString str="Пользователь: "+ QString::fromStdString(userName); painter->drawText(leftBorder,yPosition,str); nextRow(yPosition); str="Дата отчета: "+QString::fromStdString(currentDate); painter->drawText(leftBorder,yPosition,str); nextRow(yPosition); str="Установки фильтра:"; painter->drawText(0.45*pageWidth,yPosition,str); nextRow(yPosition); str="Дата от: "+QString::fromStdString(pReport->getDateFrom())+" Дата до: "+QString::fromStdString(pReport->getDateTo()); painter->drawText(leftBorder,yPosition,str); nextRow(yPosition); str="Тип: "; if((pReport->getType().first==true)&&(pReport->getType().second==false)) str+="Прибыль"; if((pReport->getType().first==false)&&(pReport->getType().second==true)) str+="Убыток"; if((pReport->getType().first==true)&&(pReport->getType().second==true)) str+="Все"; painter->drawText(leftBorder,yPosition,str); nextRow(yPosition); str="Сумма от: "+ QString::number(pReport->getSumFrom())+" Сумма до: "+QString::number(pReport->getSumTo()); painter->drawText(leftBorder,yPosition,str); nextRow(yPosition); str="Валюты: "; painter->drawText(leftBorder,yPosition,str); nextRow(yPosition); //stringFromVector(pReport->getCurrency()) //printComboBoxCheckedList(pCbxCurrency,painter,yPosition); str="Категории: "; painter->drawText(leftBorder,yPosition,str); nextRow(yPosition); //stringFromVector(pReport->getCategory()) //printComboBoxCheckedList(pCbxCategory,painter,yPosition); str="Описания: "; painter->drawText(leftBorder,yPosition,str); nextRow(yPosition); //stringFromVector(pReport->getDescription()) //printComboBoxCheckedList(pCbxDescription,painter,yPosition); } void ReportPrint::printTable(double& yPosition){ const double pageWidthWithoutBorders=(pageWidth-leftBorder-rightBorder); const double xType=0.15*pageWidthWithoutBorders; const double xCategory=0.28*pageWidthWithoutBorders; const double xDescription=0.54*pageWidthWithoutBorders; const double xSum=0.8*pageWidthWithoutBorders; const double xCurrency=0.92*pageWidthWithoutBorders; //print table header painter->drawText(leftBorder,yPosition,"Дата"); painter->drawText(leftBorder+xType,yPosition,"Тип"); painter->drawText(leftBorder+xCategory,yPosition,"Категория"); painter->drawText(leftBorder+xDescription,yPosition,"Описание"); painter->drawText(leftBorder+xSum,yPosition,"Сумма"); painter->drawText(leftBorder+xCurrency,yPosition,"Валюта"); nextRow(yPosition); //print table unsigned int rows=pReport->rowsCount(); for(unsigned int row = 0;row<rows;++row){ RecordString rec=pReport->getRow(row); painter->drawText(leftBorder,yPosition,rec.getDate().c_str()); painter->drawText(leftBorder+xType,yPosition,rec.getType().c_str()); painter->drawText(leftBorder+xCategory,yPosition,rec.getCategory().c_str()); painter->drawText(leftBorder+xDescription,yPosition,rec.getDescription().c_str()); painter->drawText(leftBorder+xSum,yPosition,QString::number(rec.getSum())); painter->drawText(leftBorder+xCurrency,yPosition,rec.getCurrency().c_str()); yPosition+=leading; if(yPosition>(pageHeight-verticalBorder)&&(row!=(rows-1))){ printer->newPage(); yPosition=verticalBorder+leading; //print table header painter->drawText(leftBorder,yPosition,"Дата"); painter->drawText(leftBorder+xType,yPosition,"Тип"); painter->drawText(leftBorder+xCategory,yPosition,"Категория"); painter->drawText(leftBorder+xDescription,yPosition,"Описание"); painter->drawText(leftBorder+xSum,yPosition,"Сумма"); painter->drawText(leftBorder+xCurrency,yPosition,"Валюта"); yPosition+=leading; } } } void ReportPrint::nextRow(double& yPosition)const{ yPosition+=leading; if(yPosition>(pageHeight-verticalBorder)){ printer->newPage(); yPosition=verticalBorder+leading; } } <file_sep>#include "Report.h" constexpr char LOSS[]="Убыток"; constexpr char PROFIT[]="Прибыль"; Report::Report(std::shared_ptr<AbstractData>& data):pData(data){} RecordString Report::getRow(const int row) const{ int count=0; for(unsigned int i=0;i<filter.size();i++){ if(filter[i]){ if(count==row){ RecordString rec(pData->getRecord(i)); return rec; } count++; } } return {"","","","",0,""}; } int Report::rowsCount() const{ return size; } void Report::update(){ size=pData->rows(); filter.resize(size); std::fill(filter.begin(),filter.end(),true); } void Report::sizeReport(){ size=0; for(const auto& i:filter) if(i) size++; } void Report::filterDB(const std::string& fDateFrom, const std::string& fDateTo, const std::pair<bool,bool>& fType, const std::vector<std::string>& fCategory, const std::vector<std::string>& fDescription, const double& fSumFrom, const double& fSumTo, const std::vector<std::string>& fCurrency){ dateFrom=fDateFrom; dateTo=fDateTo; type=fType; category=fCategory; description=fDescription; sumFrom=fSumFrom; sumTo=fSumTo; currency=fCurrency; unsigned int rows=pData->rows(); for(unsigned int i=0;i<rows;i++){ RecordString rec=pData->getRecord(i); if(dateInRange(rec.getDate(),dateFrom,dateTo) && typeInRange(rec.getType(),type) && valueInRange(rec.getCategory(),category) && valueInRange(rec.getDescription(),description) && sumInRange(rec.getSum(),sumFrom,sumTo) && valueInRange(rec.getCurrency(),currency) ) filter[i]=true; else filter[i]=false; } sizeReport(); } bool Report::typeInRange(const std::string& type,const std::pair<bool,bool> typeFilter) const{ if(type==PROFIT && typeFilter.first) return true; if(type==LOSS && typeFilter.second) return true; return false; } bool Report::valueInRange(const std::string& value,const std::vector<std::string>& vector) const{ for(const auto& i:vector) if(value==i) return true; return false; } bool Report::sumInRange(const double& sum,const double& sumFrom,const double& sumTo) const{ if(sumFrom<=sum && sum<=sumTo) return true; return false; } bool Report::dateInRange(const std::string& date,const std::string& dateFrom,const std::string& dateTo) const{ if(dateFrom<=date && date<=dateTo) return true; return false; } std::list<std::string> Report::getCategories(const bool profit,const bool loss) const{ std::list<std::string> categories; for(int i=0;i<static_cast<int>(filter.size());i++){ RecordString rec=pData->getRecord(i); if((profit && rec.getType()==PROFIT) || (loss && rec.getType()==LOSS)){ std::string category=rec.getCategory(); bool isUnique=true; for(const auto& j:categories){ if(j==category) isUnique=false; } if(isUnique) categories.push_back(category); } } categories.sort(); return categories; } std::list<std::string> Report::getDescriptions(const std::vector <std::string>& categories) const{ std::list<std::string> descriptions; for(int i=0;i<static_cast<int>(filter.size());i++){ RecordString rec=pData->getRecord(i); for(const auto& j:categories){ if(j==rec.getCategory()){ std::string description=rec.getDescription(); bool isUnique=true; for(const auto& j:descriptions){ if(j==description) isUnique=false; } if(isUnique) descriptions.push_back(description); } } } descriptions.sort(); return descriptions; } std::pair<std::string,std::string> Report::dateMinMax() const{ RecordString recMin=pData->getRecord(0); RecordString recMax=pData->getRecord(static_cast<int>(filter.size())-1); return {recMin.getDate(),recMax.getDate()}; } std::pair<double, double> Report::sumMinMax() const{ double max; double min; for(int i=0;i<static_cast<int>(filter.size());++i){ RecordString rec=pData->getRecord(i); double sum=rec.getSum(); if(i==0){ max=sum; min=sum; } if(max<sum) max=sum; if (min>sum) min=sum; } return {min,max}; } std::string Report::getDateFrom() const{ return dateFrom; } std::string Report::getDateTo() const{ return dateTo; } std::pair<bool,bool> Report::getType() const{ return type; } std::vector<std::string> Report::getCategory() const{ return category; } std::vector<std::string> Report::getDescription() const{ return description; } double Report::getSumFrom() const{ return sumFrom; } double Report::getSumTo() const{ return sumTo; } std::vector<std::string> Report::getCurrency() const{ return currency; } <file_sep>#include "ChangePasswordWidget.h" ChangePasswordWidget::ChangePasswordWidget(){ drawWindow(); QObject::connect(pBtnOK,SIGNAL(clicked()),SLOT(slotClickedOk())); setModal(true); } void ChangePasswordWidget::drawWindow(){ resize(400,150); pBtnOK=new QPushButton(tr("Ок")); pLeOldPassword= new QLineEdit; pLeOldPassword->setEchoMode(QLineEdit::Password); pLePassword=new QLineEdit; pLePassword->setEchoMode(QLineEdit::Password); pLePasswordConfirmation=new QLineEdit; pLePasswordConfirmation->setEchoMode(QLineEdit::Password); QLabel* pLblName=new QLabel(tr("Текущий пароль")); QLabel* pLblPassword=new QLabel(tr("<PASSWORD>")); QLabel* pLblPasswordConfirmation=new QLabel(tr("Подтверждение пароля")); QGridLayout* pGrdMain=new QGridLayout; pGrdMain->addWidget(pLblName,0,0,Qt::AlignRight); pGrdMain->addWidget(pLblPassword,1,0,Qt::AlignRight); pGrdMain->addWidget(pLblPasswordConfirmation,2,0,Qt::AlignRight); pGrdMain->addWidget(pLeOldPassword,0,1); pGrdMain->addWidget(pLePassword,1,1); pGrdMain->addWidget(pLePasswordConfirmation,2,1); pGrdMain->addWidget(pBtnOK,0,2); setLayout(pGrdMain); } void ChangePasswordWidget::slotClickedOk(){ if(pLePassword->text()!=pLePasswordConfirmation->text()){ QMessageBox::information(this,tr("Сообщение"),tr("Пароли не совпадают!")); pLeOldPassword->clear(); pLePassword->clear(); pLePasswordConfirmation->clear(); return; } emit clickedOk(pLeOldPassword->text(),pLePassword->text()); } <file_sep>#include "MainWindow.h" MainWindow::MainWindow(std::shared_ptr<AbstractBusinessLogic> logic):pLogic(logic){ createWindows(); drawMainWindow(); connectWindows(); userShow(); show(); } void MainWindow::createWindows(){ pWdgUser=new UserWidget(pLogic,this); pWdgMoney=new MoneyRepositaryWidget(pLogic,this); pWdgReport=new ReportWidget(pLogic,this); } void MainWindow::drawMainWindow(){ resize(1200,800); pBtnUser=new QPushButton(tr("Пользователь")); pBtnMoney=new QPushButton(tr("Кошелек")); pBtnMoney->setEnabled(false); pBtnReport=new QPushButton(tr("Отчет")); pBtnReport->setEnabled(false); pLblBalance = new QLabel(tr("Текущий баланс")); pLblBalance->hide(); QVBoxLayout* pVblLeftMenu=new QVBoxLayout(); pVblLeftMenu->setSpacing(20); //pVblLeftMenu->setMargin(15); pVblLeftMenu->addWidget(pBtnUser); pVblLeftMenu->addWidget(pBtnMoney); pVblLeftMenu->addWidget(pBtnReport); pVblLeftMenu->addStretch(1); pVblLeftMenu->addWidget(pLblBalance,0); QHBoxLayout* pHblMain=new QHBoxLayout(); pHblMain->addLayout(pVblLeftMenu,1); pHblMain->addWidget(pWdgUser,5); pHblMain->addWidget(pWdgMoney,5); pHblMain->addWidget(pWdgReport,5); setLayout(pHblMain); } void MainWindow::connectWindows(){ QObject::connect(pBtnMoney,SIGNAL(clicked()),SLOT(moneyShow())); QObject::connect(pBtnUser,SIGNAL(clicked()),SLOT(userShow())); QObject::connect(pBtnReport,SIGNAL(clicked()),SLOT(reportShow())); QObject::connect(pWdgUser,SIGNAL(dataIsLoaded()),SLOT(dataIsLoaded())); QObject::connect(pWdgUser,SIGNAL(dataIsLoaded()),pWdgMoney,SLOT(dataIsLoaded())); QObject::connect(pWdgUser,SIGNAL(exitUser()),SLOT(exitUser())); QObject::connect(pWdgMoney,SIGNAL(tableChanged()),SLOT(balance())); } void MainWindow::moneyShow() const{ pWdgMoney->show(); pWdgUser->hide(); pWdgReport->hide(); } void MainWindow::userShow() const{ pWdgMoney->hide(); pWdgUser->show(); pWdgReport->hide(); } void MainWindow::reportShow(){ pWdgMoney->hide(); pWdgUser->hide(); pWdgReport->show(); pLogic->updateReport(); pWdgReport->fillFields(); pWdgReport->updateTable(); } void MainWindow::dataIsLoaded() { pBtnMoney->setEnabled(true); pBtnReport->setEnabled(true); balance(); moneyShow(); } void MainWindow::exitUser() const{ pBtnMoney->setEnabled(false); pBtnReport->setEnabled(false); pLblBalance->hide(); pLogic->clearData(); userShow(); } void MainWindow::balance(){ pLblBalance->setText(pLogic->getBalance(QDate::currentDate().toString("yyyy-MM-dd").toStdString()).c_str()); pLblBalance->show(); } <file_sep>#pragma once #include <vector> #include <string> #include "SRC/BusinessLogic/Report.h" #include "SRC/BusinessLogic/RecordString.h" #include <memory> class GraphicBuilder{ public: GraphicBuilder(std::shared_ptr<Report>& report); std::pair<double,double> getMinMaxSum(); std::vector<std::pair<std::string,double>> getPoints(); private: std::shared_ptr<Report> pReport; std::vector<std::pair<std::string,double>> points; void calculatePoints(); }; <file_sep>#pragma once #include "SRC/DataBase/Data.h" #include "SRC/BusinessLogic/RecordString.h" #include <list> #include <memory> #include <string> class RecordsOperations{ public: explicit RecordsOperations(std::shared_ptr<AbstractData> &data); std::list<std::string> getCategories(const std::string &type)const; std::list<std::string> getDescriptions(const std::string& category)const; std::list<std::string> getCurrencies() const; private: std::shared_ptr<AbstractData> pData; }; <file_sep>#pragma once #include <list> #include <vector> #include <string> #include "SRC/BusinessLogic/RecordString.h" class AbstractBusinessLogic{ public: //Data Base virtual unsigned int rowsCount()const=0; virtual unsigned int columnsCount()const=0; virtual void setData(const unsigned int, const RecordString&)=0; virtual RecordString getData(const unsigned int)const=0; virtual void removeRow(const unsigned int)=0; virtual void sortData()=0; virtual std::list<std::string> getAllCurrencies()const=0; virtual std::list<std::string> getAllTypes()const=0; virtual std::list<std::string> getDataCategories(const std::string&)const=0; virtual std::list<std::string> getDataDescriptions(const std::string&)const=0; virtual std::list<std::string> getCurrencies()const=0; //Report virtual unsigned int rowsCountReport()const=0; virtual RecordString getReport(const unsigned int)const=0; virtual void filter(const std::string& dateFrom, const std::string& dateTo, const std::pair<bool,bool>& type, const std::vector<std::string>& category, const std::vector<std::string>& description, const double& sumFrom, const double& sumTo, const std::vector<std::string>& currency)=0; virtual std::list<std::string> getReportCategories(const bool,const bool)const=0; virtual std::list<std::string> getReportDescriptions(const std::vector<std::string>&)const=0; virtual std::pair<std::string,std::string> dateMinMax()const=0; virtual std::pair<double, double> sumMinMax()const=0; virtual void saveReportTxt(const std::string&,const std::string&)const=0; virtual void saveReportPDF(const std::string&, const std::string &currentDate)const=0; virtual void updateReport()=0; //Balance virtual std::string getBalance(const std::string&)const=0; //User operations virtual std::list<std::string> getUsersNames()const=0; virtual bool isUserCreated(const std::string& login, const std::string& password)=0; virtual bool loadData(const std::string& login, const std::string& password)=0; virtual void saveData()const=0; virtual void clearData()=0; virtual bool deleteUser(const std::string& login,const std::string& password)=0; virtual bool changePassword(const std::string& login,const std::string& oldPassword,const std::string& newPassword)=0; virtual std::string getUserName()const=0; //Graphic virtual std::pair<double,double> getMinMaxSum()=0; virtual std::vector<std::pair<std::string,double>> getPoints()=0; virtual void printReport(const std::string& currentDate)=0; }; <file_sep>#include "ReportWidget.h" ReportWidget::ReportWidget(std::shared_ptr<AbstractBusinessLogic> logic, QWidget *parent) : QWidget(parent),pLogic(logic){ drawWindow(); connectButtons(); } void ReportWidget::drawWindow(){ pGraphicWidget=new GraphicWidget(pLogic,this); pGraphicWidget->hide(); pTable=new QTableWidget(this); pTable->installEventFilter(this); pBtnSaveTxt=new QPushButton(tr("Сохранить TXT")); pBtnSavePDF=new QPushButton(tr("Сохранить в PDF")); pBtnPrint=new QPushButton(tr("Печать")); pBtnChart=new QPushButton(tr("График")); pBtnReset=new QPushButton(tr("Сбросить фильтр")); QVBoxLayout* pVbxButtons=new QVBoxLayout; pVbxButtons->addWidget(pBtnSaveTxt); pVbxButtons->addWidget(pBtnSavePDF); pVbxButtons->addWidget(pBtnPrint); pVbxButtons->addWidget(pBtnChart); pVbxButtons->addStretch(1); QLabel* pLblDateFrom=new QLabel(tr("От:")); pTimeEditFrom=new QDateEdit(); QLabel* pLblDateTo=new QLabel(tr("До:")); pTimeEditTo=new QDateEdit(); QVBoxLayout* pVbxDate=new QVBoxLayout; pVbxDate->addWidget(pLblDateFrom); pVbxDate->addWidget(pTimeEditFrom); pVbxDate->addWidget(pLblDateTo); pVbxDate->addWidget(pTimeEditTo); pVbxDate->addStretch(1); QLabel* pLblType=new QLabel(tr("Тип:")); pChbxTypeProfit=new QCheckBox(tr("Прибыль")); pChbxTypeLoss=new QCheckBox(tr("Убыток")); QVBoxLayout* pVbxType=new QVBoxLayout; pVbxType->addWidget(pLblType); pVbxType->addWidget(pChbxTypeProfit); pVbxType->addWidget(pChbxTypeLoss); pVbxType->addStretch(1); QLabel* pLblCategory=new QLabel(tr("Категория:")); pCbxCategory=new QComboBox; pModelCategory = new QStandardItemModel(0, 1); pCbxCategory->setModel(pModelCategory); QVBoxLayout* pVbxCategory=new QVBoxLayout; pVbxCategory->addWidget(pLblCategory); pVbxCategory->addWidget(pCbxCategory); pVbxCategory->addStretch(1); QLabel* pLblDescription=new QLabel(tr("Описание:")); pCbxDescription=new QComboBox; pModelDescription = new QStandardItemModel(0, 1); pCbxDescription->setModel(pModelDescription); QVBoxLayout* pVbxDescription=new QVBoxLayout; pVbxDescription->addWidget(pLblDescription); pVbxDescription->addWidget(pCbxDescription); pVbxDescription->addStretch(1); QLabel* pLblSumFrom=new QLabel(tr("Сумма от:")); pLineEditSumFrom=new QLineEdit; QLabel* pLblSumTo=new QLabel(tr("Сумма до:")); pLineEditSumTo=new QLineEdit; QVBoxLayout* pVbxSum=new QVBoxLayout; pVbxSum->addWidget(pLblSumFrom); pVbxSum->addWidget(pLineEditSumFrom); pVbxSum->addWidget(pLblSumTo); pVbxSum->addWidget(pLineEditSumTo); pVbxSum->addStretch(1); QLabel* pLblCurrency=new QLabel(tr("Валюта:")); pCbxCurrency=new QComboBox; pModelCurrency = new QStandardItemModel(0, 1); pCbxCurrency->setModel(pModelCurrency); QVBoxLayout* pVbxCurrency=new QVBoxLayout; pVbxCurrency->addWidget(pLblCurrency); pVbxCurrency->addWidget(pCbxCurrency); pVbxCurrency->addStretch(1); QHBoxLayout* pHbxFilter=new QHBoxLayout; pHbxFilter->addLayout(pVbxDate,2); pHbxFilter->addLayout(pVbxType,1); pHbxFilter->addLayout(pVbxCategory,4); pHbxFilter->addLayout(pVbxDescription,4); pHbxFilter->addLayout(pVbxSum,2); pHbxFilter->addLayout(pVbxCurrency,1); QHBoxLayout* pHbxButtonsFilter=new QHBoxLayout; pHbxButtonsFilter->addWidget(pBtnReset); pHbxButtonsFilter->addWidget(pBtnChart); QVBoxLayout* pVbxFilter=new QVBoxLayout; pVbxFilter->addLayout(pHbxFilter); pVbxFilter->addLayout(pHbxButtonsFilter); QHBoxLayout* pHbxButtonsAndFilter=new QHBoxLayout; pHbxButtonsAndFilter->addLayout(pVbxFilter); pHbxButtonsAndFilter->addLayout(pVbxButtons); QVBoxLayout* pVbxMain=new QVBoxLayout; pVbxMain->addLayout(pHbxButtonsAndFilter,1); pVbxMain->addWidget(pGraphicWidget,6); pVbxMain->addWidget(pTable,6); setLayout(pVbxMain); } void ReportWidget::connectButtons(){ QObject::connect(pChbxTypeProfit,SIGNAL(clicked()),SLOT(fillComboBoxCategory())); QObject::connect(pChbxTypeLoss,SIGNAL(clicked()),SLOT(fillComboBoxCategory())); QObject::connect(pModelCategory,SIGNAL(itemChanged(QStandardItem*)),SLOT(categoryChecked(QStandardItem*))); QObject::connect(pModelCategory,SIGNAL(itemChanged(QStandardItem*)),SLOT(fillComboBoxDescription())); QObject::connect(pModelDescription,SIGNAL(itemChanged(QStandardItem*)),SLOT(descriptionChecked(QStandardItem*))); QObject::connect(pModelCurrency,SIGNAL(itemChanged(QStandardItem*)),SLOT(currencyChecked(QStandardItem*))); QObject::connect(pBtnReset,SIGNAL(clicked()),SLOT(resetFilter())); QObject::connect(pBtnSaveTxt,SIGNAL(clicked()),SLOT(saveTxt())); QObject::connect(pBtnSavePDF,SIGNAL(clicked()),SLOT(savePDF())); QObject::connect(pBtnPrint,SIGNAL(clicked()),SLOT(btnPrintClicked())); QObject::connect(pBtnChart,SIGNAL(clicked()),SLOT(btnChartClicked())); QObject::connect(pTimeEditFrom,SIGNAL(dateChanged(const QDate&)),SLOT(filter())); QObject::connect(pTimeEditTo,SIGNAL(dateChanged(const QDate&)),SLOT(filter())); QObject::connect(pChbxTypeProfit,SIGNAL(clicked()),SLOT(filter())); QObject::connect(pChbxTypeLoss,SIGNAL(clicked()),SLOT(filter())); QObject::connect(pModelCategory,SIGNAL(itemChanged(QStandardItem*)),SLOT(filter())); QObject::connect(pModelDescription,SIGNAL(itemChanged(QStandardItem*)),SLOT(filter())); QObject::connect(pModelCurrency,SIGNAL(itemChanged(QStandardItem*)),SLOT(filter())); QObject::connect(pLineEditSumFrom,SIGNAL(textChanged(const QString&)),SLOT(filter())); QObject::connect(pLineEditSumTo,SIGNAL(textChanged(const QString&)),SLOT(filter())); } void ReportWidget::updateTable(){ unsigned int rows=pLogic->rowsCountReport(); pTable->setRowCount(rows); pTable->setColumnCount(pLogic->columnsCount()); for(unsigned int row = 0;row<rows;row++){ RecordString rec=pLogic->getReport(row); QTableWidgetItem* item0 = new QTableWidgetItem(rec.getDate().c_str()); pTable->setItem(row,0,item0); QTableWidgetItem* item1 = new QTableWidgetItem(rec.getType().c_str()); pTable->setItem(row,1,item1); QTableWidgetItem* item2 = new QTableWidgetItem(rec.getCategory().c_str()); pTable->setItem(row,2,item2); QTableWidgetItem* item3 = new QTableWidgetItem(rec.getDescription().c_str()); pTable->setItem(row,3,item3); QTableWidgetItem* item4 = new QTableWidgetItem(QString::number(rec.getSum())); pTable->setItem(row,4,item4); QTableWidgetItem* item5 = new QTableWidgetItem(rec.getCurrency().c_str()); pTable->setItem(row,5,item5); } setTableHeader(); setTableDimensions(); } void ReportWidget::setTableHeader(){ std::vector<std::string> header{"Дата","Тип","Категория","Описание","Сумма","Валюта"}; unsigned int columnsCount=header.size(); for(unsigned int i=0;i<columnsCount;i++){ QTableWidgetItem* item=new QTableWidgetItem(header[i].c_str()); pTable->setHorizontalHeaderItem(i,item); } pTable->verticalHeader()->hide(); } void ReportWidget::setTableDimensions(){ pTable->setColumnWidth(0, pTable->width() * 0.1); pTable->setColumnWidth(1, pTable->width() * 0.1); pTable->setColumnWidth(2, pTable->width() * 0.28); pTable->setColumnWidth(3, pTable->width() * 0.3); pTable->setColumnWidth(4, pTable->width() * 0.1); pTable->setColumnWidth(5, pTable->width() * 0.1); } bool ReportWidget::eventFilter(QObject* , QEvent *pEvent){ if(pEvent->type() == QEvent::Resize ) setTableDimensions(); return false; } void ReportWidget::filter(){ pLogic->filter(pTimeEditFrom->date().toString("yyyy-MM-dd").toStdString(), pTimeEditTo->date().toString("yyyy-MM-dd").toStdString(), typeToReport(), getComboBoxCheckedList(pCbxCategory), getComboBoxCheckedList(pCbxDescription), pLineEditSumFrom->text().toFloat(), pLineEditSumTo->text().toDouble(), getComboBoxCheckedList(pCbxCurrency)); updateTable(); } std::pair<bool,bool> ReportWidget::typeToReport() const{ std::pair<bool,bool> type {false,false}; if (pChbxTypeProfit->isChecked()) type.first=true; if(pChbxTypeLoss->isChecked()) type.second=true; return type; } void ReportWidget::fillFields(){ pChbxTypeProfit->setChecked(true); pChbxTypeLoss->setChecked(true); fillComboBoxCategory(); fillComboBoxDescription(); fillDate(); fillSum(); fillComboBoxCurrency(); } void ReportWidget::fillComboBoxCurrency(){ std::list<std::string> list=pLogic->getAllCurrencies(); fillComboBox(pModelCurrency,list); } void ReportWidget::fillDate(){ std::pair<std::string,std::string> minMax=pLogic->dateMinMax(); pTimeEditFrom->setDate(QDate::fromString(QString::fromStdString(minMax.first),"yyyy-MM-dd")); pTimeEditTo->setDate(QDate::fromString(QString::fromStdString(minMax.second),"yyyy-MM-dd")); } void ReportWidget::fillSum(){ std::pair<double,double> minMax=pLogic->sumMinMax(); pLineEditSumFrom->setText(QString::number(minMax.first)); pLineEditSumTo->setText(QString::number(minMax.second)); } void ReportWidget::fillComboBoxCategory(){ QObject::disconnect(pModelCategory,SIGNAL(itemChanged(QStandardItem*)),this,SLOT(categoryChecked(QStandardItem*))); std::list<std::string> list=pLogic->getReportCategories(pChbxTypeProfit->isChecked(),pChbxTypeLoss->isChecked()); fillComboBox(pModelCategory,list); QObject::connect(pModelCategory,SIGNAL(itemChanged(QStandardItem*)),SLOT(categoryChecked(QStandardItem*))); } void ReportWidget::fillComboBoxDescription() { std::vector<std::string> listCategories; listCategories=getComboBoxCheckedList(pCbxCategory); std::list<std::string> listDescriptions; listDescriptions=pLogic->getReportDescriptions(listCategories); fillComboBox(pModelDescription,listDescriptions); } void ReportWidget::fillComboBox(QStandardItemModel* model,std::list<std::string>& list){ list.insert(list.begin(),"Все"); model->setRowCount(static_cast<int>(list.size())); int row=0; for (const auto& i:list){ QStandardItem* item = new QStandardItem(i.c_str()); item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); item->setData(Qt::Checked, Qt::CheckStateRole); model->setItem(row, 0, item); row++; } } std::vector<std::string> ReportWidget::getComboBoxCheckedList(const QComboBox* combobox) const{ std::vector<std::string> list; int count=combobox->count(); for(int i=0; i<count; i++){ QModelIndex index = combobox->model()->index(i, 0); if(index.data(Qt::CheckStateRole) == Qt::Checked) list.push_back(index.data(Qt::DisplayRole).toString().toStdString()); } return list; } void ReportWidget::categoryChecked(QStandardItem* item){ QObject::disconnect(pModelCategory,SIGNAL(itemChanged(QStandardItem*)),this,SLOT(categoryChecked(QStandardItem*))); checkControl(pModelCategory,item); QObject::connect(pModelCategory,SIGNAL(itemChanged(QStandardItem*)),SLOT(categoryChecked(QStandardItem*))); } void ReportWidget::descriptionChecked(QStandardItem* item){ QObject::disconnect(pModelDescription,SIGNAL(itemChanged(QStandardItem*)),this,SLOT(descriptionChecked(QStandardItem*))); checkControl(pModelDescription,item); QObject::connect(pModelDescription,SIGNAL(itemChanged(QStandardItem*)),SLOT(descriptionChecked(QStandardItem*))); } void ReportWidget::currencyChecked(QStandardItem* item){ QObject::disconnect(pModelCurrency,SIGNAL(itemChanged(QStandardItem*)),this,SLOT(currencyChecked(QStandardItem*))); checkControl(pModelCurrency,item); QObject::connect(pModelCurrency,SIGNAL(itemChanged(QStandardItem*)),SLOT(currencyChecked(QStandardItem*))); } void ReportWidget::checkControl(QStandardItemModel* model,QStandardItem* item){ QModelIndex index = model->index(item->index().row(),0); if(item->index().row()==0){ if(index.data(Qt::CheckStateRole) == Qt::Checked) setCheckAll(model,Qt::Checked); else setCheckAll(model,Qt::Unchecked); } else{ if(index.data(Qt::CheckStateRole) == Qt::Unchecked){ QModelIndex indexAll = model->index(0, 0); model->setData(indexAll,Qt::Unchecked, Qt::CheckStateRole); } } } void ReportWidget::setCheckAll(QStandardItemModel* model,Qt::CheckState state){ int rowCount=model->rowCount(); for(int i=0; i<rowCount; i++){ QModelIndex index = model->index(i, 0); model->setData(index,state, Qt::CheckStateRole); } } void ReportWidget::resetFilter(){ fillFields(); filter(); } void ReportWidget::saveTxt(){ QString fieName = QFileDialog::getSaveFileName(0,tr("Сохранить txt"),"","*.txt"); pLogic->saveReportTxt(fieName.toStdString(),QDate::currentDate().toString("yyyy-MM-dd").toStdString()); } void ReportWidget::savePDF(){ QString fieName = QFileDialog::getSaveFileName(0,tr("Сохранить pdf"),"","*.pdf"); pLogic->saveReportPDF(fieName.toStdString(),QDate::currentDate().toString("yyyy-MM-dd").toStdString()); } void ReportWidget::btnPrintClicked(){ pLogic->printReport(QDate::currentDate().toString("yyyy-MM-dd").toStdString()); // printer=std::make_unique<QPrinter>(QPrinter::PrinterResolution); // QPrintPreviewDialog printDialog(printer.get()); // QObject::connect(&printDialog,SIGNAL(paintRequested(QPrinter*)),SLOT(printReport())); // printDialog.showMaximized(); // printDialog.exec(); // printer.reset(nullptr); } void ReportWidget::printReport(){ QPainter painter(printer.get()); painter.setFont(QFont(font,fontSize)); calculatePageParameters(); double yPosition=0; printHeader(painter,yPosition); printTable(painter,yPosition); } void ReportWidget::printHeader(QPainter& painter,double& yPosition){ yPosition=verticalBorder+leading; painter.drawText(0.48*pageWidth,yPosition,"Отчет"); nextRow(yPosition); QString str="Пользователь: "+ QString::fromStdString(pLogic->getUserName()); painter.drawText(leftBorder,yPosition,str); nextRow(yPosition); str="Дата отчета: "+QDate::currentDate().toString("yyyy-MM-dd"); painter.drawText(leftBorder,yPosition,str); nextRow(yPosition); str="Установки фильтра:"; painter.drawText(0.45*pageWidth,yPosition,str); nextRow(yPosition); str="Дата от: "+pTimeEditFrom->text()+" Дата до: "+pTimeEditTo->text(); painter.drawText(leftBorder,yPosition,str); nextRow(yPosition); str="Тип: "; if((pChbxTypeProfit->isChecked()==true)&&(pChbxTypeLoss->isChecked()==false)) str+="Прибыль"; if((pChbxTypeProfit->isChecked()==false)&&(pChbxTypeLoss->isChecked()==true)) str+="Убыток"; if((pChbxTypeProfit->isChecked()==true)&&(pChbxTypeLoss->isChecked()==true)) str+="все"; painter.drawText(leftBorder,yPosition,str); nextRow(yPosition); str="Сумма от: "+pLineEditSumFrom->text()+" Сумма до: "+pLineEditSumTo->text(); painter.drawText(leftBorder,yPosition,str); nextRow(yPosition); str="Валюты: "; painter.drawText(leftBorder,yPosition,str); nextRow(yPosition); printComboBoxCheckedList(pCbxCurrency,painter,yPosition); str="Категории: "; painter.drawText(leftBorder,yPosition,str); nextRow(yPosition); printComboBoxCheckedList(pCbxCategory,painter,yPosition); str="Описания: "; painter.drawText(leftBorder,yPosition,str); nextRow(yPosition); printComboBoxCheckedList(pCbxDescription,painter,yPosition); } void ReportWidget::nextRow(double& yPosition)const{ yPosition+=leading; if(yPosition>(pageHeight-verticalBorder)){ printer->newPage(); yPosition=verticalBorder+leading; } } void ReportWidget::printComboBoxCheckedList(const QComboBox* combobox,QPainter& painter,double& yPosition) const{ if(combobox->model()->index(0,0).data(Qt::CheckStateRole)==Qt::Checked){ painter.drawText(leftBorder,yPosition,"Все"); nextRow(yPosition); return; } for(int i=1; i<combobox->count(); i++){ QModelIndex index = combobox->model()->index(i, 0); if(index.data(Qt::CheckStateRole) == Qt::Checked){ painter.drawText(leftBorder,yPosition,index.data(Qt::DisplayRole).toString()); nextRow(yPosition); } } } void ReportWidget::printTable(QPainter& painter,double& yPosition){ const double pageWidthWithoutBorders=(pageWidth-leftBorder-rightBorder); const double xType=0.15*pageWidthWithoutBorders; const double xCategory=0.28*pageWidthWithoutBorders; const double xDescription=0.54*pageWidthWithoutBorders; const double xSum=0.8*pageWidthWithoutBorders; const double xCurrency=0.92*pageWidthWithoutBorders; /*print table header*/ painter.drawText(leftBorder,yPosition,pTable->horizontalHeaderItem(0)->data(Qt::DisplayRole).toString()); painter.drawText(leftBorder+xType,yPosition,pTable->horizontalHeaderItem(1)->data(Qt::DisplayRole).toString()); painter.drawText(leftBorder+xCategory,yPosition,pTable->horizontalHeaderItem(2)->data(Qt::DisplayRole).toString()); painter.drawText(leftBorder+xDescription,yPosition,pTable->horizontalHeaderItem(3)->data(Qt::DisplayRole).toString()); painter.drawText(leftBorder+xSum,yPosition,pTable->horizontalHeaderItem(4)->data(Qt::DisplayRole).toString()); painter.drawText(leftBorder+xCurrency,yPosition,pTable->horizontalHeaderItem(5)->data(Qt::DisplayRole).toString()); nextRow(yPosition); /*print table*/ for(int row = 0;row<pTable->rowCount();++row){ painter.drawText(leftBorder,yPosition,pTable->item(row,0)->data(Qt::DisplayRole).toString()); painter.drawText(leftBorder+xType,yPosition,pTable->item(row,1)->data(Qt::DisplayRole).toString()); painter.drawText(leftBorder+xCategory,yPosition,pTable->item(row,2)->data(Qt::DisplayRole).toString()); painter.drawText(leftBorder+xDescription,yPosition,pTable->item(row,3)->data(Qt::DisplayRole).toString()); painter.drawText(leftBorder+xSum,yPosition,pTable->item(row,4)->data(Qt::DisplayRole).toString()); painter.drawText(leftBorder+xCurrency,yPosition,pTable->item(row,5)->data(Qt::DisplayRole).toString()); yPosition+=leading; if(yPosition>(pageHeight-verticalBorder)&&(row!=(pTable->rowCount()-1))){ printer->newPage(); yPosition=verticalBorder+leading; /*print table header*/ painter.drawText(leftBorder,yPosition,pTable->horizontalHeaderItem(0)->data(Qt::DisplayRole).toString()); painter.drawText(leftBorder+xType,yPosition,pTable->horizontalHeaderItem(1)->data(Qt::DisplayRole).toString()); painter.drawText(leftBorder+xCategory,yPosition,pTable->horizontalHeaderItem(2)->data(Qt::DisplayRole).toString()); painter.drawText(leftBorder+xDescription,yPosition,pTable->horizontalHeaderItem(3)->data(Qt::DisplayRole).toString()); painter.drawText(leftBorder+xSum,yPosition,pTable->horizontalHeaderItem(4)->data(Qt::DisplayRole).toString()); painter.drawText(leftBorder+xCurrency,yPosition,pTable->horizontalHeaderItem(5)->data(Qt::DisplayRole).toString()); yPosition+=leading; } } } void ReportWidget::calculatePageParameters(){ leading=2*QFont(font,fontSize).pointSize(); pageWidth=printer->pageLayout().paintRect().width(); pageHeight=printer->pageLayout().paintRect().height(); leftBorder=0.12*pageWidth; rightBorder=0.024*pageWidth; verticalBorder=0.017*pageHeight; } void ReportWidget::btnChartClicked(){ if(pTable->isHidden()==false){ pTable->hide(); pGraphicWidget->show(); pBtnChart->setText("Таблица"); } else { pTable->show(); pGraphicWidget->hide(); pBtnChart->setText("График"); } } <file_sep>#include "GraphicBuilder.h" GraphicBuilder::GraphicBuilder(std::shared_ptr<Report> &report):pReport(report){} std::pair<double,double> GraphicBuilder::getMinMaxSum(){ calculatePoints(); double max=points[0].second; double min=points[0].second; for(int i=0;i<static_cast<int>(points.size());++i){ if(points[i].second>max) max=points[i].second; if(points[i].second<min) min=points[i].second; } return {min,max}; } std::vector<std::pair<std::string,double>> GraphicBuilder::getPoints(){ calculatePoints(); return points; } void GraphicBuilder::calculatePoints(){ points.clear(); points.resize(pReport->rowsCount()); double sumPoint=0; for(int row=0;row<pReport->rowsCount();++row){ RecordString record=pReport->getRow(row); double recordSum=record.getSum(); std::string type=record.getType(); if(type=="Прибыль") sumPoint+=recordSum; else sumPoint-=recordSum; points.push_back({record.getDate(),sumPoint}); } } <file_sep>#include "ReportSaveTxt.h" ReportSaveTxt::ReportSaveTxt(const std::shared_ptr<Report> &rep) : pReport(rep){} int ReportSaveTxt::stringLength(const std::string& str)const{ std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; std::wstring wstr=converter.from_bytes(str); return static_cast<int>(wstr.size()); } void ReportSaveTxt::maxLengthFields(){ unsigned int rows=pReport->rowsCount(); for(unsigned int i=0;i<rows;i++){ RecordString recordString=pReport->getRow(i); int sizeType=stringLength(recordString.getType()); int sizeCategory=stringLength(recordString.getCategory()); int sizeDescription=stringLength(recordString.getDescription()); int sizeSum=stringLength(doubleToString(recordString.getSum())); if(fieldTypeLength<sizeType) fieldTypeLength=sizeType; if(fieldCategoryLength<sizeCategory) fieldCategoryLength=sizeCategory; if(fieldDescriptionLength<sizeDescription) fieldDescriptionLength=sizeDescription; if(fieldSumLength<sizeSum) fieldSumLength=sizeSum; } } std::string ReportSaveTxt::row(const int row)const{ char separatorFields=' '; int numberSeparatorFields=1; std::string result; if(row==-1){ result="Дата "; std::string separatorType(fieldTypeLength-stringLength("Тип")+numberSeparatorFields,separatorFields); std::string separatorCategory(fieldCategoryLength-stringLength("Категория")+numberSeparatorFields,separatorFields); std::string separatorDescription(fieldDescriptionLength-stringLength("Описание")+numberSeparatorFields,separatorFields); std::string separatorSum(fieldSumLength-stringLength("Сумма")+numberSeparatorFields,separatorFields); result+="Тип"+separatorType+ "Категория"+separatorCategory+ "Описание"+separatorDescription+ "Сумма"+separatorSum+ "Валюта\n"; return result; } RecordString recordString=pReport->getRow(row); result+=recordString.getDate()+separatorFields; std::string separatorType(fieldTypeLength-stringLength(recordString.getType())+numberSeparatorFields,separatorFields); std::string separatorCategory(fieldCategoryLength-stringLength(recordString.getCategory())+numberSeparatorFields,separatorFields); std::string separatorDescription(fieldDescriptionLength-stringLength(recordString.getDescription())+numberSeparatorFields,separatorFields); std::string separatorSum(fieldSumLength-stringLength(doubleToString(recordString.getSum()))+numberSeparatorFields,separatorFields); result+=recordString.getType()+separatorType+ recordString.getCategory()+separatorCategory+ recordString.getDescription()+separatorDescription+ doubleToString(recordString.getSum())+separatorSum+ recordString.getCurrency()+"\n"; return result; } std::string ReportSaveTxt::doubleToString(const double value)const{ std::stringstream ss; std::string string; ss<<value; ss>>string; return string; } void ReportSaveTxt::saveTxt(const std::string& filename, const std::string& userName, const std::string& currentDate){ std::ofstream file{filename}; if(!file) throw "File wasn't created!"; file<<headerReport(userName,currentDate); maxLengthFields(); for(int i=-1;i<pReport->rowsCount();i++) file<<row(i); } std::string ReportSaveTxt::headerReport(const std::string& userName,const std::string& currentDate) const{ std::string type; if((pReport->getType().first==true)&&(pReport->getType().second==false)) type="Прибыль"; if((pReport->getType().first==false)&&(pReport->getType().second==true)) type="Убыток"; if((pReport->getType().first==true)&&(pReport->getType().second==true)) type="Все"; return "Отчет\nПользователь:"+userName+"\tДата отчета:"+currentDate+"\nФильтр\n"+ "Дата от:"+pReport->getDateFrom()+"\tДата до:"+pReport->getDateTo()+ "\nТип:"+type+ "\nСумма от:"+doubleToString(pReport->getSumFrom())+" Сумма до:"+doubleToString(pReport->getSumTo())+ "\nКатегории:\n"+stringFromVector(pReport->getCategory())+ "Описания:\n"+stringFromVector(pReport->getDescription())+ "Валюты:\n"+stringFromVector(pReport->getCurrency())+"\n"; } std::string ReportSaveTxt::stringFromVector(const std::vector<std::string>& vec)const{ std::string result; if(vec[0]=="Все") return vec[0]+"\n"; else{ for(const auto& i:vec) result+=i+"\n"; return result; } } <file_sep>#include "RecordString.h" RecordString::RecordString(const std::string& dt, const std::string& tp, const std::string& ct, const std::string& ds, const double sm, const std::string& cr) :date(dt),type(tp),category(ct),description(ds),sum(sm),currency(cr){ } double RecordString::getSum()const{ return sum; } std::string RecordString::getDate()const{ return date; } std::string RecordString::getType()const{ return type; } std::string RecordString::getCategory()const{ return category; } std::string RecordString::getDescription()const{ return description; } std::string RecordString::getCurrency()const{ return currency; } <file_sep>#include "PasswordWidget.h" PasswordWidget::PasswordWidget(){ drawWindow(); QObject::connect(pBtnOK,SIGNAL(clicked()),SLOT(slotClickedOk())); setModal(true); } void PasswordWidget::drawWindow(){ resize(400,150); pBtnOK=new QPushButton(tr("Ок")); pLeName= new QLineEdit; pLePassword=new QLineEdit; pLePassword->setEchoMode(QLineEdit::Password); pLePasswordConfirmation=new QLineEdit; pLePasswordConfirmation->setEchoMode(QLineEdit::Password); QLabel* pLblName=new QLabel(tr("Имя")); QLabel* pLblPassword=new QLabel(tr("<PASSWORD>")); QLabel* pLblPasswordConfirmation=new QLabel(tr("Подтверждение <PASSWORD>")); QGridLayout* pGrdMain=new QGridLayout; pGrdMain->addWidget(pLblName,0,0,Qt::AlignRight); pGrdMain->addWidget(pLblPassword,1,0,Qt::AlignRight); pGrdMain->addWidget(pLblPasswordConfirmation,2,0,Qt::AlignRight); pGrdMain->addWidget(pLeName,0,1); pGrdMain->addWidget(pLePassword,1,1); pGrdMain->addWidget(pLePasswordConfirmation,2,1); pGrdMain->addWidget(pBtnOK,0,2); setLayout(pGrdMain); } void PasswordWidget::slotClickedOk(){ if(pLePassword->text()!=pLePasswordConfirmation->text()){ QMessageBox::information(this,tr("Сообщение"),tr("Пароли не совпадают!")); return; } //Задать рег выражение для логина if(pLeName->text()==""||pLeName->text()==" "){ QMessageBox::information(this,tr("Сообщение"),tr("Вы забыли указать имя!")); return; } emit clickedOk(pLeName->text(),pLePassword->text(),this); } <file_sep>cmake_minimum_required(VERSION 3.5) project(Accountant LANGUAGES CXX) set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_AUTOUIC ON) set(CMAKE_AUTOMOC ON) set(CMAKE_AUTORCC ON) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) find_package(QT NAMES Qt6 Qt5 COMPONENTS Widgets REQUIRED) find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Widgets REQUIRED) find_package(Qt${QT_VERSION_MAJOR}PrintSupport REQUIRED) #INCLUDE_DIRECTORIES(usr/local/lib) #find_package(libHaru REQUIRED) #find_package(libhpdf REQUIRED) #INCLUDE_DIRECTORIES(${LIBHPDF_INCLUDE_DIRS}) #target_link_libraries(Accountant ${LIBHPDF_LIBRARIES}) add_executable(Accountant main.cpp SRC/ApplicationBuilder.cpp SRC/DataBase/Data.cpp SRC/DataBase/DataOperations.cpp SRC/DataBase/Record.cpp SRC/GUI/MainWindow.cpp SRC/GUI/ChangePasswordWidget.cpp SRC/GUI/GraphicWidget.cpp SRC/GUI/MoneyRepositaryWidget.cpp SRC/GUI/PasswordWidget.cpp SRC/GUI/ReportWidget.cpp SRC/GUI/UserWidget.cpp SRC/BusinessLogic/BusinessLogic.cpp SRC/BusinessLogic/BalanceCalculator.cpp SRC/BusinessLogic/GraphicBuilder.cpp SRC/BusinessLogic/RecordsOperations.cpp SRC/BusinessLogic/RecordString.cpp SRC/BusinessLogic/Report.cpp #SRC/BusinessLogic/ReportSavePdf.cpp SRC/BusinessLogic/ReportSaveTxt.cpp SRC/BusinessLogic/UserFileOperations.cpp SRC/BusinessLogic/ReportSaveTxt.cpp SRC/BusinessLogic/ReportPrint.cpp SRC/BusinessLogic/GraphicBuilder.cpp SRC/BusinessLogic/User.cpp ) target_link_libraries(Accountant PRIVATE Qt${QT_VERSION_MAJOR}::Widgets Qt${QT_VERSION_MAJOR}::PrintSupport) <file_sep>#include "ApplicationBuilder.h" ApplicationBuilder::ApplicationBuilder(): pData(std::make_shared<Data>()), pOperations(std::make_shared<DataFileOperations>(pData)), pLogic(std::make_shared<BusinessLogic>(pData,pOperations)), pMainWindow(std::make_unique<MainWindow>(pLogic)) {} <file_sep>#pragma once #include <QtWidgets> #include <QDate> #include <vector> #include <memory> #include <string> #include <QStringList> #include "SRC/BusinessLogic/RecordString.h" #include "SRC/BusinessLogic/BusinessLogic.h" class MoneyRepositaryWidget : public QWidget{ Q_OBJECT public: MoneyRepositaryWidget(std::shared_ptr<AbstractBusinessLogic> logic,QWidget* parent); bool eventFilter(QObject*,QEvent* pEvent)override; private slots: void addRecord(); void deleteRecord(); void editRecord(); void cancelEditRecord(); void categoryChanged(); void dataIsLoaded(); void saveData(); void updateCbxCategory(); signals: void tableChanged(); private: std::shared_ptr<AbstractBusinessLogic> pLogic; bool isEdit=false; QTableWidget* pTable; QPushButton* pBtnSave; QPushButton* pBtnAdd; QPushButton* pBtnEdit; QPushButton* pBtnDelete; QPushButton* pBtnCnacel; QDateEdit* pTimeEdit; QComboBox* pCbxType; QComboBox* pCbxCategory; QComboBox* pCbxDescription; QLineEdit* pLineEditSum; QComboBox* pCbxCurrency; void drawWindow(); void connectButtons(); void updateTable(); void setEditView(); void setWorkView(); void setTableDimensions(); void setTableHeader(); QStringList convertToQList(const std::list<std::string>& list)const; }; <file_sep>#pragma once #include <string> class RecordString{ public: RecordString(const std::string& dt, const std::string& tp, const std::string& ct, const std::string& ds, const double sm, const std::string& cr); double getSum()const; std::string getDate()const; std::string getType()const; std::string getCategory()const; std::string getDescription()const; std::string getCurrency()const; private: std::string date; std::string type; std::string category; std::string description; double sum; std::string currency; }; <file_sep>#include "Record.h" unsigned int Record::columns()const{ const unsigned int coloumnsCount=6; return coloumnsCount; } bool Record::operator<(const Record& rhs)const{ if(date<rhs.date) return true; if(date>rhs.date) return false; if(category<rhs.category) return true; if(category>rhs.category) return false; if (description<rhs.description) return true; if (description>rhs.description) return false; if (sum<rhs.sum) return true; else return false; } double Record::getSum()const{ return sum; } std::string Record::getDate()const{ return date; } Record::Type Record::getType()const{ return type; } std::string Record::getCategory()const{ return category; } std::string Record::getDescription()const{ return description; } Record::Currency Record::getCurrency()const{ return currency; } void Record::setDate(const std::string& d){ date=d; } void Record::setType(const Record::Type t){ type=t; } void Record::setCategory(const std::string& c){ category=c; } void Record::setDescription(const std::string& d){ description=d; } void Record::setSum(const double s){ sum=s; } void Record::setCurrency(const Record::Currency c){ currency=c; } Record::Record(const RecordString &record){ date=record.getDate(); std::string typeString=record.getType(); if(typeString=="Прибыль") type=Record::Type::PROFIT; if(typeString=="Убыток") type=Record::Type::LOSS; category=record.getCategory(); description=record.getDescription(); sum=record.getSum(); std::string currencyString=record.getCurrency(); if(currencyString=="USD") currency=Record::Currency::USD; if(currencyString=="BYR") currency=Record::Currency::BYR; if(currencyString=="RUB") currency=Record::Currency::RUB; if(currencyString=="EUR") currency=Record::Currency::EUR; } RecordString Record::convertToString()const{ std::string typeString; if(type==Record::Type::LOSS) typeString="Убыток"; if(type==Record::Type::PROFIT) typeString="Прибыль"; std::string currencyString; if(currency==Record::Currency::BYR) currencyString="BYR"; if(currency==Record::Currency::USD) currencyString="USD"; if(currency==Record::Currency::RUB) currencyString="RUB"; if(currency==Record::Currency::EUR) currencyString="EUR"; return {date,typeString,category,description,sum,currencyString}; } std::list<std::string> Record::getAllCurrencies() const{ return {"USD","BYR","RUB","EUR"}; } std::list<std::string> Record::getAllTypes() const{ return {"Прибыль","Убыток"}; } <file_sep>#pragma once #include <fstream> #include <iostream> #include <list> #include <memory> #include <vector> #include <string> #include "SRC/DataBase/DataOperations.h" #include "SRC/BusinessLogic/User.h" class UserFileOperations{ public: UserFileOperations(); bool isUserCreated(const std::string& login, const std::string& password); std::list<std::string> getUsersNames()const; bool deleteUser(const std::string& login,const std::string& password); bool changedPassword(const std::string& login,const std::string& oldPassword,const std::string& newPassword); std::string getUserName()const; bool checkPassword(const User& userChecking); private: std::string settingsFileName="settings.ac"; std::vector<User> users; User currentUser; bool userIsOnList(const User& user)const; void loadUsers(); void saveUsers(); }; <file_sep>#include "DataOperations.h" void DataFileOperations::saveToFile(std::string fileName)const{ fileName+=".dat"; std::ofstream file{fileName}; if(!file) throw "File wasn't created"; unsigned int rows=pData->rows(); for(unsigned int i=0;i<rows;++i) save(file,pData->getRecord(i)); } void DataFileOperations::loadFromFile(std::string fileName){ fileName+=".dat"; std::ifstream file{fileName}; if(!file) throw "File doesn't exist"; int i=0; while(!file.eof()){ Record rec=load(file); if(rec.getDate()!="") pData->setRecord(i,rec.convertToString()); i++; } } Record DataFileOperations::load(std::ifstream& dataStream){ Record record; char c; std::string tmp; //Date while(dataStream.get(c) && c!=separatorRecord){ tmp += c; } record.setDate(tmp); //Type int typeInt=0; dataStream>>typeInt; if(typeInt==static_cast<int>(Record::Type::PROFIT)) record.setType(Record::Type::PROFIT); if(typeInt==static_cast<int>(Record::Type::LOSS)) record.setType(Record::Type::LOSS); dataStream.get(c); //separatorRecord //Category tmp.clear(); while(dataStream.get(c) && c!=separatorRecord){ tmp += c; } record.setCategory(tmp); //Description tmp.clear(); while(dataStream.get(c) && c!=separatorRecord){ tmp += c; } record.setDescription(tmp); //Sum double sum=0; dataStream>>sum; record.setSum(sum); dataStream.get(c); //separatorRecord //Currency int currencyInt=0; dataStream>>currencyInt; record.setCurrency(static_cast<Record::Currency>(currencyInt)); dataStream.get(c); // '\n' return record; } void DataFileOperations::save(std::ofstream& dataStream,const Record& record)const{ dataStream<<record.getDate()<<separatorRecord <<static_cast<int>(record.getType())<<separatorRecord <<record.getCategory()<<separatorRecord <<record.getDescription()<<separatorRecord <<record.getSum()<<separatorRecord <<static_cast<int>(record.getCurrency())<<'\n'; } void DataFileOperations::deleteFile(std::string fileName){ fileName+=".dat"; std::remove(fileName.c_str()); } <file_sep>#include "BusinessLogic.h" BusinessLogic::BusinessLogic(std::shared_ptr<AbstractData> data, std::shared_ptr<AbstractDataFileOperations> operations): pData(data),pDataOperations(operations){ pOperations=std::make_shared<RecordsOperations>(data); pCalculator=std::make_unique<BalanceCalculator>(data,pOperations); pUserFileOperations=std::make_unique<UserFileOperations>(); pReport=std::make_shared<Report>(data); pReportSaveTxt=std::make_unique<ReportSaveTxt>(pReport); //pReportSavePdf=std::make_unique<ReportSavePdf>(pReport); pGraphicBuilder=std::make_unique<GraphicBuilder>(pReport); } unsigned int BusinessLogic::rowsCount() const{ return pData->rows(); } unsigned int BusinessLogic::columnsCount() const{ return pData->columns(); } void BusinessLogic::setData(const unsigned int row, const RecordString& record){ pData->setRecord(row,record); } RecordString BusinessLogic::getData(const unsigned int row) const{ return pData->getRecord(row); } void BusinessLogic::removeRow(const unsigned int row){ pData->remove(row); } void BusinessLogic::sortData(){ pData->sort(); } std::list<std::string> BusinessLogic::getDataCategories(const std::string& type) const{ return pOperations->getCategories(type); } std::list<std::string> BusinessLogic::getDataDescriptions(const std::string& category) const{ return pOperations->getDescriptions(category); } unsigned int BusinessLogic::rowsCountReport() const{ return pReport->rowsCount(); } RecordString BusinessLogic::getReport(const unsigned int row) const{ return pReport->getRow(row); } void BusinessLogic::filter(const std::string& dateFrom, const std::string& dateTo, const std::pair<bool,bool>& type, const std::vector<std::string>& category, const std::vector<std::string>& description, const double &sumFrom, const double &sumTo, const std::vector<std::string>& currency){ pReport->filterDB(dateFrom,dateTo,type,category,description,sumFrom,sumTo,currency); } std::list<std::string> BusinessLogic::getReportCategories(const bool profit, const bool loss)const{ return pReport->getCategories(profit,loss); } std::list<std::string> BusinessLogic::getReportDescriptions(const std::vector<std::string> &categories)const{ return pReport->getDescriptions(categories); } std::pair<std::string,std::string> BusinessLogic::dateMinMax()const{ return pReport->dateMinMax(); } std::pair<double,double> BusinessLogic::sumMinMax()const{ return pReport->sumMinMax(); } void BusinessLogic::saveReportTxt(const std::string& fileName,const std::string& currentDate) const{ pReportSaveTxt->saveTxt(fileName,pUserFileOperations->getUserName(),currentDate); } void BusinessLogic::saveReportPDF(const std::string& fileName,const std::string& currentDate) const{ //pReportSavePdf->savePDF(fileName,pUserFileOperations->getUserName(),currentDate); } std::string BusinessLogic::getBalance(const std::string& currentDate)const{ return pCalculator->getBalance(currentDate); } std::list<std::string> BusinessLogic::getUsersNames() const{ return pUserFileOperations->getUsersNames(); } bool BusinessLogic::isUserCreated(const std::string &login, const std::string &password){ bool result=pUserFileOperations->isUserCreated(login,password); if(result) pDataOperations->saveToFile(pUserFileOperations->getUserName()); return result; } bool BusinessLogic::loadData(const std::string& login, const std::string& password){ bool result=pUserFileOperations->checkPassword({login,password}); if(result) pDataOperations->loadFromFile(pUserFileOperations->getUserName()); return result; } void BusinessLogic::clearData(){ pData->clear(); } bool BusinessLogic::deleteUser(const std::string &login, const std::string &password){ bool result=pUserFileOperations->deleteUser(login,password); if(result) pDataOperations->deleteFile(pUserFileOperations->getUserName()); return result; } bool BusinessLogic::changePassword(const std::string &login, const std::string &oldPassword, const std::string &newPassword){ return pUserFileOperations->changedPassword(login,oldPassword,newPassword); } void BusinessLogic::saveData() const{ pDataOperations->saveToFile(pUserFileOperations->getUserName()); } std::list<std::string> BusinessLogic::getCurrencies() const{ return pOperations->getCurrencies(); } std::list<std::string> BusinessLogic::getAllCurrencies() const{ return pData->getAllCurrencies(); } std::list<std::string> BusinessLogic::getAllTypes() const{ return pData->getAllTypes(); } void BusinessLogic::updateReport(){ pReport->update(); } std::string BusinessLogic::getUserName()const{ return pUserFileOperations->getUserName(); } std::pair<double,double> BusinessLogic::getMinMaxSum(){ return pGraphicBuilder->getMinMaxSum(); } std::vector<std::pair<std::string,double>> BusinessLogic::getPoints(){ return pGraphicBuilder->getPoints(); } void BusinessLogic::printReport(const std::string& currentDate){ ReportPrint report(pReport); report.printReport(pUserFileOperations->getUserName(),currentDate); }
9de656908edc5b1ea9f70229ae3fb31836b4bb6f
[ "Markdown", "CMake", "C++" ]
49
C++
Lukas1584/Accountant
7ce8d33659f51dc613874aab336248f3c56cb25b
9531fe6c6b791c5032848f5f0196cd2ec5efd2ca
refs/heads/master
<repo_name>danilodahlen/search-zipcode-app<file_sep>/src/about/about.jsx import React from 'react' export default props => ( <div> <h2>Quem somos</h2> <p> Somos uma plataforma tecnológica que quer mudar a forma de comprar e vender seu carro seminovo. Juntamos inovação, conhecimento e expertise do negócio para conectar vendedores e compradores, agilizando, sendo mais eficientes e barato que os canais tradicionais de venda, gerando assim negociações justa para todos. Garantir segurança, qualidade dos veículos e evitar risco de fraude é fundamental para nós, por isso inspecionamos rigorosamente todos os carros. Também, para sua tranquilidade, tiramos as fotos, fazemos os anúncios, cuidamos de toda negociação e resolvemos a papelada no final. </p> <p><strong>By</strong> Carflix</p> </div> ) <file_sep>/src/template/labelError.jsx import React from 'react'; export default props => ( <div> <label className="label-error" for="lblErro">{ props.errorMenssager || "" }</label> </div> )<file_sep>/src/zipcode/zipcodeForm.jsx import React from 'react'; import LabelError from '../template/labelError'; export default props => ( <div> <form className="form"> <div className="form-group"> <label for="txtZIP">Search for zip code:</label> <input type="text" className="form-control" id="txtZIP" placeholder="06458-620" onChange={ props.changeValue } value={ props.code } onKeyPress={ props.keyPress } > </input> <LabelError errorMenssager={ props.errorMenssager }/> </div> <button className="btn btn-primary" id="btnSearch" onClick={ props.searchValue } >Search</button> <button className="btn btn-default" id="btnClear" onClick={ props.clearValue } >Clear</button> </form> </div> ) <file_sep>/src/zipcode/zipcodeList.jsx import React from 'react' export default props => { const buildBody = () => { const list = props.list || []; return list.map(object => ( <tr key={object.cep}> <td>{ object.cep }</td> <td>{ object.logradouro }</td> <td>{ object.bairro }</td> <td>{ object.localidade }</td> <td>{ object.uf }</td> </tr> )); } return( <div> <table className="table"> <thead className="thead-dark"> <tr> <th scope="col">Zip code</th> <th scope="col">Avenue/Street</th> <th scope="col">District</th> <th scope="col">City</th> <th scope="col">State</th> </tr> </thead> <tbody> {buildBody()} </tbody> </table> </div>) }
50078a889960c348341b258620b9d5e0a0b0b140
[ "JavaScript" ]
4
JavaScript
danilodahlen/search-zipcode-app
e75c1c52ac04963bf21cfccfa35a9a18d808e2c4
fe69c71d48365d0bd17dff31d23d43758535ba9c
refs/heads/master
<repo_name>pezhore/AnsibleSourceFiles<file_sep>/.bashrc # ~/.bashrc: executed by bash(1) for non-login shells. # see /usr/share/doc/bash/examples/startup-files (in the package bash-doc) # for examples # If not running interactively, don't do anything case $- in *i*) ;; *) return;; esac # don't put duplicate lines or lines starting with space in the history. # See bash(1) for more options HISTCONTROL=ignoreboth # append to the history file, don't overwrite it shopt -s histappend # for setting history length see HISTSIZE and HISTFILESIZE in bash(1) HISTSIZE=1000 HISTFILESIZE=2000 # Alias definitions. # You may want to put all your additions into a separate file like # ~/.bash_aliases, instead of adding them here directly. # See /usr/share/doc/bash-doc/examples in the bash-doc package. if [ -f ~/.bash_aliases ]; then . ~/.bash_aliases fi # enable programmable completion features (you don't need to enable # this, if it's already enabled in /etc/bash.bashrc and /etc/profile # sources /etc/bash.bashrc). if ! shopt -oq posix; then if [ -f /usr/share/bash-completion/bash_completion ]; then . /usr/share/bash-completion/bash_completion elif [ -f /etc/bash_completion ]; then . /etc/bash_completion fi fi if [ $(which rbenv) ] then export PATH="$HOME/.rbenv/bin:$PATH" eval "$(rbenv init -)" export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH" fi if [[ $- == *i* ]] then bind '"\e[A": history-search-backward' bind '"\e[B": history-search-forward' fi GIT_PROMPT_ONLY_IN_REPO=1 GIT_PROMPT_THEME=Solarized_Ubuntu source ~/.bash-git-prompt/gitprompt.sh PATH=$HOME/.local/bin:$PATH #THIS MUST BE AT THE END OF THE FILE FOR SDKMAN TO WORK!!! export SDKMAN_DIR="/home/pezhore/.sdkman" [[ -s "/home/pezhore/.sdkman/bin/sdkman-init.sh" ]] && source "/home/pezhore/.sdkman/bin/sdkman-init.sh"<file_sep>/README.md # AnsibleSourceFiles Repository of Ansible source files for Vagrant, VM deployments # Contents * .bashrc - default bashrc file, contains portions for gitprompt and sdkman * .inputrc - configures arrow up for search backward, arrow down for search formward in bash * .tmux.conf - default tmux config, including changes to bind key `[Ctrl]-[a]`, tmux plugins * .vimrc - default vimrc file, contains YouCompleteMe plugin for python completion and a suite of other vim plugins * .vimrc.NoYCM - Same as above, but without YouCompleteMe (useful for raspbian/other distros that don't have the necessary vim-gtk package) * Ghost\nginx_default - a simple nginx proxypass for local Ghost development <file_sep>/.bash_aliases # enable color support of ls and also add handy aliases if [ -x /usr/bin/dircolors ]; then test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)" alias ls='ls --color=auto' #alias dir='dir --color=auto' #alias vdir='vdir --color=auto' alias grep='grep --color=auto' alias fgrep='fgrep --color=auto' alias egrep='egrep --color=auto' fi # some more ls aliases alias ll='ls -alF' alias la='ls -A' alias l='ls -CF' alias apt='sudo apt' alias apt-get='sudo apt-get' # Add an "alert" alias for long running commands. Use like so: # sleep 10; alert alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"' # Quack Quack alias ducks='du -cks * | sort -rn | while read size fname; do for unit in k M G T P E Z Y; do if [ $size -lt 1024 ]; then echo -e "${size}${unit}\t${fname}"; break; fi; size=$((size/1024)); done; done'
4376918c0d7f64eadba42543834d5ea26f74b0a0
[ "Markdown", "Shell" ]
3
Shell
pezhore/AnsibleSourceFiles
a20caa63679a0d5e4616a3353c6b84052fd3ffe2
1cc14ec8b9b075466adb57d8b40c3f79ea97dd25
refs/heads/master
<repo_name>sriyag/project32<file_sep>/app/src/main/java/com/example/sriyag/drawingapp2/MainActivity.java package com.example.sriyag.drawingapp2; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.provider.MediaStore; import android.support.v4.content.ContextCompat; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.Toast; import java.util.UUID; public class MainActivity extends Activity implements View.OnClickListener { private DrawingView drawView; //canvas: DrawingView class extends View private ImageButton currPaint, drawBtn, eraseBtn, newBtn, saveBtn, typeBtn; //top row: 5 icons private float smallPencil, mediumPencil, largePencil; //pencil size private EditText et1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); //Initialize all the views and form widgets in activity_main.xml et1 = (EditText) findViewById(R.id.et1); et1.setVisibility(View.INVISIBLE); //initially hidden smallPencil = getResources().getInteger(R.integer.small_size); mediumPencil = getResources().getInteger(R.integer.medium_size); largePencil = getResources().getInteger(R.integer.large_size); drawBtn = (ImageButton)findViewById(R.id.draw_btn); eraseBtn = (ImageButton)findViewById(R.id.erase_btn); eraseBtn.setOnClickListener(this); newBtn = (ImageButton)findViewById(R.id.new_btn); newBtn.setOnClickListener(this); saveBtn = (ImageButton)findViewById(R.id.save_btn); saveBtn.setOnClickListener(this); typeBtn = (ImageButton)findViewById(R.id.type_btn); typeBtn.setOnClickListener(this); // Set the class up as a click listener for the button drawBtn.setOnClickListener(this); // instantiate this variable by retrieving a reference to it from the layout: drawView = (DrawingView) findViewById(R.id.drawing); /* drawView.setLongClickable(true); drawView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { final CharSequence[] items = {"Start Typing"}; AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("Start Typing?"); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show(); et1.setVisibility(View.VISIBLE); //et1.setHeight(); InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(et1, InputMethodManager.SHOW_IMPLICIT); } }); AlertDialog alert = builder.create(); alert.show(); //registerForContextMenu(drawView); //openContextMenu(drawView); return true; } }); */ LinearLayout paintLayout = (LinearLayout) findViewById(R.id.paint_colors); currPaint = (ImageButton)paintLayout.getChildAt(0); // use a different drawable image on the button to show that it is currently selected currPaint.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.paint_pressed)); } public void paintClicked(View view){ //use chosen color drawView.setErase(false); drawView.setBrushSize(drawView.getLastBrushSize()); if(view!=currPaint){ //update color, retrieve the tag we set for each button in the layout, representing the chosen color ImageButton imgView = (ImageButton) view; String color = view.getTag().toString(); drawView.setColor(color); // update the UI to reflect the new chosen paint and set the previous one back to normal imgView.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.paint_pressed)); currPaint.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.paint)); currPaint=(ImageButton)view; } } @Override public void onClick(View view){ //respond to clicks if(view.getId()==R.id.draw_btn){ //draw button clicked final Dialog brushDialog = new Dialog(this); brushDialog.setTitle("Pencil size:"); brushDialog.setContentView(R.layout.pencil_size_chooser); ImageButton smallBtn = (ImageButton)brushDialog.findViewById(R.id.small_pencil); smallBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { drawView.setBrushSize(smallPencil); drawView.setLastBrushSize(smallPencil); drawView.setErase(false); brushDialog.dismiss(); } }); ImageButton mediumBtn = (ImageButton)brushDialog.findViewById(R.id.medium_pencil); mediumBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { drawView.setBrushSize(mediumPencil); drawView.setLastBrushSize(mediumPencil); drawView.setErase(false); brushDialog.dismiss(); } }); ImageButton largeBtn = (ImageButton)brushDialog.findViewById(R.id.large_pencil); largeBtn.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { drawView.setBrushSize(largePencil); drawView.setLastBrushSize(largePencil); drawView.setErase(false); brushDialog.dismiss(); } }); brushDialog.show(); } else if(view.getId()==R.id.erase_btn){ //switch to erase - choose size final Dialog brushDialog = new Dialog(this); brushDialog.setTitle("Eraser size:"); brushDialog.setContentView(R.layout.pencil_size_chooser); ImageButton smallBtn = (ImageButton)brushDialog.findViewById(R.id.small_pencil); smallBtn.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { drawView.setErase(true); drawView.setBrushSize(5); brushDialog.dismiss(); } }); ImageButton mediumBtn = (ImageButton)brushDialog.findViewById(R.id.medium_pencil); mediumBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { drawView.setErase(true); drawView.setBrushSize(10); brushDialog.dismiss(); } }); ImageButton largeBtn = (ImageButton)brushDialog.findViewById(R.id.large_pencil); largeBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { drawView.setErase(true); drawView.setBrushSize(20); brushDialog.dismiss(); } }); brushDialog.show(); } else if(view.getId()==R.id.new_btn){ //new button AlertDialog.Builder newDialog = new AlertDialog.Builder(this); newDialog.setTitle("New drawing"); newDialog.setMessage("Start new drawing (you will lose the current drawing)?"); newDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { drawView.startNew(); et1.clearComposingText(); et1.setText(""); et1.destroyDrawingCache(); drawView.buildDrawingCache(); drawView.bringToFront(); dialog.dismiss(); } }); newDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); newDialog.show(); } else if(view.getId()==R.id.save_btn){ //save drawing AlertDialog.Builder saveDialog = new AlertDialog.Builder(this); saveDialog.setTitle("Save drawing"); saveDialog.setMessage("Save drawing to device Gallery?"); saveDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { //save drawing // enable the drawing cache on the custom View drawView.setDrawingCacheEnabled(true); //write image to file /*pass the content resolver, drawing cache for the displayed View, a randomly generated UUID string for the filename with PNG extension and a short description. The method returns the URL of the image created, or null if the operation was unsuccessful - this lets us give user feedback:*/ String imgSaved = MediaStore.Images.Media.insertImage( getContentResolver(), drawView.getDrawingCache(), UUID.randomUUID().toString()+".png", "drawing"); if(imgSaved!=null){ Toast savedToast = Toast.makeText(getApplicationContext(), "Drawing saved to Gallery!", Toast.LENGTH_SHORT); savedToast.show(); } else{ Toast unsavedToast = Toast.makeText(getApplicationContext(), "Oops! Image could not be saved.", Toast.LENGTH_SHORT); unsavedToast.show(); } drawView.destroyDrawingCache(); } }); saveDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int which){ dialog.cancel(); } }); saveDialog.show(); } else if(view.getId()==R.id.type_btn){ //save drawing AlertDialog.Builder typeDialog = new AlertDialog.Builder(this); typeDialog.setTitle("Type"); typeDialog.setMessage("Start typing?"); typeDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { et1.setVisibility(View.VISIBLE); et1.bringToFront(); et1.setHeight(LinearLayout.LayoutParams.MATCH_PARENT); InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(et1, InputMethodManager.SHOW_IMPLICIT); } }); typeDialog.setNegativeButton("No", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int which){ dialog.cancel(); } }); typeDialog.show(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
3cdf3d167f684779ef965a1980022e0890bc9a79
[ "Java" ]
1
Java
sriyag/project32
ac78ef8c856bb2c439050e146bbf05c529b2a4ef
a9e01cfbad913354e40a370b65f4ea7db36d1ace
refs/heads/master
<repo_name>dulumao/php-srouter<file_sep>/src/AbstractRouter.php <?php /** * Created by PhpStorm. * User: inhere * Date: 2017/10/17 * Time: 下午11:37 */ namespace Inhere\Route; /** * Class AbstractRouter * @package Inhere\Route * @method get(string $route, mixed $handler, array $opts = []) * @method post(string $route, mixed $handler, array $opts = []) * @method put(string $route, mixed $handler, array $opts = []) * @method delete(string $route, mixed $handler, array $opts = []) * @method options(string $route, mixed $handler, array $opts = []) * @method head(string $route, mixed $handler, array $opts = []) * @method search(string $route, mixed $handler, array $opts = []) * @method connect(string $route, mixed $handler, array $opts = []) * @method trace(string $route, mixed $handler, array $opts = []) * @method any(string $route, mixed $handler, array $opts = []) */ abstract class AbstractRouter implements RouterInterface { /** * some available patterns regex * $router->get('/user/{id}', 'handler'); * @var array */ protected static $globalParams = [ 'all' => '.*', 'any' => '[^/]+', // match any except '/' 'num' => '[1-9][0-9]*', // match a number and gt 0 'int' => '\d+', // match a number 'act' => '[a-zA-Z][\w-]+', // match a action name ]; /** @var bool */ protected $initialized = false; /** @var string */ protected $currentGroupPrefix; /** @var array */ protected $currentGroupOption; /** * static Routes - no dynamic argument match * 整个路由 path 都是静态字符串 e.g. '/user/login' * @var array[] * [ * '/user/login' => [ * // METHOD => [...] * 'GET' => [ * 'handler' => 'handler', * 'option' => [...], * ], * 'PUT' => [ * 'handler' => 'handler', * 'option' => [...], * ], * ... * ], * ... ... * ] */ protected $staticRoutes = []; /** * regular Routes - have dynamic arguments, but the first node is normal string. * 第一节是个静态字符串,称之为有规律的动态路由。按第一节的信息进行分组存储 * e.g '/hello/{name}' '/user/{id}' * @var array[] * [ * // 使用完整的第一节作为key进行分组 * 'add' => [ * [ * 'start' => '/add/', * 'regex' => '/add/(\w+)', * 'methods' => 'GET', * 'handler' => 'handler', * 'option' => [...], * ], * ... * ], * 'blog' => [ * [ * 'start' => '/blog/post-', * 'regex' => '/blog/post-(\w+)', * 'methods' => 'GET', * 'handler' => 'handler', * 'option' => [...], * ], * ... * ], * ... ... * ] */ protected $regularRoutes = []; /** * vague Routes - have dynamic arguments,but the first node is exists regex. * 第一节就包含了正则匹配,称之为无规律/模糊的动态路由 * e.g '/{name}/profile' '/{some}/{some2}' * @var array * [ * // 使用 HTTP METHOD 作为 key进行分组 * 'GET' => [ * [ * // 必定包含的字符串 * 'include' => '/profile', * 'regex' => '/(\w+)/profile', * 'handler' => 'handler', * 'option' => [...], * ], * ... * ], * 'POST' => [ * [ * 'include' => null, * 'regex' => '/(\w+)/(\w+)', * 'handler' => 'handler', * 'option' => [...], * ], * ... * ], * ... ... * ] */ protected $vagueRoutes = []; /******************************************************************************* * router config ******************************************************************************/ /** * Match all request. * 1. If is a valid URI path, will matchAll all request uri to the path. * 2. If is a closure, will matchAll all request then call it * eg: '/site/maintenance' or `function () { echo 'System Maintaining ... ...'; }` * @var mixed */ public $matchAll; /** * Setting a routes file. * @var string */ public $routesFile; /** * Ignore last slash char('/'). If is True, will clear last '/'. * @var bool */ public $ignoreLastSlash = false; /** * @var bool NotAllowed As NotFound. If True, only two status value will be return(FOUND, NOT_FOUND). */ public $notAllowedAsNotFound = false; /** * Auto route match @like yii framework * If is True, will auto find the handler controller file. * @var bool */ public $autoRoute = false; /** * The default controllers namespace. eg: 'App\\Controllers' * @var string */ public $controllerNamespace; /** * Controller suffix, is valid when '$autoRoute' = true. eg: 'Controller' * @var string */ public $controllerSuffix = 'Controller'; /** * object creator. * @param array $config * @return self * @throws \LogicException */ public static function make(array $config = []): AbstractRouter { return new static($config); } /** * object constructor. * @param array $config * @throws \LogicException */ public function __construct(array $config = []) { $this->setConfig($config); $this->currentGroupPrefix = ''; $this->currentGroupOption = []; // load routes if (($file = $this->routesFile) && is_file($file)) { require $file; } } /** * @param array $config * @throws \LogicException */ public function setConfig(array $config) { if ($this->initialized) { throw new \LogicException('Routing has been added, and configuration is not allowed!'); } static $props = [ 'routesFile' => 1, 'ignoreLastSlash' => 1, 'tmpCacheNumber' => 1, 'notAllowedAsNotFound' => 1, 'matchAll' => 1, 'autoRoute' => 1, 'controllerNamespace' => 1, 'controllerSuffix' => 1, ]; foreach ($config as $name => $value) { if (isset($props[$name])) { $this->$name = $value; } } } /******************************************************************************* * route collection ******************************************************************************/ /** * Defines a route callback and method * @param string $method * @param array $args * @return static * @throws \LogicException * @throws \InvalidArgumentException */ public function __call($method, array $args) { if (\in_array(strtoupper($method), self::ALLOWED_METHODS, true)) { if (\count($args) < 2) { throw new \InvalidArgumentException("The method [$method] parameters is missing."); } return $this->map($method, ...$args); } throw new \InvalidArgumentException("The method [$method] not exists in the class."); } /** * quick register a group restful routes for the controller class. * ```php * $router->rest('/users', UserController::class); * ``` * @param string $prefix eg '/users' * @param string $controllerClass * @param array $map You can append or change default map list. * [ * 'index' => null, // set value is empty to delete. * 'list' => 'get', // add new route * ] * @param array $opts Common options * @return static * @throws \LogicException * @throws \InvalidArgumentException */ public function rest($prefix, $controllerClass, array $map = [], array $opts = []): AbstractRouter { $map = array_merge([ 'index' => ['GET'], 'create' => ['POST'], 'view' => ['GET', '{id}', ['id' => '[1-9]\d*']], 'update' => ['PUT', '{id}', ['id' => '[1-9]\d*']], 'patch' => ['PATCH', '{id}', ['id' => '[1-9]\d*']], 'delete' => ['DELETE', '{id}', ['id' => '[1-9]\d*']], ], $map); //$opts = array_merge([], $opts); foreach ($map as $action => $conf) { if (!$conf || !$action) { continue; } $route = $prefix; // '/users/{id}' if (isset($conf[1]) && ($subPath = trim($conf[1]))) { // allow define a abs route. '/user-other-info'. it's not prepend prefix. $route = $subPath[0] === '/' ? $subPath : $prefix . '/' . $subPath; } if (isset($conf[2])) { $opts['params'] = $conf[2]; } $this->map($conf[0], $route, $controllerClass . '@' . $action, $opts); } return $this; } /** * quick register a group universal routes for the controller class. * ```php * $router->rest('/users', UserController::class, [ * 'index' => 'get', * 'create' => 'post', * 'update' => 'post', * 'delete' => 'delete', * ]); * ``` * @param string $prefix eg '/users' * @param string $controllerClass * @param array $map You can append or change default map list. * [ * 'index' => null, // set value is empty to delete. * 'list' => 'get', // add new route * ] * @param array $opts Common options * @return static * @throws \LogicException * @throws \InvalidArgumentException */ public function ctrl($prefix, $controllerClass, array $map = [], array $opts = []): AbstractRouter { foreach ($map as $action => $method) { if (!$method || !\is_string($action)) { continue; } if ($action) { $route = $prefix . '/' . $action; } else { $route = $prefix; $action = 'index'; } $this->map($method, $route, $controllerClass . '@' . $action, $opts); } return $this; } /** * Create a route group with a common prefix. * All routes created in the passed callback will have the given group prefix prepended. * @ref package 'nikic/fast-route' * @param string $prefix * @param \Closure $callback * @param array $opts */ public function group(string $prefix, \Closure $callback, array $opts = []) { $previousGroupPrefix = $this->currentGroupPrefix; $this->currentGroupPrefix = $previousGroupPrefix . '/' . trim($prefix, '/'); $previousGroupOption = $this->currentGroupOption; $this->currentGroupOption = $opts; $callback($this); $this->currentGroupPrefix = $previousGroupPrefix; $this->currentGroupOption = $previousGroupOption; } /** * validate and format arguments * @param string|array $methods * @param mixed $handler * @return array * @throws \InvalidArgumentException */ public function validateArguments($methods, $handler): array { if (!$methods || !$handler) { throw new \InvalidArgumentException('The method and route handler is not allow empty.'); } $allow = self::ALLOWED_METHODS_STR . ','; $hasAny = false; $methods = array_map(function ($m) use ($allow, &$hasAny) { $m = strtoupper(trim($m)); if (!$m || false === strpos($allow, $m . ',')) { throw new \InvalidArgumentException("The method [$m] is not supported, Allow: " . trim($allow, ',')); } if (!$hasAny && $m === self::ANY) { $hasAny = true; } return $m; }, (array)$methods); return $hasAny ? self::ALLOWED_METHODS : $methods; } /** * is Static Route * @param string $route * @return bool */ public static function isStaticRoute($route): bool { return strpos($route, '{') === false && strpos($route, '[') === false; } /** * @param string $path * @param bool $ignoreLastSlash * @return string */ protected function formatUriPath($path, $ignoreLastSlash): string { // clear '//', '///' => '/' if (false !== strpos($path, '//')) { $path = (string)preg_replace('#\/\/+#', '/', $path); } // decode $path = rawurldecode($path); // setting 'ignoreLastSlash' if ($path !== '/' && $ignoreLastSlash) { $path = rtrim($path, '/'); } return $path; } /** * @param array $matches * @param array $conf */ protected function filterMatches(array $matches, array &$conf) { if (!$matches) { $conf['matches'] = []; return; } // clear all int key $matches = array_filter($matches, '\is_string', ARRAY_FILTER_USE_KEY); // apply some default param value if (isset($conf['option']['defaults'])) { $conf['matches'] = array_merge($conf['option']['defaults'], $matches); } else { $conf['matches'] = $matches; } } /** * parse param route * @param string $route * @param array $params * @param array $conf * @return array * @throws \LogicException */ public function parseParamRoute(string $route, array $params, array $conf): array { $bak = $route; $noOptional = null; // 解析可选参数位 if (false !== ($pos = strpos($route, '['))) { // $hasOptional = true; $noOptional = substr($route, 0, $pos); $withoutClosingOptionals = rtrim($route, ']'); $optionalNum = \strlen($route) - \strlen($withoutClosingOptionals); if ($optionalNum !== substr_count($withoutClosingOptionals, '[')) { throw new \LogicException('Optional segments can only occur at the end of a route'); } // '/hello[/{name}]' -> '/hello(?:/{name})?' $route = str_replace(['[', ']'], ['(?:', ')?'], $route); } // quote '.','/' to '\.','\/' if (false !== strpos($route, '.')) { // $route = preg_quote($route, '/'); $route = str_replace('.', '\.', $route); } // 解析参数,替换为对应的 正则 if (preg_match_all('#\{([a-zA-Z_][a-zA-Z0-9_-]*)\}#', $route, $m)) { /** @var array[] $m */ $replacePairs = []; foreach ($m[1] as $name) { $key = '{' . $name . '}'; $regex = $params[$name] ?? self::DEFAULT_REGEX; // 将匹配结果命名 (?P<arg1>[^/]+) $replacePairs[$key] = '(?P<' . $name . '>' . $regex . ')'; // $replacePairs[$key] = '(' . $regex . ')'; } $route = strtr($route, $replacePairs); } // 分析路由字符串是否是有规律的 $first = null; $conf['regex'] = '#^' . $route . '$#'; // first node is a normal string // e.g '/user/{id}' first: 'user', '/a/{post}' first: 'a' if (preg_match('#^/([\w-]+)/[\w-]*/?#', $bak, $m)) { $first = $m[1]; $conf['start'] = $m[0]; return [$first, $conf]; } // first node contain regex param '/hello[/{name}]' '/{some}/{some2}/xyz' $include = null; if ($noOptional) { if (strpos($noOptional, '{') === false) { $include = $noOptional; } else { $bak = $noOptional; } } if (!$include && preg_match('#/([\w-]+)/?[\w-]*#', $bak, $m)) { $include = $m[0]; } $conf['include'] = $include; return [$first, $conf]; } /** * @param array $routesData * @param string $path * @param string $method * @return array */ abstract protected function findInRegularRoutes(array $routesData, string $path, string $method): array; /** * @param array $routesData * @param string $path * @param string $method * @return array */ abstract protected function findInVagueRoutes(array $routesData, string $path, string $method): array; /** * handle auto route match, when config `'autoRoute' => true` * @param string $path The route path * @internal string $cnp controller namespace. eg: 'app\\controllers' * @internal string $sfx controller suffix. eg: 'Controller' * @return bool|callable */ public function matchAutoRoute(string $path) { if (!$cnp = trim($this->controllerNamespace)) { return false; } $sfx = trim($this->controllerSuffix); $tmp = trim($path, '/- '); // one node. eg: 'home' if (!strpos($tmp, '/')) { $tmp = self::convertNodeStr($tmp); $class = "$cnp\\" . ucfirst($tmp) . $sfx; return class_exists($class) ? $class : false; } $ary = array_map([self::class, 'convertNodeStr'], explode('/', $tmp)); $cnt = \count($ary); // two nodes. eg: 'home/test' 'admin/user' if ($cnt === 2) { list($n1, $n2) = $ary; // last node is an controller class name. eg: 'admin/user' $class = "$cnp\\$n1\\" . ucfirst($n2) . $sfx; if (class_exists($class)) { return $class; } // first node is an controller class name, second node is a action name, $class = "$cnp\\" . ucfirst($n1) . $sfx; return class_exists($class) ? "$class@$n2" : false; } // max allow 5 nodes if ($cnt > 5) { return false; } // last node is an controller class name $n2 = array_pop($ary); $class = sprintf('%s\\%s\\%s', $cnp, implode('\\', $ary), ucfirst($n2) . $sfx); if (class_exists($class)) { return $class; } // last second is an controller class name, last node is a action name, $n1 = array_pop($ary); $class = sprintf('%s\\%s\\%s', $cnp, implode('\\', $ary), ucfirst($n1) . $sfx); return class_exists($class) ? "$class@$n2" : false; } /** * @param array $tmpParams * @return array */ public function getAvailableParams(array $tmpParams): array { $params = self::$globalParams; if ($tmpParams) { foreach ($tmpParams as $name => $pattern) { $key = trim($name, '{}'); $params[$key] = $pattern; } } return $params; } /** * convert 'first-second' to 'firstSecond' * @param string $str * @return string */ public static function convertNodeStr($str): string { $str = trim($str, '-'); // convert 'first-second' to 'firstSecond' if (strpos($str, '-')) { $str = (string)preg_replace_callback('/-+([a-z])/', function ($c) { return strtoupper($c[1]); }, trim($str, '- ')); } return $str; } /** * @param array $params */ public function addGlobalParams(array $params) { foreach ($params as $name => $pattern) { $this->addGlobalParam($name, $pattern); } } /** * @param $name * @param $pattern */ public function addGlobalParam($name, $pattern) { $name = trim($name, '{} '); self::$globalParams[$name] = $pattern; } /** * @return array */ public static function getGlobalParams(): array { return self::$globalParams; } /** * @return array */ public static function getSupportedMethods(): array { return self::ALLOWED_METHODS; } /** * @param array $staticRoutes */ public function setStaticRoutes(array $staticRoutes) { $this->staticRoutes = $staticRoutes; } /** * @return array */ public function getStaticRoutes(): array { return $this->staticRoutes; } /** * @param \array[] $regularRoutes */ public function setRegularRoutes(array $regularRoutes) { $this->regularRoutes = $regularRoutes; } /** * @return \array[] */ public function getRegularRoutes(): array { return $this->regularRoutes; } /** * @param array $vagueRoutes */ public function setVagueRoutes(array $vagueRoutes) { $this->vagueRoutes = $vagueRoutes; } /** * @return array */ public function getVagueRoutes(): array { return $this->vagueRoutes; } } <file_sep>/docs/TODO.md # todo - 调整参数路由的解析,由现在的正则分析 -> 使用字符串分析 - 增加属性 `$routesData` 存储路由中不用于匹配的数据,减轻现有路由数据的复杂度 - 现有的变量 `$routesData` 改成 `$routesInfo` <file_sep>/src/Dispatcher/SimpleDispatcher.php <?php /** * Created by PhpStorm. * User: inhere * Date: 2017-12-29 * Time: 11:10 */ namespace Inhere\Route\Dispatcher; use Inhere\Route\ORouter; use Inhere\Route\RouterInterface; /** * Class SimpleDispatcher * @package Inhere\Route\Dispatcher */ class SimpleDispatcher implements DispatcherInterface { /** @var RouterInterface */ private $router; /** * some setting for self * @var array */ protected $options = [ // Filter the `/favicon.ico` request. 'filterFavicon' => false, // default action method name 'defaultAction' => 'index', 'actionPrefix' => '', 'actionSuffix' => 'Action', // enable dynamic action. // e.g // if set True; // $router->any('/demo/{act}', App\Controllers\Demo::class); // you access '/demo/test' will call 'App\Controllers\Demo::test()' 'dynamicAction' => false, // @see ORouter::$globalParams['act'] 'dynamicActionVar' => 'act', // action executor. will auto call controller's executor method to run all action. // e.g: 'actionExecutor' => 'run'` // $router->any('/demo/{act}', App\Controllers\Demo::class); // you access `/demo/test` will call `App\Controllers\Demo::run('test')` 'actionExecutor' => '', // 'run' // events ]; /** @var bool */ private $initialized; /** * object creator. * @param RouterInterface $router * @param array $options * @return self * @throws \LogicException */ public static function make(array $options = [], RouterInterface $router = null): DispatcherInterface { return new static($options, $router); } /** * object constructor. * @param RouterInterface $router * @param array $options * @throws \LogicException */ public function __construct(array $options = [], RouterInterface $router = null) { $this->initialized = false; $this->initOptions($options); if ($router) { $this->setRouter($router); } } /** * @param array $options * @throws \LogicException */ public function initOptions(array $options) { if ($this->initialized) { throw new \LogicException('Has already started to distributed routing, and configuration is not allowed!'); } foreach ($options as $name => $value) { if (isset($this->options[$name])) { $this->options[$name] = $value; } else { // maybe it is a event $this->on($name, $value); } } } /** * Runs the callback for the given path and method. * @param string $path * @param null|string $method * @return mixed * @throws \Throwable */ public function dispatchUri(string $path = null, string $method = null) { $path = $path ?: $_SERVER['REQUEST_URI']; if (strpos($path, '?')) { $path = parse_url($path, PHP_URL_PATH); } // if 'filterFavicon' setting is TRUE if ($path === self::FAV_ICON && $this->options['filterFavicon']) { return null; } $method = $method ?: $_SERVER['REQUEST_METHOD']; list($status, $path, $info) = $this->router->match($path, $method); $info['requestMethod'] = $method; return $this->dispatch($status, $path, $info); } /** * Dispatch route handler for the given route info. * @param int $status * @param string $path * @param array $info * @return mixed * @throws \Throwable */ public function dispatch(int $status, string $path, array $info) { $args = $info['matches'] ?? []; $method = $info['requestMethod'] ?? null; // not found if ($status === RouterInterface::NOT_FOUND) { return $this->handleNotFound($path, $method); } // method not allowed if ($status === RouterInterface::METHOD_NOT_ALLOWED) { return $this->handleNotAllowed($path, $method, $info); } $result = null; try { $result = $this->callRouteHandler($path, $method, $info['handler'], $args); } catch (\Exception $e) { $this->handleException($e, $path, $info); // throw new \RuntimeException($e->getMessage(), __LINE__, $e); } catch (\Throwable $e) { // throw new \RuntimeException($e->getMessage(), __LINE__, $e); $this->handleException($e, $path, $info); } return $result; } /** * execute the matched Route Handler * @param string $path The route path * @param string $method The request method * @param callable $handler The route path handler * @param array $args Matched param from path * [ * 'matches' => [] * ] * @return mixed * @throws \Throwable */ protected function callRouteHandler(string $path, string $method, $handler, array $args = []) { $vars = $args['matches']; $args = array_values($args); // is a \Closure or a callable object if (\is_object($handler)) { return $handler(...$args); } //// $handler is string // is array ['controller', 'action'] if (\is_array($handler)) { $segments = $handler; } elseif (\is_string($handler)) { // is function if (strpos($handler, '@') === false && \function_exists($handler)) { return $handler(...$args); } // e.g `Controllers\Home@index` Or only `Controllers\Home` $segments = explode('@', trim($handler)); } else { throw new \InvalidArgumentException('Invalid route handler'); } // Instantiation controller $controller = new $segments[0](); // Already assign action if (!empty($segments[1])) { $action = $segments[1]; // use dynamic action } elseif ($this->options['dynamicAction'] && ($var = $this->options['dynamicActionVar'])) { $action = isset($vars[$var]) ? trim($vars[$var], '/') : $this->options['defaultAction']; // defined default action } elseif (!$action = $this->options['defaultAction']) { throw new \RuntimeException("please config the route path [$path] controller action to call"); } $action = ORouter::convertNodeStr($action); $actionMethod = $action . $this->options['actionSuffix']; // if set the 'actionExecutor', the action handle logic by it. if ($executor = $this->options['actionExecutor']) { return $controller->$executor($actionMethod, $args); } // action method is not exist if (!method_exists($controller, $actionMethod)) { return $this->handleNotFound($path, $method, true); } // call controller's action method return $controller->$actionMethod(...$args); } /** * @param string $path Request uri path * @param string $method * @param bool $actionNotExist * True: The `$path` is matched success, but action not exist on route parser * False: The `$path` is matched fail * @return bool|mixed * @throws \Throwable */ protected function handleNotFound(string $path, string $method, $actionNotExist = false) { // Run the 'notFound' callback if the route was not found if (!$handler = $this->getOption(self::ON_NOT_FOUND)) { $handler = $this->defaultNotFoundHandler(); $this->setOption(self::ON_NOT_FOUND, $handler); // is a route path. like '/site/notFound' } else if (\is_string($handler) && '/' === $handler{0}) { $_GET['_src_path'] = $path; if ($path === $handler) { $defaultHandler = $this->defaultNotFoundHandler(); return $defaultHandler($path, $method); } return $this->dispatchUri($handler, $method); } // trigger notFound event return $this->fireCallback($handler, [$path, $method, $actionNotExist]); } /** * @param string $path * @param string $method * @param array $methods The allowed methods * @return mixed * @throws \Throwable */ protected function handleNotAllowed(string $path, string $method, array $methods) { // Run the 'NotAllowed' callback if the route was not found if (!$handler = $this->getOption(self::ON_METHOD_NOT_ALLOWED)) { $handler = $this->defaultNotAllowedHandler(); $this->setOption(self::ON_METHOD_NOT_ALLOWED, $handler); // is a route path. like '/site/notFound' } elseif (\is_string($handler) && '/' === $handler{0}) { $_GET['_src_path'] = $path; if ($path === $handler) { $defaultHandler = $this->defaultNotAllowedHandler(); return $defaultHandler($path, $method, $methods); } return $this->dispatchUri($handler, $method); } // trigger methodNotAllowed event return $this->fireCallback($handler, [$path, $method, $methods]); } /** * @param \Exception|\Throwable $e * @param string $path * @param array $info */ public function handleException($e, string $path, array $info) { // handle ... } /** * @return \Closure */ protected function defaultNotFoundHandler(): \Closure { return function ($path) { $protocol = $_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1'; header($protocol . ' 404 Not Found'); echo "<h1 style='width: 60%; margin: 5% auto;'>:( 404<br>Page Not Found <code style='font-weight: normal;'>$path</code></h1>"; }; } /** * @return \Closure */ protected function defaultNotAllowedHandler(): \Closure { return function ($path, $method, $methods) { $allow = implode(',', $methods); $protocol = $_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1'; header($protocol . ' 405 Method Not Allowed'); echo <<<HTML <div style="width: 500px; margin: 5% auto;"> <h1>:( Method not allowed <code style="font-weight: normal;font-size: 16px">for $method $path</code></h1> <p style="font-size: 20px">Method not allowed. Must be one of: <strong>$allow</strong></p> </div> HTML; }; } /** * Defines callback on happen event * @param $event * @param callable $handler */ public function on(string $event, $handler) { if (self::isSupportedEvent($event)) { $this->options[$event] = $handler; } } /** * @param callable $cb * string - func name, class name * array - [class, method] * object - Closure, Object * * @param array $args * @return mixed */ protected function fireCallback($cb, array $args = []) { if (!$cb) { return true; } if (\is_array($cb)) { list($obj, $mhd) = $cb; return \is_object($obj) ? $obj->$mhd(...$args) : $obj::$mhd(...$args); } if (\is_string($cb)) { if (\function_exists($cb)) { return $cb(...$args); } // a class name if (class_exists($cb)) { $cb = new $cb; } } // a \Closure or Object implement '__invoke' if (\is_object($cb) && method_exists($cb, '__invoke')) { return $cb(...$args); } throw new \InvalidArgumentException('the callback handler is not callable!'); } /** * @param string $name * @param $value */ public function setOption(string $name, $value) { $this->options[$name] = $value; } /** * @param string $name * @param null $default * @return mixed|null */ public function getOption(string $name, $default = null) { return $this->options[$name] ?? $default; } /** * @return array */ public static function getSupportedEvents(): array { return [ self::ON_FOUND, self::ON_NOT_FOUND, self::ON_METHOD_NOT_ALLOWED, self::ON_EXEC_START, self::ON_EXEC_END, self::ON_EXEC_ERROR ]; } /** * @param string $name * @return bool */ public static function isSupportedEvent(string $name): bool { return \in_array($name, static::getSupportedEvents(), true); } /** * @return RouterInterface|null */ public function getRouter() { return $this->router; } /** * @param RouterInterface $router * @return SimpleDispatcher */ public function setRouter(RouterInterface $router): SimpleDispatcher { $this->router = $router; return $this; } /** * @return array */ public function getOptions(): array { return $this->options; } /** * @param array $options */ public function setOptions(array $options) { $this->options = $options; } } <file_sep>/examples/cached/bench-routes-cache.php <?php /* * This is routes cache file of the package `inhere/sroute`. * It is auto generate by Inhere\Route\CachedRouter. * @date 2018-01-11 19:01:43 * @count 1000 * @notice Please don't edit it. */ return array ( // static routes 'staticRoutes' => array ( '/rdubekwyuzqs/eqjouuf' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/mrle/s/kg' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/lhmjg/nf/xprvld' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/aetvw/ahtyc/rrl' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/tztuuxwqxnwoh/' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/lkndknele' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/faexpgfstpjvcqfix/sr' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/efn/pwf/zwuebazm/' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/nw/qh/chwvmjakeurbba/r' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/y/vbrc' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/kwdqp/bseiqxp' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/xubm/hhaih' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/duvcuieui' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/xpmc/tx' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/ekwud' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/pnxui' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/fun/k/g/rzmnmydjuuu' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/fsz/nebpuiabfjtdtuvmi' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/razmibqdkrmbybtc/fq' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/fxrpufcaeonpfl/' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/ebdghsw' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/xqjdaumiec/mjuiotofpt' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/lcf/ytagxgcyyreky' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/rggydhhovuqsoxci' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/mqmcuiyd' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/ydnqomlerbp' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/d/e/lhjp/vxaxwjceksstq' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/ktabmrzn' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/ycjieq/m' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/rvrvpneycnlnkreou' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/kidy/z/jqu/twkpto' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/nvbpbsdvy/i/jgvylrn/c' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/wutfuwtjbon/hte' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/qs/exmspbgs' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/ubqaee' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/jafmfiut/frgfdyhzfse' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/dioxmmylq' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/reozydmhpw' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/twxghvgbghr' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/ojqz/dgtqmwpmpluay' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/ubdahegxroasbsqwb' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/upjoivkb/glwtfzudl' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/nhj/ozb/q' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/wsrx/j/xpvvpnzj' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/sbsmuof/' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/tcypakdyxqi/zidz/ur' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/eumrp' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/t/bt/ax' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/tclbmpdpd/rclomqis' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/ggck/k/pvntxms' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/m/tzprz/k' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/e/ccyoqblqu/bhdzvxh' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/klhpay/eu' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/jvdvzrtr' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/mzf/ej/cv/mxp/ogfpy/' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/xjpoehbtcg/ttb' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/gk/zdzhpgtbgot/kk/drswf' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/erojcz/am/emlqd' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/vgrlxa/lyk' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/vtani/a/' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/oouvee' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/qlavfd/l' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/cj/xx/zu/qbdlwjjf' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/omj/rnygzywakx/w' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/kyxf/wpx/pfxs' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/gabrfqmv/uyegryxx' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/slywkjuvevfczxvb' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/hyimjhxjdjk/lqrh/d' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/cteuitxjhq' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/jomtooqj' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/aeliuesrvuh' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/ialadijb/ys' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/m/qbxf' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/uwhmifhkhzzg/gp/peeyz' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/culxuxfd/jddn' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/eizwfhileoplw/etwxe' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/sicxjoiposr/' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/rpnczpiqrsxu/qixutst' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/dwvkojr' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/xrvo/nxe/zdxglpedzbn' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/b/gujpvtxtox/buz' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/ionbzecrnt' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/yjodf/pv/i/ehk/gzybpruzx' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/axcmofxzcx/fmysu/babh' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/hrmawci/ybarbq' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/plyl/s' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/mupt/u/dlyl/yukdg/qe' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/syeamc/oxwtjfzqqvix' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/kl/y/llzahczisfwenporv' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/cbbjfm/ogq' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/r/xsdm/crh/pi' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/tgotizamwixbsgvuoy' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/rvmdsiruyz/ien' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/pzkbzqw/' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/bywaox' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/weuiqlhvj/fpxqgi' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/mmyqveki/qan/wa/eanq' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/ukcdypzxin' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/lnlubpgcoo/m/gk/x' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/ns/sjctczvlyx/n/h/jg/khfq' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/scvukfvieht' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/caf/qsrqfptvbwv' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/vbiovav/' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/ntqljlkxlg/v/azrhnui/g' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/mrjvq/cjtpudmsxr/uoi' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/pibqqslnk/w' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/celbnlcadtlkuap/kz' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/r/cirhugki/pfx' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/yx/fhwcqqclhwmyfp' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/ykukjiegxtlrjdt' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/rqubrpk/t/jvylntcix' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/h/vendunifpbmh/xciwq' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/rhkebutiqgkkj' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/slcduxwcwkzrzm' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/ejfgj/ojob/hbc' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/xgabfo' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/jbfit/x/wkaajvjdb' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/kojzdpk/nyy' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/of/ueo' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/zstjhbzg/hiximizwwjp' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/awuppxzgmnx' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/otzvicbhzdielthp/dm' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/pvmaiqd/vnfxiu' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/skjgeij' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/gmx/gr' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/d/usmlyf' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/kiu/ezlg' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/gizmbr/zvvre/uiux' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/qxh/krsg/frr/a' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/jtlzjudz' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/ctpsvwamqhebb' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/ujpjtcndwqs' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/jlbcuenjiziuqfrjh/g/l' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/ijw/iharcdhlqje/wy' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/aqr/fotn/upnjkoxia/ivz' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/hgddkg' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/uovwxqnu' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/tsz/bk/cy/zifb/tc' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/umfla' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/wl/mwavo' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/rqkwmkv/x' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/ycdlxlmnmsoexhwoc/jrr' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/cssfa/kaf/tepzi' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/nzumytmz/s' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/gqmjrsv' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/wslq/cwzn/busc/q' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/e/ycugv' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/ikazqwter/k' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/mrhqwabt' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/ositiypihcedn/sd' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/uqpicteciyghfyu/yo' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/rwtfnol/ew/ajcxg/' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/mkmqtur' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/qvsr/fsg/vlbdr' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/peb/zuwzb' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/ectmxffsfgovoba' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/nying/ik/mioflhjsl' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/bkym/v' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/ar/aeowir/mkkrcwpsuxa/p' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/faazzrdlodbuwqxhs/' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/lfaxh/rboyzcnj/' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/z/vzvr' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/vdsz/v/pngrja' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/geapdf/xblfrutnryh' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/j/wm/euah' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/nkdrkevgelpihtfgn' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/ffwzdamdzdts' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/xmqwxc/yziktnaaosu/fz/' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/wpl/lfoh' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/zyid/ci/iing' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/rjbxj/glg' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/wfqrqckc' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/mtwoaagafoc' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/psssp' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/zhfdbrs/gzglikpsdfssb' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/hvxw/dbso' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/j/vr/ftbpwadwlsn/qjs' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/hzrzlyjoufvbbdkaxl' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/sksqtioasic' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/xvwgappzd/od/' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/y/urfwm/rtbl/pptsjv/oxa' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/rgyrc/obeysp/xkcsmjt/ae' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/jqeqomw/' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/tioppymywiizquzzndw' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/v/wlgqlw/' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/iozhyvojw/wggwienkkl' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/kfgvqpoo/ju/twyxdyfpaa/' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/cfxf/yiozqwdr/' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/ctvabxueaawi' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/dlyhmfu' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/kdxqt/ytzeqpzaj' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/jeloxxponuur/' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/bbybake/tgrwjaaz' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/gbzs/oucuydrj/p/h' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/hbwxtdkuhnfwtzmb/mq' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/djqjnwfz/olx/q' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/hefff/zdpdshv' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/xlamne' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/uimqtytggivlfnq/oqsms' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/wpgwduilidenm/vxp' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/dhgdm/dcwezlhwhy' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/qvpkevvndizbfg' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/lfgyawe/dpbwrwqz' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/eylodfbha/scctshl' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/ewzgctjelw/c' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/wmcnjtkwmecukaylz/xgh' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/fl/zy/yj' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/nbvv/cav/unewekpewlapp' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/s/v/oowcgzqqektkmeqaoe' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/hlymzlymchxs/r/lpkxg' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/crxihvavy/lzoe/sq/fnlfs/' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/zkuibgiiaxmgqop' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/nrnlwnalrgsr' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/z/xmmiktx/ruheya/yhn/zw' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/gdfoja/k' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/yvrgkszet' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/jmzx/flc' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/enxkib/vjwakar' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/zfauyui/uforvlma' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/kjr/kpvl' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/jxaahzwcs' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/fjusephjej/viuw/cdl' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/thwtsqevanfljegvhsfn/' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/vxvfigdaufgm' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/vumxwsmoyjzqtu/n' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/oy/wlf/m' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/kcny/gvdkysgn/mqrwm/r' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/j/ddwvkg/i' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/zrfprqfdiosmqtf' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/spa/iw/zne/xu' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/yolqujdri' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/ghdyzh' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/xixbbbrsmosrftyyaoq' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/wnxcy/mzihqmbi' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/hwybp' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/doyrxzryqztwu/djy' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/zwfcvyoo/ywpe/tsopw/dkw/' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/ndsavhr' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/dnrznu/oantlop/gs/iro' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/dnbbdybxhez' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/shedvidjiuapxy/sihexf' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/ttj/nzvz' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/efnrsdstawezovm/havf' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/nhbkdrxvt' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/lu/oomjopg' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/urrqem/efkxggyas/lkpv' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/cnilovlosnsg/pa' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/t/zhpq/lvx' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/wfi/lxu' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/caqzsd/ka/vnpn' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/m/vzpsmi' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/wteltlanl/tzm' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/mnxapyah/ietxt' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/tacq/zasjz/soha' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/xrdoz/pxwltotz' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/wr/qqcfuhsvsvfheergez' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/lgz/idxumb/t/bd/' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/sxgonvemruzv/hj/' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/fgztet' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/riuizno/wvnk' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/tivkefr/vkx/rawb/qzs' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/xxfn/dpzsz' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/twicmrhqr' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/zraqitqso/d/hykf' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/mep/dbfmdgudpsd' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/wprb/casfhuzox/kyg/mw' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/dhvzay/lifxzelxemw/us' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/oa/piyighaismmsuog' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/lnq/kfta' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/rj/pvto/zjvm' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/a/qdxzyghrqtkr' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/xgcm/h' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/i/npsgkwojhapr' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/mxlikpynv/xi' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/x/hjapi/ihh/okpqp' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/rm/tiveprzknqj/d' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/fymddp/ok' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/avxpen' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/vliil/p' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/be/nwq/odvzcwjfhu' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/kdzkepzj' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/qwfotcbj/peacerxm' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/noivkzmxrs' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/mkn/rhwsf/pjtnf' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/wvezlpvhxi' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/pnfqllz/ztfq' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/qwx/qacvi/z/osmc/yfh/vsw/y' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/kswjfq' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/xdu/unevfr' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/in/xfeexoqyjjuh/db' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/pbggtdzqjiykgxj' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/otnaipvgpzk' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/gxrf/unlhpyqtpjxw/klmq' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/rkozoejstev/veke' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/gm/qccjf/qu/qktpz' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/x/yzid/qwvjslrq/' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/qgzptzyjts/sijjk' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/pfrln/qtqid' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/pillptzf' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/mgxvzx' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/ihhyqhsp/vzzf' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/er/icbbqehv/' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/lhkxd' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/mmthkbcsgpxi/cexy/jpeu' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/wd/zneinubo' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/apvhy/eh/hnubtns/piyp' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/gkrz/lkwfl/gwah/wmg' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/zyccjmuod' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/oeehqaa/knx' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/lrmwpclc/cmbhoyiayqw' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/x/u/zceoeivop/hxmsj/m' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/maewuklfwr' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/otksljkwf' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/nlhefxriunu' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/ireqblhbqqabhibggcue/' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/wb/ljydlmm' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/viv/m/qdhfgczju' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/iyzahvlbfodv' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/pccha' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/varok/sz' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/weexh/wddwnp' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/r/tdpxtnbq/zju' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/djkov/fxqtjamhxqf' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/y/mwzkfubkuy/ezbad' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/kvfaxzhb' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/sc/mjjaj/akrb' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/rlxmo/fpfxe' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/dcav/u/vuuoxbgvf/qcrsk' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/ekdnnowvxnop' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/oqfgnistfuky' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/vjwgr' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/jdiftgrsnin' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/cfvf/gjqlriy' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/frqamk/yxuphf' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/eyntqywgwrtq' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/iogrxlrlqktmf/u/njzn/' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/zg/odm/zbxvw/qtyo' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/sryllffkxkjx/arlms' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/owpzn/rtmsmlhp' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/ruzbxfcz' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/lzmevhmtpuf/y' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/q/rzkgffyqp' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/anvcm/x/knlx/nkeffzrto' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/fpfjko/apdv/iiyigf/i' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/aoujeeby' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/d/yqwl' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/heanjrbhapvfcvsgei' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/zjrlrpw/pcflvl' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/upjcyeayaizcpm/odcmy' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/nufmlptcc/hbkz/mrhnub' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/wltandkweowgzdz' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/d/qtebgqaotgi/hnm' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/bjikkdyzwtlr/gi' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/ycqrewshqfoqowch/s/xuo' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/wt/d/rqstmrarr/ul' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/bwerctm/' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/saverktep/t' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/mhard/tq/vt' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/jjor/joovp/gvns/' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/yj/iazj/dpwcjmzdazpxjk' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/ozluruu/wtouowvpga' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/zsjdiko/' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/nxfpkvc' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/pp/y/it/rmr/tiech' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/vvpelshicesl/' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/hapr/qtnctrtsbs' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/zmrkbzbp/vf/upxnvgc/p' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/r/hq/edkgphokvixpc/ui' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/lrwjpurflgqhsiecgmz/i' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/mr/bbkf/ipuhgtk' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/exmm/qidmcvtzti/' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/bzd/exmdtzxa' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/zslunujquyulo' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/vuszbeic' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/gaauxckf' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/appsxwzpctnu' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/njiylx/inkkh' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/lholu/viboevog/c' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/iiezdqrqydzjt' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/bqbr/zuimdvpebnbl' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/dqaanvdwpblaf/' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/aqnvfn' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/xrhtqwzmweqmlfrwx/' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/h/fqpysuhptxqotoeq' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/sg/kgff/' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/jwvb/wc' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/mencm/abkk/s/e/x' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/lqdr/ikozo/ziabu/db' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/fmrbd/fjrs/nye/lafkjybz' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/eukrkjlkazxccy' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/qyvyg/rh/knkviadbfqzp' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/w/f/ryoac' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/ovvuxx' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/jbdtr/hkafpjlimyuqkbb' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/oot/v/jgxbiuvoeostrym' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/ruusazzcn/chs' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/whbeo/uy/i/ffytn/nupsov' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/y/phszcqmzmmnnjo' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/gtgdcueji' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/yvppbaewyvxsi/q' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/lbc/vae' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/yjvjzgqeu' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/ipazeqf/su' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/elczbleajatljok/' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/ywsqytcic/hslsaamh' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/yodwzdbtulky' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/awk/wt/t/famci' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/etjebpul/rbeffuwc/n/' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/ihyhjwtzcdib' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/qd/m/enavr' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/dggndyoyemdllpk/zdk/sy' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/gyj/oqfkwewda' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/rwa/ed/pdnhohff/g' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/knsutdxy' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/ugjwhucvcs/t' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/nwjdjygwby' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/zowoo' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/bsqzhhpoh/ssjm/slbdz' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/mnbdoxaizejf' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/qdsragtu/or/nrmon' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/v/o/osbtynstduv' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/pllccb/ta/' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/jpwkxxsfsvg/cfjd' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/outjar' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/brsszopfyjhkgr' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/pmkisr' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/z/eor/ukmt' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/gr/iaaysjkfplx' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/iawyhxkdytc' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/dhllkqa' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/atxvy' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/pv/gwnqdijknbyguxg/' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/dgm/szr/o/xzf' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/vwznvw/qubdjw/pnf' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/ynfkflgbm/itsrgr' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/hfxhk' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/cnrxf' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/mveqsdielwhomsli' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/mdcekhz/exmukluq/ml' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/b/pgehe' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/i/d/akvje/o' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/kyrq/n/' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/dzrxdqvzb/av/ecznpvzgt' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/jixvnmdya' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/ulyc/qsclpw' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/caifvhniplxzqdhhczsm' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/dhoswe' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/av/qacavjryylhppjm' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/ofttanul' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/idvg/ruujdtc' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/uqb/gdz/wmygesth' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/kuwb/tn' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/auaastrvoixyvvsl/' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/bsqghcpqdtn' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/s/dctdult/pj' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/eexhc/isbwvsf' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/ptmhlfdgai/fvqmcm/z' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/vmiv/pxhbxvb/z/ss' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/sqaiudweotvtrtnrirrn' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/kjqy/fqhbnjfctiu' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/pwhw/ulyxquc/dq' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/kitoabzyek' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/w/huft/yicqvl/i' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/daetkodwdo/k' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/vbmsuvlvdflmsrear' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/qwhmnhosh/pvkfr/nup' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/vlgbicdjsyqjrw/' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/wobhqhfojpdwjskndyg' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/xydcp' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/bzli/lpe/ysj/utus' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/tsr/rrsgjrzkqfsjb' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/fgtxtnmk/wsuoo' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/rpaujraszzj/ydm/mawe' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/pypptydvd/l' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/ldldtqm/k' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/xdtiiqtostbexl' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/yyfl/rr/wxd' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/puqma/xf/pyp/' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/vpznvnap/eqgcwf/bufvh' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/wjhxzarfstgq/pqpa' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/kt/xwmpkedgb' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/biwrp/or/hlvfpm/hliu' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/ynkzjlctk' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/fzzwtjto/nzgae/m' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/feikgdlclnzdv' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/akd/kjupw' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/pccdqxhgba/jaytgx' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/ofwtpnh/ydiq/ksfynzf' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/s/jgjswqpcq/vwzjzvjs/' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/uo/mvtyz' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/gddwjbz' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/xbmhmtlhw' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/asvokyjz/lhlzfrhfecmi' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/jjhqrq/phercerg/' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/aifmtndfebkjg' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/nywctcs' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/dbqh/znujcqmmufxsikoy' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/fpqw/khhubhcmdvzxeu/e' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/mvikf' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/lgua/bubzw' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/bmhucuugm' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/knpjd/fdlvkkoysw/lri' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/yr/gqr/by/ojtorq' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/c/kxtduhdpw/sslotka' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/sie/vtvzvk/odsugrgfwxx' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/lnzefzlqzt/fy' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/dcgnzsltmkbdomxwtk' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/riikgmszqvtunhx' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/j/pmz/llseps/rvt/pmxwqlk' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/vdpm/pdydq/ljln' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/pexqniybocnvt/dwj/' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/rbeifupa/nqboe/lf' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/e/xbtm' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/vrfxiucww' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/bbrrb/alq/ummia/ozwqp' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/oam/fgizqrzpvirxq' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/pzyydvvtzhufbfymkgbi' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/iivwf' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/khrgl' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/gjljkvomgghglt' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/yrabgyprbtan' => array ( 'POST' => array ( 'handler' => 'handler_func', ), ), '/wowhebplkqvoirudaxx' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/jjyqvu/pmflf' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/qywmv/osvjha/xay/mf' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/kxlpjeg' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/w/vltqedutmxg/s/afsom' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/irgbmtcaspeurhp/u' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/im/rbapjlzmj' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/uspepuss/oavmzdcdm/' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/nkudnemcahrjs/ebgxl' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/yb/mfrgybr' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/g/oqgkvhl/lp' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/or/skjxkmdjscihgh' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/lwikwh/e/msvupjvgi' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/xmh/qp/vj/x/hslpfn' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/zc/vhwnvjztg/doxylxdu' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/ml/pqrc/yaj' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/huqjtewbnbgwlirbgu' => array ( 'DELETE' => array ( 'handler' => 'handler_func', ), ), '/nxtpv' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/jgnxnfiohrwa' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/rquutjzpmgggil' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/bepbmzzo/z/yfp/ulufxlsy' => array ( 'PATCH' => array ( 'handler' => 'handler_func', ), ), '/xb/xaiw' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), '/cr/dro' => array ( 'PUT' => array ( 'handler' => 'handler_func', ), ), '/u/zremwwnauhpa' => array ( 'GET' => array ( 'handler' => 'handler_func', ), ), ), // regular routes 'regularRoutes' => array ( 'nxspfb' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/nxspfb/{name}', 'regex' => '#^/nxspfb/(?P<name>[^/]+)$#', 'start' => '/nxspfb/', 'methods' => 'GET,', ), ), 'hzs' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/hzs/ufkcgggelsxhne/{name}', 'regex' => '#^/hzs/ufkcgggelsxhne/(?P<name>[^/]+)$#', 'start' => '/hzs/ufkcgggelsxhne/', 'methods' => 'GET,', ), ), 'uwxiov' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/uwxiov/ieizwfn/s/a/{name}', 'regex' => '#^/uwxiov/ieizwfn/s/a/(?P<name>[^/]+)$#', 'start' => '/uwxiov/ieizwfn/', 'methods' => 'GET,', ), ), 'nbuer' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/nbuer/{name}', 'regex' => '#^/nbuer/(?P<name>[^/]+)$#', 'start' => '/nbuer/', 'methods' => 'DELETE,', ), ), 'irlfukmrhu' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/irlfukmrhu/{name}', 'regex' => '#^/irlfukmrhu/(?P<name>[^/]+)$#', 'start' => '/irlfukmrhu/', 'methods' => 'PATCH,', ), ), 'hlnldsooeegvsoy' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/hlnldsooeegvsoy/pjxfy/{name}', 'regex' => '#^/hlnldsooeegvsoy/pjxfy/(?P<name>[^/]+)$#', 'start' => '/hlnldsooeegvsoy/pjxfy/', 'methods' => 'GET,', ), ), 'a' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/a/phpk/{name}', 'regex' => '#^/a/phpk/(?P<name>[^/]+)$#', 'start' => '/a/phpk/', 'methods' => 'DELETE,', ), ), 'fgx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/fgx/hu/{name}', 'regex' => '#^/fgx/hu/(?P<name>[^/]+)$#', 'start' => '/fgx/hu/', 'methods' => 'PATCH,', ), ), 'ssuhs' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ssuhs/ltoz/{name}', 'regex' => '#^/ssuhs/ltoz/(?P<name>[^/]+)$#', 'start' => '/ssuhs/ltoz/', 'methods' => 'GET,', ), ), 'ffdvarr' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ffdvarr/m/sxktpjpxek/{name}', 'regex' => '#^/ffdvarr/m/sxktpjpxek/(?P<name>[^/]+)$#', 'start' => '/ffdvarr/m/', 'methods' => 'PUT,', ), ), 'jtbhcuxwhwjmjmzs' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/jtbhcuxwhwjmjmzs/{name}', 'regex' => '#^/jtbhcuxwhwjmjmzs/(?P<name>[^/]+)$#', 'start' => '/jtbhcuxwhwjmjmzs/', 'methods' => 'GET,', ), ), 'ppcjwddjnzrf' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ppcjwddjnzrf/{name}', 'regex' => '#^/ppcjwddjnzrf/(?P<name>[^/]+)$#', 'start' => '/ppcjwddjnzrf/', 'methods' => 'GET,', ), ), 'pmfonee' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/pmfonee/{name}', 'regex' => '#^/pmfonee/(?P<name>[^/]+)$#', 'start' => '/pmfonee/', 'methods' => 'PUT,', ), ), 'x' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/x/g/dygwx/ydkoujsrfg/{name}', 'regex' => '#^/x/g/dygwx/ydkoujsrfg/(?P<name>[^/]+)$#', 'start' => '/x/g/', 'methods' => 'PATCH,', ), 1 => array ( 'handler' => 'handler_func', 'original' => '/x/iurrsb/ruu/{name}', 'regex' => '#^/x/iurrsb/ruu/(?P<name>[^/]+)$#', 'start' => '/x/iurrsb/', 'methods' => 'GET,', ), ), 'tjgqos' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/tjgqos/{name}', 'regex' => '#^/tjgqos/(?P<name>[^/]+)$#', 'start' => '/tjgqos/', 'methods' => 'PATCH,', ), ), 'qiqlv' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/qiqlv/p/k/{name}', 'regex' => '#^/qiqlv/p/k/(?P<name>[^/]+)$#', 'start' => '/qiqlv/p/', 'methods' => 'POST,', ), ), 'gq' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/gq/ltw/{name}', 'regex' => '#^/gq/ltw/(?P<name>[^/]+)$#', 'start' => '/gq/ltw/', 'methods' => 'GET,', ), ), 'zlex' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/zlex/awl/wpmswqi/{name}', 'regex' => '#^/zlex/awl/wpmswqi/(?P<name>[^/]+)$#', 'start' => '/zlex/awl/', 'methods' => 'GET,', ), ), 'kjzsima' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/kjzsima/{name}', 'regex' => '#^/kjzsima/(?P<name>[^/]+)$#', 'start' => '/kjzsima/', 'methods' => 'GET,', ), ), 'ppklnbywep' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ppklnbywep/{name}', 'regex' => '#^/ppklnbywep/(?P<name>[^/]+)$#', 'start' => '/ppklnbywep/', 'methods' => 'GET,', ), ), 'pq' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/pq/ntsnmsrzs/{name}', 'regex' => '#^/pq/ntsnmsrzs/(?P<name>[^/]+)$#', 'start' => '/pq/ntsnmsrzs/', 'methods' => 'GET,', ), ), 'l' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/l/vrucxrulo/{name}', 'regex' => '#^/l/vrucxrulo/(?P<name>[^/]+)$#', 'start' => '/l/vrucxrulo/', 'methods' => 'GET,', ), 1 => array ( 'handler' => 'handler_func', 'original' => '/l/oy/ijxxagfulyf/{name}', 'regex' => '#^/l/oy/ijxxagfulyf/(?P<name>[^/]+)$#', 'start' => '/l/oy/', 'methods' => 'PUT,', ), ), 'mr' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/mr/oyvpjkpilsqajo/{name}', 'regex' => '#^/mr/oyvpjkpilsqajo/(?P<name>[^/]+)$#', 'start' => '/mr/oyvpjkpilsqajo/', 'methods' => 'PUT,', ), ), 'yuc' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/yuc/fbgba/{name}', 'regex' => '#^/yuc/fbgba/(?P<name>[^/]+)$#', 'start' => '/yuc/fbgba/', 'methods' => 'GET,', ), ), 'jes' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/jes/ossanb/zqw/{name}', 'regex' => '#^/jes/ossanb/zqw/(?P<name>[^/]+)$#', 'start' => '/jes/ossanb/', 'methods' => 'POST,', ), ), 'mqeuykp' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/mqeuykp/{name}', 'regex' => '#^/mqeuykp/(?P<name>[^/]+)$#', 'start' => '/mqeuykp/', 'methods' => 'PATCH,', ), ), 'sh' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/sh/p/oojgstdecpsmf/{name}', 'regex' => '#^/sh/p/oojgstdecpsmf/(?P<name>[^/]+)$#', 'start' => '/sh/p/', 'methods' => 'POST,', ), ), 'knl' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/knl/hhkfrzga/{name}', 'regex' => '#^/knl/hhkfrzga/(?P<name>[^/]+)$#', 'start' => '/knl/hhkfrzga/', 'methods' => 'GET,', ), ), 'wfkzlt' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/wfkzlt/{name}', 'regex' => '#^/wfkzlt/(?P<name>[^/]+)$#', 'start' => '/wfkzlt/', 'methods' => 'PUT,', ), ), 'b' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/b/chc/pealecps/y/{name}', 'regex' => '#^/b/chc/pealecps/y/(?P<name>[^/]+)$#', 'start' => '/b/chc/', 'methods' => 'PATCH,', ), ), 'pjdju' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/pjdju/dbbkxa/rqbfg/{name}', 'regex' => '#^/pjdju/dbbkxa/rqbfg/(?P<name>[^/]+)$#', 'start' => '/pjdju/dbbkxa/', 'methods' => 'GET,', ), ), 'kitiuu' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/kitiuu/ct/{name}', 'regex' => '#^/kitiuu/ct/(?P<name>[^/]+)$#', 'start' => '/kitiuu/ct/', 'methods' => 'POST,', ), ), 'kiojwp' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/kiojwp/{name}', 'regex' => '#^/kiojwp/(?P<name>[^/]+)$#', 'start' => '/kiojwp/', 'methods' => 'GET,', ), ), 'wjtmautihzubk' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/wjtmautihzubk/{name}', 'regex' => '#^/wjtmautihzubk/(?P<name>[^/]+)$#', 'start' => '/wjtmautihzubk/', 'methods' => 'GET,', ), ), 'whuqjzhknyeookmfxzlq' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/whuqjzhknyeookmfxzlq/{name}', 'regex' => '#^/whuqjzhknyeookmfxzlq/(?P<name>[^/]+)$#', 'start' => '/whuqjzhknyeookmfxzlq/', 'methods' => 'PATCH,', ), ), 'lzm' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/lzm/rlbo/{name}', 'regex' => '#^/lzm/rlbo/(?P<name>[^/]+)$#', 'start' => '/lzm/rlbo/', 'methods' => 'POST,', ), ), 'horgyzvnn' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/horgyzvnn/{name}', 'regex' => '#^/horgyzvnn/(?P<name>[^/]+)$#', 'start' => '/horgyzvnn/', 'methods' => 'PATCH,', ), ), 'wvrt' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/wvrt/u/{name}', 'regex' => '#^/wvrt/u/(?P<name>[^/]+)$#', 'start' => '/wvrt/u/', 'methods' => 'GET,', ), ), 'r' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/r/huuwrvierxsw/{name}', 'regex' => '#^/r/huuwrvierxsw/(?P<name>[^/]+)$#', 'start' => '/r/huuwrvierxsw/', 'methods' => 'POST,', ), 1 => array ( 'handler' => 'handler_func', 'original' => '/r/bbnkr/nrjwbg/{name}', 'regex' => '#^/r/bbnkr/nrjwbg/(?P<name>[^/]+)$#', 'start' => '/r/bbnkr/', 'methods' => 'DELETE,', ), ), 'h' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/h/r/hzkxcndxtkewl/{name}', 'regex' => '#^/h/r/hzkxcndxtkewl/(?P<name>[^/]+)$#', 'start' => '/h/r/', 'methods' => 'DELETE,', ), ), 'cjcizl' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/cjcizl/{name}', 'regex' => '#^/cjcizl/(?P<name>[^/]+)$#', 'start' => '/cjcizl/', 'methods' => 'PUT,', ), ), 'nmcvbddzbqk' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/nmcvbddzbqk/{name}', 'regex' => '#^/nmcvbddzbqk/(?P<name>[^/]+)$#', 'start' => '/nmcvbddzbqk/', 'methods' => 'PATCH,', ), ), 'xvfvxcska' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/xvfvxcska/x/{name}', 'regex' => '#^/xvfvxcska/x/(?P<name>[^/]+)$#', 'start' => '/xvfvxcska/x/', 'methods' => 'GET,', ), ), 'dlsiqkkcenx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/dlsiqkkcenx/pxvop/{name}', 'regex' => '#^/dlsiqkkcenx/pxvop/(?P<name>[^/]+)$#', 'start' => '/dlsiqkkcenx/pxvop/', 'methods' => 'DELETE,', ), ), 'damgadd' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/damgadd/fbyrnc/{name}', 'regex' => '#^/damgadd/fbyrnc/(?P<name>[^/]+)$#', 'start' => '/damgadd/fbyrnc/', 'methods' => 'DELETE,', ), ), 'xkmexyznwr' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/xkmexyznwr/{name}', 'regex' => '#^/xkmexyznwr/(?P<name>[^/]+)$#', 'start' => '/xkmexyznwr/', 'methods' => 'PUT,', ), ), 'vs' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/vs/lwanoy/{name}', 'regex' => '#^/vs/lwanoy/(?P<name>[^/]+)$#', 'start' => '/vs/lwanoy/', 'methods' => 'PUT,', ), ), 'tvwpzhtfgig' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/tvwpzhtfgig/{name}', 'regex' => '#^/tvwpzhtfgig/(?P<name>[^/]+)$#', 'start' => '/tvwpzhtfgig/', 'methods' => 'GET,', ), ), 'cu' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/cu/bxybq/ygyfprja/o/{name}', 'regex' => '#^/cu/bxybq/ygyfprja/o/(?P<name>[^/]+)$#', 'start' => '/cu/bxybq/', 'methods' => 'GET,', ), ), 'eyhuisksdsmaz' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/eyhuisksdsmaz/{name}', 'regex' => '#^/eyhuisksdsmaz/(?P<name>[^/]+)$#', 'start' => '/eyhuisksdsmaz/', 'methods' => 'PATCH,', ), ), 'eqgajekzjkh' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/eqgajekzjkh/acdf/vyo/{name}', 'regex' => '#^/eqgajekzjkh/acdf/vyo/(?P<name>[^/]+)$#', 'start' => '/eqgajekzjkh/acdf/', 'methods' => 'POST,', ), ), 'dghl' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/dghl/v/t/de/udy/{name}', 'regex' => '#^/dghl/v/t/de/udy/(?P<name>[^/]+)$#', 'start' => '/dghl/v/', 'methods' => 'DELETE,', ), ), 'htyw' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/htyw/osz/{name}', 'regex' => '#^/htyw/osz/(?P<name>[^/]+)$#', 'start' => '/htyw/osz/', 'methods' => 'GET,', ), ), 'bvqibciphhd' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/bvqibciphhd/p/{name}', 'regex' => '#^/bvqibciphhd/p/(?P<name>[^/]+)$#', 'start' => '/bvqibciphhd/p/', 'methods' => 'PUT,', ), ), 'ci' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ci/onszzyuc/{name}', 'regex' => '#^/ci/onszzyuc/(?P<name>[^/]+)$#', 'start' => '/ci/onszzyuc/', 'methods' => 'PUT,', ), ), 'xx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/xx/rpalp/{name}', 'regex' => '#^/xx/rpalp/(?P<name>[^/]+)$#', 'start' => '/xx/rpalp/', 'methods' => 'GET,', ), ), 'adwcixsbowkwis' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/adwcixsbowkwis/{name}', 'regex' => '#^/adwcixsbowkwis/(?P<name>[^/]+)$#', 'start' => '/adwcixsbowkwis/', 'methods' => 'GET,', ), ), 'rbzg' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/rbzg/nnxxxbpzc/{name}', 'regex' => '#^/rbzg/nnxxxbpzc/(?P<name>[^/]+)$#', 'start' => '/rbzg/nnxxxbpzc/', 'methods' => 'POST,', ), ), 'wluyg' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/wluyg/zdk/w/{name}', 'regex' => '#^/wluyg/zdk/w/(?P<name>[^/]+)$#', 'start' => '/wluyg/zdk/', 'methods' => 'PATCH,', ), ), 'oxxysladqjpvgvhsfl' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/oxxysladqjpvgvhsfl/rn/{name}', 'regex' => '#^/oxxysladqjpvgvhsfl/rn/(?P<name>[^/]+)$#', 'start' => '/oxxysladqjpvgvhsfl/rn/', 'methods' => 'PATCH,', ), ), 'rokuf' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/rokuf/l/{name}', 'regex' => '#^/rokuf/l/(?P<name>[^/]+)$#', 'start' => '/rokuf/l/', 'methods' => 'GET,', ), ), 'zimdww' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/zimdww/{name}', 'regex' => '#^/zimdww/(?P<name>[^/]+)$#', 'start' => '/zimdww/', 'methods' => 'GET,', ), ), 'iagnpuib' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/iagnpuib/p/mfjoho/bskzl/{name}', 'regex' => '#^/iagnpuib/p/mfjoho/bskzl/(?P<name>[^/]+)$#', 'start' => '/iagnpuib/p/', 'methods' => 'GET,', ), ), 'auymaqnbiiuuap' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/auymaqnbiiuuap/{name}', 'regex' => '#^/auymaqnbiiuuap/(?P<name>[^/]+)$#', 'start' => '/auymaqnbiiuuap/', 'methods' => 'GET,', ), ), 'yp' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/yp/qmubodqxwph/{name}', 'regex' => '#^/yp/qmubodqxwph/(?P<name>[^/]+)$#', 'start' => '/yp/qmubodqxwph/', 'methods' => 'POST,', ), ), 'tearef' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/tearef/{name}', 'regex' => '#^/tearef/(?P<name>[^/]+)$#', 'start' => '/tearef/', 'methods' => 'PUT,', ), ), 'psxtzqbtyfer' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/psxtzqbtyfer/p/{name}', 'regex' => '#^/psxtzqbtyfer/p/(?P<name>[^/]+)$#', 'start' => '/psxtzqbtyfer/p/', 'methods' => 'PUT,', ), ), 'deuu' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/deuu/iulyk/{name}', 'regex' => '#^/deuu/iulyk/(?P<name>[^/]+)$#', 'start' => '/deuu/iulyk/', 'methods' => 'POST,', ), ), 'gpctejhoryhiuttwcqxy' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/gpctejhoryhiuttwcqxy/{name}', 'regex' => '#^/gpctejhoryhiuttwcqxy/(?P<name>[^/]+)$#', 'start' => '/gpctejhoryhiuttwcqxy/', 'methods' => 'PUT,', ), ), 'veavxraamq' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/veavxraamq/dxg/{name}', 'regex' => '#^/veavxraamq/dxg/(?P<name>[^/]+)$#', 'start' => '/veavxraamq/dxg/', 'methods' => 'PATCH,', ), ), 'vembyuhwfaw' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/vembyuhwfaw/cp/{name}', 'regex' => '#^/vembyuhwfaw/cp/(?P<name>[^/]+)$#', 'start' => '/vembyuhwfaw/cp/', 'methods' => 'PATCH,', ), ), 'xffdkhkzgeuyj' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/xffdkhkzgeuyj/{name}', 'regex' => '#^/xffdkhkzgeuyj/(?P<name>[^/]+)$#', 'start' => '/xffdkhkzgeuyj/', 'methods' => 'GET,', ), ), 'mdlpub' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/mdlpub/{name}', 'regex' => '#^/mdlpub/(?P<name>[^/]+)$#', 'start' => '/mdlpub/', 'methods' => 'GET,', ), ), 'yfeqrfwrjwiwk' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/yfeqrfwrjwiwk/{name}', 'regex' => '#^/yfeqrfwrjwiwk/(?P<name>[^/]+)$#', 'start' => '/yfeqrfwrjwiwk/', 'methods' => 'POST,', ), ), 'ffvkisqxtsuvhgg' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ffvkisqxtsuvhgg/{name}', 'regex' => '#^/ffvkisqxtsuvhgg/(?P<name>[^/]+)$#', 'start' => '/ffvkisqxtsuvhgg/', 'methods' => 'POST,', ), ), 'vyljcnizfsbyb' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/vyljcnizfsbyb/{name}', 'regex' => '#^/vyljcnizfsbyb/(?P<name>[^/]+)$#', 'start' => '/vyljcnizfsbyb/', 'methods' => 'DELETE,', ), ), 't' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/t/zewutnnybk/vj/gcj/{name}', 'regex' => '#^/t/zewutnnybk/vj/gcj/(?P<name>[^/]+)$#', 'start' => '/t/zewutnnybk/', 'methods' => 'PUT,', ), 1 => array ( 'handler' => 'handler_func', 'original' => '/t/o/i/sr/zp/cwb/{name}', 'regex' => '#^/t/o/i/sr/zp/cwb/(?P<name>[^/]+)$#', 'start' => '/t/o/', 'methods' => 'GET,', ), ), 'ksalamk' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ksalamk/t/{name}', 'regex' => '#^/ksalamk/t/(?P<name>[^/]+)$#', 'start' => '/ksalamk/t/', 'methods' => 'GET,', ), ), 'trji' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/trji/zn/{name}', 'regex' => '#^/trji/zn/(?P<name>[^/]+)$#', 'start' => '/trji/zn/', 'methods' => 'GET,', ), ), 'bwrsu' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/bwrsu/btohafg/{name}', 'regex' => '#^/bwrsu/btohafg/(?P<name>[^/]+)$#', 'start' => '/bwrsu/btohafg/', 'methods' => 'PATCH,', ), ), 'zwi' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/zwi/f/gmmrpb/{name}', 'regex' => '#^/zwi/f/gmmrpb/(?P<name>[^/]+)$#', 'start' => '/zwi/f/', 'methods' => 'PUT,', ), ), 'dkxsddzz' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/dkxsddzz/vgxiqxxwy/{name}', 'regex' => '#^/dkxsddzz/vgxiqxxwy/(?P<name>[^/]+)$#', 'start' => '/dkxsddzz/vgxiqxxwy/', 'methods' => 'PATCH,', ), ), 'xvdqfyix' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/xvdqfyix/qlwcmcqkp/bkk/{name}', 'regex' => '#^/xvdqfyix/qlwcmcqkp/bkk/(?P<name>[^/]+)$#', 'start' => '/xvdqfyix/qlwcmcqkp/', 'methods' => 'GET,', ), ), 'qffrz' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/qffrz/ufepmp/{name}', 'regex' => '#^/qffrz/ufepmp/(?P<name>[^/]+)$#', 'start' => '/qffrz/ufepmp/', 'methods' => 'PATCH,', ), ), 'rwtwqygal' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/rwtwqygal/j/{name}', 'regex' => '#^/rwtwqygal/j/(?P<name>[^/]+)$#', 'start' => '/rwtwqygal/j/', 'methods' => 'PUT,', ), ), 'z' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/z/aqgtt/{name}', 'regex' => '#^/z/aqgtt/(?P<name>[^/]+)$#', 'start' => '/z/aqgtt/', 'methods' => 'DELETE,', ), 1 => array ( 'handler' => 'handler_func', 'original' => '/z/iodj/{name}', 'regex' => '#^/z/iodj/(?P<name>[^/]+)$#', 'start' => '/z/iodj/', 'methods' => 'PATCH,', ), ), 'okh' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/okh/tnmbcjnqwdduv/{name}', 'regex' => '#^/okh/tnmbcjnqwdduv/(?P<name>[^/]+)$#', 'start' => '/okh/tnmbcjnqwdduv/', 'methods' => 'DELETE,', ), ), 'dqtonolzzgm' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/dqtonolzzgm/{name}', 'regex' => '#^/dqtonolzzgm/(?P<name>[^/]+)$#', 'start' => '/dqtonolzzgm/', 'methods' => 'POST,', ), ), 'cbyz' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/cbyz/zc/vwhq/{name}', 'regex' => '#^/cbyz/zc/vwhq/(?P<name>[^/]+)$#', 'start' => '/cbyz/zc/', 'methods' => 'DELETE,', ), ), 'vpkvxvviclpulob' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/vpkvxvviclpulob/lnmi/{name}', 'regex' => '#^/vpkvxvviclpulob/lnmi/(?P<name>[^/]+)$#', 'start' => '/vpkvxvviclpulob/lnmi/', 'methods' => 'PATCH,', ), ), 'wk' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/wk/hzuqsa/{name}', 'regex' => '#^/wk/hzuqsa/(?P<name>[^/]+)$#', 'start' => '/wk/hzuqsa/', 'methods' => 'GET,', ), ), 'rn' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/rn/jip/gwspj/{name}', 'regex' => '#^/rn/jip/gwspj/(?P<name>[^/]+)$#', 'start' => '/rn/jip/', 'methods' => 'POST,', ), ), 'srrnyjx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/srrnyjx/{name}', 'regex' => '#^/srrnyjx/(?P<name>[^/]+)$#', 'start' => '/srrnyjx/', 'methods' => 'PUT,', ), ), 'qy' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/qy/lceds/{name}', 'regex' => '#^/qy/lceds/(?P<name>[^/]+)$#', 'start' => '/qy/lceds/', 'methods' => 'GET,', ), ), 'demnxuujuokkiteow' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/demnxuujuokkiteow/{name}', 'regex' => '#^/demnxuujuokkiteow/(?P<name>[^/]+)$#', 'start' => '/demnxuujuokkiteow/', 'methods' => 'GET,', ), ), 'tmwu' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/tmwu/ehhhmuc/{name}', 'regex' => '#^/tmwu/ehhhmuc/(?P<name>[^/]+)$#', 'start' => '/tmwu/ehhhmuc/', 'methods' => 'GET,', ), ), 'ycalj' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ycalj/{name}', 'regex' => '#^/ycalj/(?P<name>[^/]+)$#', 'start' => '/ycalj/', 'methods' => 'GET,', ), ), 'urbdecv' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/urbdecv/{name}', 'regex' => '#^/urbdecv/(?P<name>[^/]+)$#', 'start' => '/urbdecv/', 'methods' => 'POST,', ), ), 'zcvimpzhccdfccv' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/zcvimpzhccdfccv/{name}', 'regex' => '#^/zcvimpzhccdfccv/(?P<name>[^/]+)$#', 'start' => '/zcvimpzhccdfccv/', 'methods' => 'GET,', ), ), 'ujbkr' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ujbkr/{name}', 'regex' => '#^/ujbkr/(?P<name>[^/]+)$#', 'start' => '/ujbkr/', 'methods' => 'PATCH,', ), ), 'dqykcatibofz' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/dqykcatibofz/kohkna/{name}', 'regex' => '#^/dqykcatibofz/kohkna/(?P<name>[^/]+)$#', 'start' => '/dqykcatibofz/kohkna/', 'methods' => 'PATCH,', ), ), 'pybzeiub' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/pybzeiub/{name}', 'regex' => '#^/pybzeiub/(?P<name>[^/]+)$#', 'start' => '/pybzeiub/', 'methods' => 'GET,', ), ), 'kdjprn' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/kdjprn/rby/{name}', 'regex' => '#^/kdjprn/rby/(?P<name>[^/]+)$#', 'start' => '/kdjprn/rby/', 'methods' => 'PATCH,', ), ), 'wfappaktysas' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/wfappaktysas/evrtzl/{name}', 'regex' => '#^/wfappaktysas/evrtzl/(?P<name>[^/]+)$#', 'start' => '/wfappaktysas/evrtzl/', 'methods' => 'GET,', ), ), 'jjzlfqo' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/jjzlfqo/dsq/my/{name}', 'regex' => '#^/jjzlfqo/dsq/my/(?P<name>[^/]+)$#', 'start' => '/jjzlfqo/dsq/', 'methods' => 'POST,', ), ), 'kqxxigvtyyr' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/kqxxigvtyyr/{name}', 'regex' => '#^/kqxxigvtyyr/(?P<name>[^/]+)$#', 'start' => '/kqxxigvtyyr/', 'methods' => 'GET,', ), ), 'rcx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/rcx/rnhkufvpx/d/{name}', 'regex' => '#^/rcx/rnhkufvpx/d/(?P<name>[^/]+)$#', 'start' => '/rcx/rnhkufvpx/', 'methods' => 'POST,', ), ), 'era' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/era/xwek/fdui/gykg/{name}', 'regex' => '#^/era/xwek/fdui/gykg/(?P<name>[^/]+)$#', 'start' => '/era/xwek/', 'methods' => 'POST,', ), ), 'jsnk' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/jsnk/bc/bnrkn/jd/vf/x/gpw/{name}', 'regex' => '#^/jsnk/bc/bnrkn/jd/vf/x/gpw/(?P<name>[^/]+)$#', 'start' => '/jsnk/bc/', 'methods' => 'GET,', ), ), 'w' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/w/kuybqtxswspcww/{name}', 'regex' => '#^/w/kuybqtxswspcww/(?P<name>[^/]+)$#', 'start' => '/w/kuybqtxswspcww/', 'methods' => 'PATCH,', ), 1 => array ( 'handler' => 'handler_func', 'original' => '/w/dxyxfagcaux/{name}', 'regex' => '#^/w/dxyxfagcaux/(?P<name>[^/]+)$#', 'start' => '/w/dxyxfagcaux/', 'methods' => 'PUT,', ), 2 => array ( 'handler' => 'handler_func', 'original' => '/w/q/qoqn/flsmru/ebuy/{name}', 'regex' => '#^/w/q/qoqn/flsmru/ebuy/(?P<name>[^/]+)$#', 'start' => '/w/q/', 'methods' => 'PATCH,', ), ), 'dq' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/dq/ajr/xnqi/flr/xkr/{name}', 'regex' => '#^/dq/ajr/xnqi/flr/xkr/(?P<name>[^/]+)$#', 'start' => '/dq/ajr/', 'methods' => 'GET,', ), ), 'wjmukkzzdoo' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/wjmukkzzdoo/{name}', 'regex' => '#^/wjmukkzzdoo/(?P<name>[^/]+)$#', 'start' => '/wjmukkzzdoo/', 'methods' => 'POST,', ), ), 'i' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/i/pnyipe/{name}', 'regex' => '#^/i/pnyipe/(?P<name>[^/]+)$#', 'start' => '/i/pnyipe/', 'methods' => 'GET,', ), 1 => array ( 'handler' => 'handler_func', 'original' => '/i/yf/v/grtfnm/{name}', 'regex' => '#^/i/yf/v/grtfnm/(?P<name>[^/]+)$#', 'start' => '/i/yf/', 'methods' => 'POST,', ), ), 'lzdednl' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/lzdednl/{name}', 'regex' => '#^/lzdednl/(?P<name>[^/]+)$#', 'start' => '/lzdednl/', 'methods' => 'GET,', ), ), 'ybmvozlegqcwyy' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ybmvozlegqcwyy/r/{name}', 'regex' => '#^/ybmvozlegqcwyy/r/(?P<name>[^/]+)$#', 'start' => '/ybmvozlegqcwyy/r/', 'methods' => 'PATCH,', ), ), 'hn' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/hn/uf/qvidfpw/wwq/{name}', 'regex' => '#^/hn/uf/qvidfpw/wwq/(?P<name>[^/]+)$#', 'start' => '/hn/uf/', 'methods' => 'PATCH,', ), ), 'hfvnto' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/hfvnto/yge/jw/znhtvl/{name}', 'regex' => '#^/hfvnto/yge/jw/znhtvl/(?P<name>[^/]+)$#', 'start' => '/hfvnto/yge/', 'methods' => 'GET,', ), ), 'hl' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/hl/dukoxwop/f/u/j/wyggr/s/{name}', 'regex' => '#^/hl/dukoxwop/f/u/j/wyggr/s/(?P<name>[^/]+)$#', 'start' => '/hl/dukoxwop/', 'methods' => 'GET,', ), ), 'jwlfjzojdelnuqvw' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/jwlfjzojdelnuqvw/mrz/{name}', 'regex' => '#^/jwlfjzojdelnuqvw/mrz/(?P<name>[^/]+)$#', 'start' => '/jwlfjzojdelnuqvw/mrz/', 'methods' => 'GET,', ), ), 'fymemylb' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/fymemylb/wmxaaxvag/{name}', 'regex' => '#^/fymemylb/wmxaaxvag/(?P<name>[^/]+)$#', 'start' => '/fymemylb/wmxaaxvag/', 'methods' => 'PATCH,', ), ), 'olknvbnndig' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/olknvbnndig/{name}', 'regex' => '#^/olknvbnndig/(?P<name>[^/]+)$#', 'start' => '/olknvbnndig/', 'methods' => 'PATCH,', ), ), 'ky' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ky/erivsi/mgscwaaymm/{name}', 'regex' => '#^/ky/erivsi/mgscwaaymm/(?P<name>[^/]+)$#', 'start' => '/ky/erivsi/', 'methods' => 'POST,', ), ), 'edvruj' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/edvruj/{name}', 'regex' => '#^/edvruj/(?P<name>[^/]+)$#', 'start' => '/edvruj/', 'methods' => 'PUT,', ), ), 'k' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/k/cjrc/mqxbg/tjofjuo/{name}', 'regex' => '#^/k/cjrc/mqxbg/tjofjuo/(?P<name>[^/]+)$#', 'start' => '/k/cjrc/', 'methods' => 'DELETE,', ), 1 => array ( 'handler' => 'handler_func', 'original' => '/k/k/rdad/urcn/j/{name}', 'regex' => '#^/k/k/rdad/urcn/j/(?P<name>[^/]+)$#', 'start' => '/k/k/', 'methods' => 'DELETE,', ), 2 => array ( 'handler' => 'handler_func', 'original' => '/k/zxyb/txug/ur/{name}', 'regex' => '#^/k/zxyb/txug/ur/(?P<name>[^/]+)$#', 'start' => '/k/zxyb/', 'methods' => 'DELETE,', ), ), 'sshd' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/sshd/pfk/vt/{name}', 'regex' => '#^/sshd/pfk/vt/(?P<name>[^/]+)$#', 'start' => '/sshd/pfk/', 'methods' => 'DELETE,', ), ), 'mcqffdfl' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/mcqffdfl/xl/{name}', 'regex' => '#^/mcqffdfl/xl/(?P<name>[^/]+)$#', 'start' => '/mcqffdfl/xl/', 'methods' => 'DELETE,', ), ), 'wbcchnyls' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/wbcchnyls/huvd/{name}', 'regex' => '#^/wbcchnyls/huvd/(?P<name>[^/]+)$#', 'start' => '/wbcchnyls/huvd/', 'methods' => 'PUT,', ), ), 'feejz' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/feejz/fnodf/{name}', 'regex' => '#^/feejz/fnodf/(?P<name>[^/]+)$#', 'start' => '/feejz/fnodf/', 'methods' => 'PUT,', ), ), 'brjj' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/brjj/dqvrv/ot/{name}', 'regex' => '#^/brjj/dqvrv/ot/(?P<name>[^/]+)$#', 'start' => '/brjj/dqvrv/', 'methods' => 'PATCH,', ), ), 'tb' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/tb/l/qqmbdgbfyurb/{name}', 'regex' => '#^/tb/l/qqmbdgbfyurb/(?P<name>[^/]+)$#', 'start' => '/tb/l/', 'methods' => 'POST,', ), ), 'jw' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/jw/v/lcjmquqluz/{name}', 'regex' => '#^/jw/v/lcjmquqluz/(?P<name>[^/]+)$#', 'start' => '/jw/v/', 'methods' => 'GET,', ), ), 'gfgy' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/gfgy/zsxbve/uvon/{name}', 'regex' => '#^/gfgy/zsxbve/uvon/(?P<name>[^/]+)$#', 'start' => '/gfgy/zsxbve/', 'methods' => 'GET,', ), ), 'dglnwoxvrhux' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/dglnwoxvrhux/{name}', 'regex' => '#^/dglnwoxvrhux/(?P<name>[^/]+)$#', 'start' => '/dglnwoxvrhux/', 'methods' => 'DELETE,', ), ), 'eqogga' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/eqogga/{name}', 'regex' => '#^/eqogga/(?P<name>[^/]+)$#', 'start' => '/eqogga/', 'methods' => 'GET,', ), ), 'vlzdlmruxch' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/vlzdlmruxch/jftr/{name}', 'regex' => '#^/vlzdlmruxch/jftr/(?P<name>[^/]+)$#', 'start' => '/vlzdlmruxch/jftr/', 'methods' => 'DELETE,', ), ), 'vkhidt' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/vkhidt/{name}', 'regex' => '#^/vkhidt/(?P<name>[^/]+)$#', 'start' => '/vkhidt/', 'methods' => 'GET,', ), ), 'hwsddosmowlk' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/hwsddosmowlk/{name}', 'regex' => '#^/hwsddosmowlk/(?P<name>[^/]+)$#', 'start' => '/hwsddosmowlk/', 'methods' => 'GET,', ), ), 'rdetgddbjlweokhdjx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/rdetgddbjlweokhdjx/{name}', 'regex' => '#^/rdetgddbjlweokhdjx/(?P<name>[^/]+)$#', 'start' => '/rdetgddbjlweokhdjx/', 'methods' => 'PUT,', ), ), 'xahxcajwb' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/xahxcajwb/{name}', 'regex' => '#^/xahxcajwb/(?P<name>[^/]+)$#', 'start' => '/xahxcajwb/', 'methods' => 'GET,', ), ), 'xf' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/xf/aj/baiulhjtjrj/{name}', 'regex' => '#^/xf/aj/baiulhjtjrj/(?P<name>[^/]+)$#', 'start' => '/xf/aj/', 'methods' => 'DELETE,', ), ), 'pelfx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/pelfx/mrh/upkhg/{name}', 'regex' => '#^/pelfx/mrh/upkhg/(?P<name>[^/]+)$#', 'start' => '/pelfx/mrh/', 'methods' => 'GET,', ), ), 'doinues' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/doinues/md/{name}', 'regex' => '#^/doinues/md/(?P<name>[^/]+)$#', 'start' => '/doinues/md/', 'methods' => 'GET,', ), ), 'gwecbjuw' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/gwecbjuw/ioai/v/ebbyzs/{name}', 'regex' => '#^/gwecbjuw/ioai/v/ebbyzs/(?P<name>[^/]+)$#', 'start' => '/gwecbjuw/ioai/', 'methods' => 'PATCH,', ), ), 'qlj' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/qlj/avlxi/{name}', 'regex' => '#^/qlj/avlxi/(?P<name>[^/]+)$#', 'start' => '/qlj/avlxi/', 'methods' => 'PUT,', ), ), 'urkvkmrcusmy' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/urkvkmrcusmy/{name}', 'regex' => '#^/urkvkmrcusmy/(?P<name>[^/]+)$#', 'start' => '/urkvkmrcusmy/', 'methods' => 'DELETE,', ), ), 'y' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/y/qztqaotenc/vek/{name}', 'regex' => '#^/y/qztqaotenc/vek/(?P<name>[^/]+)$#', 'start' => '/y/qztqaotenc/', 'methods' => 'DELETE,', ), 1 => array ( 'handler' => 'handler_func', 'original' => '/y/urmosockxitgxtp/k/{name}', 'regex' => '#^/y/urmosockxitgxtp/k/(?P<name>[^/]+)$#', 'start' => '/y/urmosockxitgxtp/', 'methods' => 'DELETE,', ), ), 'hqh' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/hqh/zwfbzs/{name}', 'regex' => '#^/hqh/zwfbzs/(?P<name>[^/]+)$#', 'start' => '/hqh/zwfbzs/', 'methods' => 'PATCH,', ), ), 'otkkzklfrdl' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/otkkzklfrdl/{name}', 'regex' => '#^/otkkzklfrdl/(?P<name>[^/]+)$#', 'start' => '/otkkzklfrdl/', 'methods' => 'GET,', ), ), 'got' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/got/ubafzngxm/{name}', 'regex' => '#^/got/ubafzngxm/(?P<name>[^/]+)$#', 'start' => '/got/ubafzngxm/', 'methods' => 'PUT,', ), ), 'dmqbtim' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/dmqbtim/{name}', 'regex' => '#^/dmqbtim/(?P<name>[^/]+)$#', 'start' => '/dmqbtim/', 'methods' => 'GET,', ), ), 'hxr' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/hxr/xpogksz/y/{name}', 'regex' => '#^/hxr/xpogksz/y/(?P<name>[^/]+)$#', 'start' => '/hxr/xpogksz/', 'methods' => 'GET,', ), ), 'jx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/jx/fzxw/{name}', 'regex' => '#^/jx/fzxw/(?P<name>[^/]+)$#', 'start' => '/jx/fzxw/', 'methods' => 'POST,', ), ), 'goecnlealzb' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/goecnlealzb/ybicy/{name}', 'regex' => '#^/goecnlealzb/ybicy/(?P<name>[^/]+)$#', 'start' => '/goecnlealzb/ybicy/', 'methods' => 'POST,', ), ), 'cgq' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/cgq/opkmmelf/{name}', 'regex' => '#^/cgq/opkmmelf/(?P<name>[^/]+)$#', 'start' => '/cgq/opkmmelf/', 'methods' => 'GET,', ), ), 'u' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/u/phvk/{name}', 'regex' => '#^/u/phvk/(?P<name>[^/]+)$#', 'start' => '/u/phvk/', 'methods' => 'GET,', ), ), 'bjspwuadet' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/bjspwuadet/k/mwbcpk/{name}', 'regex' => '#^/bjspwuadet/k/mwbcpk/(?P<name>[^/]+)$#', 'start' => '/bjspwuadet/k/', 'methods' => 'PATCH,', ), ), 'vv' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/vv/kia/tlmqz/{name}', 'regex' => '#^/vv/kia/tlmqz/(?P<name>[^/]+)$#', 'start' => '/vv/kia/', 'methods' => 'PUT,', ), 1 => array ( 'handler' => 'handler_func', 'original' => '/vv/yd/jm/wxsu/{name}', 'regex' => '#^/vv/yd/jm/wxsu/(?P<name>[^/]+)$#', 'start' => '/vv/yd/', 'methods' => 'POST,', ), ), 'yaouihzpbzyzujeky' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/yaouihzpbzyzujeky/{name}', 'regex' => '#^/yaouihzpbzyzujeky/(?P<name>[^/]+)$#', 'start' => '/yaouihzpbzyzujeky/', 'methods' => 'PUT,', ), ), 'huhduvljonanmy' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/huhduvljonanmy/{name}', 'regex' => '#^/huhduvljonanmy/(?P<name>[^/]+)$#', 'start' => '/huhduvljonanmy/', 'methods' => 'DELETE,', ), ), 'ejyi' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ejyi/qkc/{name}', 'regex' => '#^/ejyi/qkc/(?P<name>[^/]+)$#', 'start' => '/ejyi/qkc/', 'methods' => 'POST,', ), ), 'gtxxxfufk' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/gtxxxfufk/tgsaks/{name}', 'regex' => '#^/gtxxxfufk/tgsaks/(?P<name>[^/]+)$#', 'start' => '/gtxxxfufk/tgsaks/', 'methods' => 'GET,', ), ), 'ixnjhwjqxy' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ixnjhwjqxy/{name}', 'regex' => '#^/ixnjhwjqxy/(?P<name>[^/]+)$#', 'start' => '/ixnjhwjqxy/', 'methods' => 'PUT,', ), ), 'j' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/j/ukg/ale/{name}', 'regex' => '#^/j/ukg/ale/(?P<name>[^/]+)$#', 'start' => '/j/ukg/', 'methods' => 'PATCH,', ), ), 'gmuokbayt' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/gmuokbayt/jyijfvgg/{name}', 'regex' => '#^/gmuokbayt/jyijfvgg/(?P<name>[^/]+)$#', 'start' => '/gmuokbayt/jyijfvgg/', 'methods' => 'GET,', ), ), 'yneqw' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/yneqw/uonhnctkkiy/{name}', 'regex' => '#^/yneqw/uonhnctkkiy/(?P<name>[^/]+)$#', 'start' => '/yneqw/uonhnctkkiy/', 'methods' => 'GET,', ), ), 'yuccjrwv' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/yuccjrwv/zfqjdkmxwxxz/{name}', 'regex' => '#^/yuccjrwv/zfqjdkmxwxxz/(?P<name>[^/]+)$#', 'start' => '/yuccjrwv/zfqjdkmxwxxz/', 'methods' => 'PATCH,', ), ), 'mfvrxojy' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/mfvrxojy/wp/b/gt/oyw/{name}', 'regex' => '#^/mfvrxojy/wp/b/gt/oyw/(?P<name>[^/]+)$#', 'start' => '/mfvrxojy/wp/', 'methods' => 'DELETE,', ), ), 'pyqxjjeabeinlq' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/pyqxjjeabeinlq/{name}', 'regex' => '#^/pyqxjjeabeinlq/(?P<name>[^/]+)$#', 'start' => '/pyqxjjeabeinlq/', 'methods' => 'PATCH,', ), ), 'fbgjcltelcwiwxjh' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/fbgjcltelcwiwxjh/{name}', 'regex' => '#^/fbgjcltelcwiwxjh/(?P<name>[^/]+)$#', 'start' => '/fbgjcltelcwiwxjh/', 'methods' => 'GET,', ), ), 'gcjghow' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/gcjghow/ldpasqbwc/djy/{name}', 'regex' => '#^/gcjghow/ldpasqbwc/djy/(?P<name>[^/]+)$#', 'start' => '/gcjghow/ldpasqbwc/', 'methods' => 'GET,', ), ), 'ys' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ys/kc/zrvhvt/{name}', 'regex' => '#^/ys/kc/zrvhvt/(?P<name>[^/]+)$#', 'start' => '/ys/kc/', 'methods' => 'GET,', ), ), 'wgose' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/wgose/{name}', 'regex' => '#^/wgose/(?P<name>[^/]+)$#', 'start' => '/wgose/', 'methods' => 'POST,', ), ), 'zxx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/zxx/vzzw/{name}', 'regex' => '#^/zxx/vzzw/(?P<name>[^/]+)$#', 'start' => '/zxx/vzzw/', 'methods' => 'DELETE,', ), ), 'bod' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/bod/sc/n/yf/jftuyqyn/{name}', 'regex' => '#^/bod/sc/n/yf/jftuyqyn/(?P<name>[^/]+)$#', 'start' => '/bod/sc/', 'methods' => 'PUT,', ), ), 'chyyt' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/chyyt/{name}', 'regex' => '#^/chyyt/(?P<name>[^/]+)$#', 'start' => '/chyyt/', 'methods' => 'GET,', ), ), 'ntiqaf' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ntiqaf/emtyjtck/np/{name}', 'regex' => '#^/ntiqaf/emtyjtck/np/(?P<name>[^/]+)$#', 'start' => '/ntiqaf/emtyjtck/', 'methods' => 'PUT,', ), ), 'cqehjacsldfnite' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/cqehjacsldfnite/lsx/{name}', 'regex' => '#^/cqehjacsldfnite/lsx/(?P<name>[^/]+)$#', 'start' => '/cqehjacsldfnite/lsx/', 'methods' => 'PUT,', ), ), 'jl' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/jl/sobgrddd/elbdkfhxl/{name}', 'regex' => '#^/jl/sobgrddd/elbdkfhxl/(?P<name>[^/]+)$#', 'start' => '/jl/sobgrddd/', 'methods' => 'GET,', ), ), 'euhwothu' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/euhwothu/pss/{name}', 'regex' => '#^/euhwothu/pss/(?P<name>[^/]+)$#', 'start' => '/euhwothu/pss/', 'methods' => 'GET,', ), ), 'mzt' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/mzt/kxgzxui/{name}', 'regex' => '#^/mzt/kxgzxui/(?P<name>[^/]+)$#', 'start' => '/mzt/kxgzxui/', 'methods' => 'GET,', ), ), 'tmcclrqrx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/tmcclrqrx/{name}', 'regex' => '#^/tmcclrqrx/(?P<name>[^/]+)$#', 'start' => '/tmcclrqrx/', 'methods' => 'GET,', ), ), 'q' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/q/eekyzgotqb/yxze/{name}', 'regex' => '#^/q/eekyzgotqb/yxze/(?P<name>[^/]+)$#', 'start' => '/q/eekyzgotqb/', 'methods' => 'DELETE,', ), ), 'lhckk' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/lhckk/m/x/{name}', 'regex' => '#^/lhckk/m/x/(?P<name>[^/]+)$#', 'start' => '/lhckk/m/', 'methods' => 'GET,', ), ), 'teizndpnaa' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/teizndpnaa/hsv/{name}', 'regex' => '#^/teizndpnaa/hsv/(?P<name>[^/]+)$#', 'start' => '/teizndpnaa/hsv/', 'methods' => 'DELETE,', ), ), 'xpvhh' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/xpvhh/vnaskup/{name}', 'regex' => '#^/xpvhh/vnaskup/(?P<name>[^/]+)$#', 'start' => '/xpvhh/vnaskup/', 'methods' => 'DELETE,', ), ), 'bawdbilcjeuq' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/bawdbilcjeuq/{name}', 'regex' => '#^/bawdbilcjeuq/(?P<name>[^/]+)$#', 'start' => '/bawdbilcjeuq/', 'methods' => 'GET,', ), ), 'hcgydndhw' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/hcgydndhw/{name}', 'regex' => '#^/hcgydndhw/(?P<name>[^/]+)$#', 'start' => '/hcgydndhw/', 'methods' => 'POST,', ), ), 'xbemebjjsubzar' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/xbemebjjsubzar/{name}', 'regex' => '#^/xbemebjjsubzar/(?P<name>[^/]+)$#', 'start' => '/xbemebjjsubzar/', 'methods' => 'GET,', ), ), 's' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/s/nshatkjc/{name}', 'regex' => '#^/s/nshatkjc/(?P<name>[^/]+)$#', 'start' => '/s/nshatkjc/', 'methods' => 'DELETE,', ), 1 => array ( 'handler' => 'handler_func', 'original' => '/s/stv/oxnauqrftk/zmf/{name}', 'regex' => '#^/s/stv/oxnauqrftk/zmf/(?P<name>[^/]+)$#', 'start' => '/s/stv/', 'methods' => 'GET,', ), ), 'rllv' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/rllv/scon/fvkbpb/{name}', 'regex' => '#^/rllv/scon/fvkbpb/(?P<name>[^/]+)$#', 'start' => '/rllv/scon/', 'methods' => 'GET,', ), ), 'feuct' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/feuct/{name}', 'regex' => '#^/feuct/(?P<name>[^/]+)$#', 'start' => '/feuct/', 'methods' => 'POST,', ), ), 'vziyqqseyy' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/vziyqqseyy/v/{name}', 'regex' => '#^/vziyqqseyy/v/(?P<name>[^/]+)$#', 'start' => '/vziyqqseyy/v/', 'methods' => 'GET,', ), ), 'o' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/o/lsqjjfnpc/ou/{name}', 'regex' => '#^/o/lsqjjfnpc/ou/(?P<name>[^/]+)$#', 'start' => '/o/lsqjjfnpc/', 'methods' => 'PUT,', ), 1 => array ( 'handler' => 'handler_func', 'original' => '/o/pltfmlny/yvb/jcmmdwm/{name}', 'regex' => '#^/o/pltfmlny/yvb/jcmmdwm/(?P<name>[^/]+)$#', 'start' => '/o/pltfmlny/', 'methods' => 'PATCH,', ), ), 'fou' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/fou/v/u/oqohx/{name}', 'regex' => '#^/fou/v/u/oqohx/(?P<name>[^/]+)$#', 'start' => '/fou/v/', 'methods' => 'GET,', ), ), 'lmxmwx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/lmxmwx/qwsqcevfrmook/{name}', 'regex' => '#^/lmxmwx/qwsqcevfrmook/(?P<name>[^/]+)$#', 'start' => '/lmxmwx/qwsqcevfrmook/', 'methods' => 'POST,', ), ), 'osqj' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/osqj/rlibu/qt/{name}', 'regex' => '#^/osqj/rlibu/qt/(?P<name>[^/]+)$#', 'start' => '/osqj/rlibu/', 'methods' => 'GET,', ), ), 'eehcpuonlgvyhsrdtn' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/eehcpuonlgvyhsrdtn/{name}', 'regex' => '#^/eehcpuonlgvyhsrdtn/(?P<name>[^/]+)$#', 'start' => '/eehcpuonlgvyhsrdtn/', 'methods' => 'PATCH,', ), ), 'axr' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/axr/bgr/{name}', 'regex' => '#^/axr/bgr/(?P<name>[^/]+)$#', 'start' => '/axr/bgr/', 'methods' => 'PUT,', ), ), 'ru' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ru/c/if/eesfvt/psliyz/{name}', 'regex' => '#^/ru/c/if/eesfvt/psliyz/(?P<name>[^/]+)$#', 'start' => '/ru/c/', 'methods' => 'PUT,', ), ), 'jqycjwprsmicxaayzq' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/jqycjwprsmicxaayzq/m/{name}', 'regex' => '#^/jqycjwprsmicxaayzq/m/(?P<name>[^/]+)$#', 'start' => '/jqycjwprsmicxaayzq/m/', 'methods' => 'DELETE,', ), ), 'ccwsdnwt' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ccwsdnwt/{name}', 'regex' => '#^/ccwsdnwt/(?P<name>[^/]+)$#', 'start' => '/ccwsdnwt/', 'methods' => 'GET,', ), ), 'wibnaux' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/wibnaux/{name}', 'regex' => '#^/wibnaux/(?P<name>[^/]+)$#', 'start' => '/wibnaux/', 'methods' => 'DELETE,', ), ), 'vdbxlepnwb' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/vdbxlepnwb/{name}', 'regex' => '#^/vdbxlepnwb/(?P<name>[^/]+)$#', 'start' => '/vdbxlepnwb/', 'methods' => 'POST,', ), ), 'nalhn' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/nalhn/{name}', 'regex' => '#^/nalhn/(?P<name>[^/]+)$#', 'start' => '/nalhn/', 'methods' => 'PUT,', ), ), 'svqemfv' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/svqemfv/{name}', 'regex' => '#^/svqemfv/(?P<name>[^/]+)$#', 'start' => '/svqemfv/', 'methods' => 'GET,', ), ), 'pbhsdtrwki' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/pbhsdtrwki/d/{name}', 'regex' => '#^/pbhsdtrwki/d/(?P<name>[^/]+)$#', 'start' => '/pbhsdtrwki/d/', 'methods' => 'PATCH,', ), ), 'mstrj' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/mstrj/e/b/vgkbir/qcfhm/{name}', 'regex' => '#^/mstrj/e/b/vgkbir/qcfhm/(?P<name>[^/]+)$#', 'start' => '/mstrj/e/', 'methods' => 'GET,', ), ), 'isnrezacwrtfdjwv' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/isnrezacwrtfdjwv/{name}', 'regex' => '#^/isnrezacwrtfdjwv/(?P<name>[^/]+)$#', 'start' => '/isnrezacwrtfdjwv/', 'methods' => 'PUT,', ), ), 'vfb' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/vfb/nd/{name}', 'regex' => '#^/vfb/nd/(?P<name>[^/]+)$#', 'start' => '/vfb/nd/', 'methods' => 'DELETE,', ), ), 'rzkhtgxvrd' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/rzkhtgxvrd/{name}', 'regex' => '#^/rzkhtgxvrd/(?P<name>[^/]+)$#', 'start' => '/rzkhtgxvrd/', 'methods' => 'PATCH,', ), ), 'zsrzr' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/zsrzr/pgv/sgfalujn/{name}', 'regex' => '#^/zsrzr/pgv/sgfalujn/(?P<name>[^/]+)$#', 'start' => '/zsrzr/pgv/', 'methods' => 'GET,', ), ), 'amj' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/amj/su/p/xoyrtinnp/{name}', 'regex' => '#^/amj/su/p/xoyrtinnp/(?P<name>[^/]+)$#', 'start' => '/amj/su/', 'methods' => 'PATCH,', ), ), 'cyosoqjkzkvmwhfvfe' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/cyosoqjkzkvmwhfvfe/y/{name}', 'regex' => '#^/cyosoqjkzkvmwhfvfe/y/(?P<name>[^/]+)$#', 'start' => '/cyosoqjkzkvmwhfvfe/y/', 'methods' => 'DELETE,', ), ), 'rhgqrxpekgokqndhq' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/rhgqrxpekgokqndhq/{name}', 'regex' => '#^/rhgqrxpekgokqndhq/(?P<name>[^/]+)$#', 'start' => '/rhgqrxpekgokqndhq/', 'methods' => 'PUT,', ), ), 'wfhtdiz' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/wfhtdiz/ujc/ldyuqphq/{name}', 'regex' => '#^/wfhtdiz/ujc/ldyuqphq/(?P<name>[^/]+)$#', 'start' => '/wfhtdiz/ujc/', 'methods' => 'DELETE,', ), ), 'kgrtapne' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/kgrtapne/{name}', 'regex' => '#^/kgrtapne/(?P<name>[^/]+)$#', 'start' => '/kgrtapne/', 'methods' => 'DELETE,', ), ), 'fz' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/fz/bdwwhba/y/{name}', 'regex' => '#^/fz/bdwwhba/y/(?P<name>[^/]+)$#', 'start' => '/fz/bdwwhba/', 'methods' => 'DELETE,', ), ), 'zgzvlqbyu' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/zgzvlqbyu/{name}', 'regex' => '#^/zgzvlqbyu/(?P<name>[^/]+)$#', 'start' => '/zgzvlqbyu/', 'methods' => 'PATCH,', ), ), 'heodgiuouzbxs' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/heodgiuouzbxs/ch/zg/gzp/{name}', 'regex' => '#^/heodgiuouzbxs/ch/zg/gzp/(?P<name>[^/]+)$#', 'start' => '/heodgiuouzbxs/ch/', 'methods' => 'GET,', ), ), 'nmki' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/nmki/fhg/{name}', 'regex' => '#^/nmki/fhg/(?P<name>[^/]+)$#', 'start' => '/nmki/fhg/', 'methods' => 'PATCH,', ), ), 'teamu' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/teamu/g/hs/{name}', 'regex' => '#^/teamu/g/hs/(?P<name>[^/]+)$#', 'start' => '/teamu/g/', 'methods' => 'DELETE,', ), ), 'wpcw' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/wpcw/gjdlrndz/h/{name}', 'regex' => '#^/wpcw/gjdlrndz/h/(?P<name>[^/]+)$#', 'start' => '/wpcw/gjdlrndz/', 'methods' => 'PUT,', ), ), 'rwl' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/rwl/gpqylkis/qau/g/{name}', 'regex' => '#^/rwl/gpqylkis/qau/g/(?P<name>[^/]+)$#', 'start' => '/rwl/gpqylkis/', 'methods' => 'DELETE,', ), ), 'rqnm' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/rqnm/ngqbv/x/jyoxf/{name}', 'regex' => '#^/rqnm/ngqbv/x/jyoxf/(?P<name>[^/]+)$#', 'start' => '/rqnm/ngqbv/', 'methods' => 'GET,', ), ), 'hxz' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/hxz/uxqnwg/fsrrsd/t/{name}', 'regex' => '#^/hxz/uxqnwg/fsrrsd/t/(?P<name>[^/]+)$#', 'start' => '/hxz/uxqnwg/', 'methods' => 'DELETE,', ), ), 'dg' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/dg/zfcja/nydrfvxoc/{name}', 'regex' => '#^/dg/zfcja/nydrfvxoc/(?P<name>[^/]+)$#', 'start' => '/dg/zfcja/', 'methods' => 'POST,', ), ), 'ulzqx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ulzqx/kjyxkvmf/{name}', 'regex' => '#^/ulzqx/kjyxkvmf/(?P<name>[^/]+)$#', 'start' => '/ulzqx/kjyxkvmf/', 'methods' => 'PATCH,', ), ), 'ebhdqassptzszqff' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ebhdqassptzszqff/{name}', 'regex' => '#^/ebhdqassptzszqff/(?P<name>[^/]+)$#', 'start' => '/ebhdqassptzszqff/', 'methods' => 'POST,', ), ), 'qlbeabtksl' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/qlbeabtksl/ot/{name}', 'regex' => '#^/qlbeabtksl/ot/(?P<name>[^/]+)$#', 'start' => '/qlbeabtksl/ot/', 'methods' => 'DELETE,', ), ), 'ir' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ir/geh/ib/{name}', 'regex' => '#^/ir/geh/ib/(?P<name>[^/]+)$#', 'start' => '/ir/geh/', 'methods' => 'DELETE,', ), ), 'lqxaepy' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/lqxaepy/nbpnoit/{name}', 'regex' => '#^/lqxaepy/nbpnoit/(?P<name>[^/]+)$#', 'start' => '/lqxaepy/nbpnoit/', 'methods' => 'PUT,', ), ), 'd' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/d/eodhxg/jeeosom/xv/{name}', 'regex' => '#^/d/eodhxg/jeeosom/xv/(?P<name>[^/]+)$#', 'start' => '/d/eodhxg/', 'methods' => 'DELETE,', ), 1 => array ( 'handler' => 'handler_func', 'original' => '/d/i/v/vjbehsdtawkmrr/{name}', 'regex' => '#^/d/i/v/vjbehsdtawkmrr/(?P<name>[^/]+)$#', 'start' => '/d/i/', 'methods' => 'PATCH,', ), ), 'xhrfzrng' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/xhrfzrng/iwqb/knwe/{name}', 'regex' => '#^/xhrfzrng/iwqb/knwe/(?P<name>[^/]+)$#', 'start' => '/xhrfzrng/iwqb/', 'methods' => 'GET,', ), ), 'tf' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/tf/xp/bfgvijlh/{name}', 'regex' => '#^/tf/xp/bfgvijlh/(?P<name>[^/]+)$#', 'start' => '/tf/xp/', 'methods' => 'PATCH,', ), ), 'bi' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/bi/clgwegqikidwbca/{name}', 'regex' => '#^/bi/clgwegqikidwbca/(?P<name>[^/]+)$#', 'start' => '/bi/clgwegqikidwbca/', 'methods' => 'POST,', ), ), 'pi' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/pi/oy/s/debtc/zwrezd/{name}', 'regex' => '#^/pi/oy/s/debtc/zwrezd/(?P<name>[^/]+)$#', 'start' => '/pi/oy/', 'methods' => 'GET,', ), ), 'fqvhadkm' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/fqvhadkm/yxy/{name}', 'regex' => '#^/fqvhadkm/yxy/(?P<name>[^/]+)$#', 'start' => '/fqvhadkm/yxy/', 'methods' => 'POST,', ), ), 'qpmfjjb' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/qpmfjjb/lguzdm/{name}', 'regex' => '#^/qpmfjjb/lguzdm/(?P<name>[^/]+)$#', 'start' => '/qpmfjjb/lguzdm/', 'methods' => 'POST,', ), ), 'vp' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/vp/kmkkdvfiudylb/{name}', 'regex' => '#^/vp/kmkkdvfiudylb/(?P<name>[^/]+)$#', 'start' => '/vp/kmkkdvfiudylb/', 'methods' => 'POST,', ), ), 'm' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/m/wuprnzddm/{name}', 'regex' => '#^/m/wuprnzddm/(?P<name>[^/]+)$#', 'start' => '/m/wuprnzddm/', 'methods' => 'GET,', ), ), 'dszqhvsmk' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/dszqhvsmk/{name}', 'regex' => '#^/dszqhvsmk/(?P<name>[^/]+)$#', 'start' => '/dszqhvsmk/', 'methods' => 'GET,', ), ), 'hbkmjeuwx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/hbkmjeuwx/{name}', 'regex' => '#^/hbkmjeuwx/(?P<name>[^/]+)$#', 'start' => '/hbkmjeuwx/', 'methods' => 'POST,', ), ), 'xtmrkn' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/xtmrkn/mtklkmltuvyli/{name}', 'regex' => '#^/xtmrkn/mtklkmltuvyli/(?P<name>[^/]+)$#', 'start' => '/xtmrkn/mtklkmltuvyli/', 'methods' => 'DELETE,', ), ), 'osdjnsotrqkpxmj' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/osdjnsotrqkpxmj/{name}', 'regex' => '#^/osdjnsotrqkpxmj/(?P<name>[^/]+)$#', 'start' => '/osdjnsotrqkpxmj/', 'methods' => 'POST,', ), ), 'hzxrzqgioadesx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/hzxrzqgioadesx/kxibwe/{name}', 'regex' => '#^/hzxrzqgioadesx/kxibwe/(?P<name>[^/]+)$#', 'start' => '/hzxrzqgioadesx/kxibwe/', 'methods' => 'PATCH,', ), ), 'zzxxaazxyewdd' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/zzxxaazxyewdd/axcrlqm/{name}', 'regex' => '#^/zzxxaazxyewdd/axcrlqm/(?P<name>[^/]+)$#', 'start' => '/zzxxaazxyewdd/axcrlqm/', 'methods' => 'PATCH,', ), ), 'azlyygddafxtqc' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/azlyygddafxtqc/{name}', 'regex' => '#^/azlyygddafxtqc/(?P<name>[^/]+)$#', 'start' => '/azlyygddafxtqc/', 'methods' => 'POST,', ), ), 'jwmfeothsu' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/jwmfeothsu/{name}', 'regex' => '#^/jwmfeothsu/(?P<name>[^/]+)$#', 'start' => '/jwmfeothsu/', 'methods' => 'PATCH,', ), ), 'pj' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/pj/zjurvmlruluzifk/{name}', 'regex' => '#^/pj/zjurvmlruluzifk/(?P<name>[^/]+)$#', 'start' => '/pj/zjurvmlruluzifk/', 'methods' => 'PUT,', ), ), 'prx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/prx/juoborfd/zpw/{name}', 'regex' => '#^/prx/juoborfd/zpw/(?P<name>[^/]+)$#', 'start' => '/prx/juoborfd/', 'methods' => 'PATCH,', ), ), 'jsonfeadvmwws' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/jsonfeadvmwws/{name}', 'regex' => '#^/jsonfeadvmwws/(?P<name>[^/]+)$#', 'start' => '/jsonfeadvmwws/', 'methods' => 'DELETE,', ), ), 'hmhwljuzgx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/hmhwljuzgx/p/ulb/{name}', 'regex' => '#^/hmhwljuzgx/p/ulb/(?P<name>[^/]+)$#', 'start' => '/hmhwljuzgx/p/', 'methods' => 'PATCH,', ), ), 'qlfhybcx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/qlfhybcx/wk/{name}', 'regex' => '#^/qlfhybcx/wk/(?P<name>[^/]+)$#', 'start' => '/qlfhybcx/wk/', 'methods' => 'POST,', ), ), 'fnmqj' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/fnmqj/vxnir/wyfujkxjw/{name}', 'regex' => '#^/fnmqj/vxnir/wyfujkxjw/(?P<name>[^/]+)$#', 'start' => '/fnmqj/vxnir/', 'methods' => 'PUT,', ), ), 'uvqltbbxcwwkfss' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/uvqltbbxcwwkfss/qgp/tz/{name}', 'regex' => '#^/uvqltbbxcwwkfss/qgp/tz/(?P<name>[^/]+)$#', 'start' => '/uvqltbbxcwwkfss/qgp/', 'methods' => 'GET,', ), ), 'qnhosvkmocayrotlz' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/qnhosvkmocayrotlz/zh/{name}', 'regex' => '#^/qnhosvkmocayrotlz/zh/(?P<name>[^/]+)$#', 'start' => '/qnhosvkmocayrotlz/zh/', 'methods' => 'DELETE,', ), ), 'nzbnutpmiifgm' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/nzbnutpmiifgm/{name}', 'regex' => '#^/nzbnutpmiifgm/(?P<name>[^/]+)$#', 'start' => '/nzbnutpmiifgm/', 'methods' => 'POST,', ), ), 'msfgywfxizjjzlnous' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/msfgywfxizjjzlnous/{name}', 'regex' => '#^/msfgywfxizjjzlnous/(?P<name>[^/]+)$#', 'start' => '/msfgywfxizjjzlnous/', 'methods' => 'PATCH,', ), ), 'xmopwmgv' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/xmopwmgv/{name}', 'regex' => '#^/xmopwmgv/(?P<name>[^/]+)$#', 'start' => '/xmopwmgv/', 'methods' => 'PATCH,', ), ), 'tknndkpsdwfrksndwbj' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/tknndkpsdwfrksndwbj/{name}', 'regex' => '#^/tknndkpsdwfrksndwbj/(?P<name>[^/]+)$#', 'start' => '/tknndkpsdwfrksndwbj/', 'methods' => 'DELETE,', ), ), 'aunhkuxl' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/aunhkuxl/{name}', 'regex' => '#^/aunhkuxl/(?P<name>[^/]+)$#', 'start' => '/aunhkuxl/', 'methods' => 'POST,', ), ), 'ildu' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ildu/arwg/{name}', 'regex' => '#^/ildu/arwg/(?P<name>[^/]+)$#', 'start' => '/ildu/arwg/', 'methods' => 'POST,', ), ), 'ff' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ff/mnkb/{name}', 'regex' => '#^/ff/mnkb/(?P<name>[^/]+)$#', 'start' => '/ff/mnkb/', 'methods' => 'POST,', ), ), 'yhurkwuyz' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/yhurkwuyz/{name}', 'regex' => '#^/yhurkwuyz/(?P<name>[^/]+)$#', 'start' => '/yhurkwuyz/', 'methods' => 'PATCH,', ), ), 'vemzc' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/vemzc/dsvlv/{name}', 'regex' => '#^/vemzc/dsvlv/(?P<name>[^/]+)$#', 'start' => '/vemzc/dsvlv/', 'methods' => 'POST,', ), ), 'fnufmkvxjrxdjfsg' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/fnufmkvxjrxdjfsg/{name}', 'regex' => '#^/fnufmkvxjrxdjfsg/(?P<name>[^/]+)$#', 'start' => '/fnufmkvxjrxdjfsg/', 'methods' => 'PATCH,', ), ), 'dd' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/dd/geb/tk/mwua/n/gy/{name}', 'regex' => '#^/dd/geb/tk/mwua/n/gy/(?P<name>[^/]+)$#', 'start' => '/dd/geb/', 'methods' => 'PUT,', ), ), 'ruqaqals' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ruqaqals/e/muhlarcn/y/{name}', 'regex' => '#^/ruqaqals/e/muhlarcn/y/(?P<name>[^/]+)$#', 'start' => '/ruqaqals/e/', 'methods' => 'DELETE,', ), ), 'zywcxn' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/zywcxn/wv/pwkggcao/{name}', 'regex' => '#^/zywcxn/wv/pwkggcao/(?P<name>[^/]+)$#', 'start' => '/zywcxn/wv/', 'methods' => 'POST,', ), ), 'mcv' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/mcv/m/epipz/wre/jfgvaw/{name}', 'regex' => '#^/mcv/m/epipz/wre/jfgvaw/(?P<name>[^/]+)$#', 'start' => '/mcv/m/', 'methods' => 'PATCH,', ), ), 'vg' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/vg/vt/nccdf/{name}', 'regex' => '#^/vg/vt/nccdf/(?P<name>[^/]+)$#', 'start' => '/vg/vt/', 'methods' => 'PATCH,', ), ), 'huyp' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/huyp/llxkptfu/{name}', 'regex' => '#^/huyp/llxkptfu/(?P<name>[^/]+)$#', 'start' => '/huyp/llxkptfu/', 'methods' => 'PATCH,', ), ), 'eurufndacy' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/eurufndacy/{name}', 'regex' => '#^/eurufndacy/(?P<name>[^/]+)$#', 'start' => '/eurufndacy/', 'methods' => 'PUT,', ), ), 'iltzazxuniq' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/iltzazxuniq/tbclwj/wtu/{name}', 'regex' => '#^/iltzazxuniq/tbclwj/wtu/(?P<name>[^/]+)$#', 'start' => '/iltzazxuniq/tbclwj/', 'methods' => 'PATCH,', ), ), 'bvxddc' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/bvxddc/{name}', 'regex' => '#^/bvxddc/(?P<name>[^/]+)$#', 'start' => '/bvxddc/', 'methods' => 'GET,', ), ), 'ifpqm' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ifpqm/{name}', 'regex' => '#^/ifpqm/(?P<name>[^/]+)$#', 'start' => '/ifpqm/', 'methods' => 'POST,', ), ), 'vtbjfz' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/vtbjfz/{name}', 'regex' => '#^/vtbjfz/(?P<name>[^/]+)$#', 'start' => '/vtbjfz/', 'methods' => 'PUT,', ), ), 'zxkubxlie' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/zxkubxlie/{name}', 'regex' => '#^/zxkubxlie/(?P<name>[^/]+)$#', 'start' => '/zxkubxlie/', 'methods' => 'POST,', ), ), 'v' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/v/kss/kr/zeji/{name}', 'regex' => '#^/v/kss/kr/zeji/(?P<name>[^/]+)$#', 'start' => '/v/kss/', 'methods' => 'GET,', ), 1 => array ( 'handler' => 'handler_func', 'original' => '/v/ecbba/zks/aje/yhkiviwo/{name}', 'regex' => '#^/v/ecbba/zks/aje/yhkiviwo/(?P<name>[^/]+)$#', 'start' => '/v/ecbba/', 'methods' => 'GET,', ), ), 'zmmzbhulte' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/zmmzbhulte/{name}', 'regex' => '#^/zmmzbhulte/(?P<name>[^/]+)$#', 'start' => '/zmmzbhulte/', 'methods' => 'PATCH,', ), ), 'xit' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/xit/irdwbyan/xtqxhyi/{name}', 'regex' => '#^/xit/irdwbyan/xtqxhyi/(?P<name>[^/]+)$#', 'start' => '/xit/irdwbyan/', 'methods' => 'PATCH,', ), ), 'wrc' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/wrc/asrwz/{name}', 'regex' => '#^/wrc/asrwz/(?P<name>[^/]+)$#', 'start' => '/wrc/asrwz/', 'methods' => 'PATCH,', ), ), 'zzm' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/zzm/ouuixk/zfquvx/{name}', 'regex' => '#^/zzm/ouuixk/zfquvx/(?P<name>[^/]+)$#', 'start' => '/zzm/ouuixk/', 'methods' => 'GET,', ), ), 'mervugd' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/mervugd/hhmpme/qw/{name}', 'regex' => '#^/mervugd/hhmpme/qw/(?P<name>[^/]+)$#', 'start' => '/mervugd/hhmpme/', 'methods' => 'DELETE,', ), ), 'tufpot' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/tufpot/ovmp/bgt/{name}', 'regex' => '#^/tufpot/ovmp/bgt/(?P<name>[^/]+)$#', 'start' => '/tufpot/ovmp/', 'methods' => 'DELETE,', ), ), 'qzgnrqsfsh' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/qzgnrqsfsh/{name}', 'regex' => '#^/qzgnrqsfsh/(?P<name>[^/]+)$#', 'start' => '/qzgnrqsfsh/', 'methods' => 'GET,', ), ), 'yaj' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/yaj/vt/{name}', 'regex' => '#^/yaj/vt/(?P<name>[^/]+)$#', 'start' => '/yaj/vt/', 'methods' => 'PATCH,', ), ), 'uup' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/uup/fnbcqlbxaw/{name}', 'regex' => '#^/uup/fnbcqlbxaw/(?P<name>[^/]+)$#', 'start' => '/uup/fnbcqlbxaw/', 'methods' => 'DELETE,', ), ), 'zs' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/zs/c/oo/{name}', 'regex' => '#^/zs/c/oo/(?P<name>[^/]+)$#', 'start' => '/zs/c/', 'methods' => 'DELETE,', ), ), 'oziul' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/oziul/emvunrrvo/axja/am/{name}', 'regex' => '#^/oziul/emvunrrvo/axja/am/(?P<name>[^/]+)$#', 'start' => '/oziul/emvunrrvo/', 'methods' => 'PATCH,', ), ), 'qyxyikycogdxjx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/qyxyikycogdxjx/{name}', 'regex' => '#^/qyxyikycogdxjx/(?P<name>[^/]+)$#', 'start' => '/qyxyikycogdxjx/', 'methods' => 'DELETE,', ), ), 'bsdtb' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/bsdtb/ycib/{name}', 'regex' => '#^/bsdtb/ycib/(?P<name>[^/]+)$#', 'start' => '/bsdtb/ycib/', 'methods' => 'GET,', ), ), 'ytukrbanedhpuwbm' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ytukrbanedhpuwbm/{name}', 'regex' => '#^/ytukrbanedhpuwbm/(?P<name>[^/]+)$#', 'start' => '/ytukrbanedhpuwbm/', 'methods' => 'DELETE,', ), ), 'dseywfjtronc' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/dseywfjtronc/{name}', 'regex' => '#^/dseywfjtronc/(?P<name>[^/]+)$#', 'start' => '/dseywfjtronc/', 'methods' => 'POST,', ), ), 'iixq' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/iixq/u/{name}', 'regex' => '#^/iixq/u/(?P<name>[^/]+)$#', 'start' => '/iixq/u/', 'methods' => 'GET,', ), ), 'kmdupuoapgxvmsavn' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/kmdupuoapgxvmsavn/hz/{name}', 'regex' => '#^/kmdupuoapgxvmsavn/hz/(?P<name>[^/]+)$#', 'start' => '/kmdupuoapgxvmsavn/hz/', 'methods' => 'PUT,', ), ), 'hpfds' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/hpfds/ps/f/{name}', 'regex' => '#^/hpfds/ps/f/(?P<name>[^/]+)$#', 'start' => '/hpfds/ps/', 'methods' => 'GET,', ), ), 'usf' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/usf/uqtugh/{name}', 'regex' => '#^/usf/uqtugh/(?P<name>[^/]+)$#', 'start' => '/usf/uqtugh/', 'methods' => 'GET,', ), ), 'ob' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ob/feh/{name}', 'regex' => '#^/ob/feh/(?P<name>[^/]+)$#', 'start' => '/ob/feh/', 'methods' => 'POST,', ), ), 'oyljbh' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/oyljbh/pnlh/{name}', 'regex' => '#^/oyljbh/pnlh/(?P<name>[^/]+)$#', 'start' => '/oyljbh/pnlh/', 'methods' => 'POST,', ), ), 'sfmeeozeogyc' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/sfmeeozeogyc/{name}', 'regex' => '#^/sfmeeozeogyc/(?P<name>[^/]+)$#', 'start' => '/sfmeeozeogyc/', 'methods' => 'PUT,', ), ), 'lqnrckaq' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/lqnrckaq/iw/{name}', 'regex' => '#^/lqnrckaq/iw/(?P<name>[^/]+)$#', 'start' => '/lqnrckaq/iw/', 'methods' => 'PUT,', ), ), 'vuyitfxp' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/vuyitfxp/miuq/{name}', 'regex' => '#^/vuyitfxp/miuq/(?P<name>[^/]+)$#', 'start' => '/vuyitfxp/miuq/', 'methods' => 'DELETE,', ), ), 'wbpezjz' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/wbpezjz/fjphnkjt/{name}', 'regex' => '#^/wbpezjz/fjphnkjt/(?P<name>[^/]+)$#', 'start' => '/wbpezjz/fjphnkjt/', 'methods' => 'PUT,', ), ), 'duvnpjvjfdbkf' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/duvnpjvjfdbkf/vet/{name}', 'regex' => '#^/duvnpjvjfdbkf/vet/(?P<name>[^/]+)$#', 'start' => '/duvnpjvjfdbkf/vet/', 'methods' => 'PATCH,', ), ), 'jr' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/jr/gzrg/{name}', 'regex' => '#^/jr/gzrg/(?P<name>[^/]+)$#', 'start' => '/jr/gzrg/', 'methods' => 'GET,', ), ), 'caifwbwmvlu' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/caifwbwmvlu/{name}', 'regex' => '#^/caifwbwmvlu/(?P<name>[^/]+)$#', 'start' => '/caifwbwmvlu/', 'methods' => 'GET,', ), ), 'walupjl' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/walupjl/q/{name}', 'regex' => '#^/walupjl/q/(?P<name>[^/]+)$#', 'start' => '/walupjl/q/', 'methods' => 'PATCH,', ), ), 'dm' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/dm/qmffruy/{name}', 'regex' => '#^/dm/qmffruy/(?P<name>[^/]+)$#', 'start' => '/dm/qmffruy/', 'methods' => 'GET,', ), ), 'xui' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/xui/dw/{name}', 'regex' => '#^/xui/dw/(?P<name>[^/]+)$#', 'start' => '/xui/dw/', 'methods' => 'GET,', ), ), 'kfyyt' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/kfyyt/{name}', 'regex' => '#^/kfyyt/(?P<name>[^/]+)$#', 'start' => '/kfyyt/', 'methods' => 'GET,', ), ), 'scfmeslgxxb' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/scfmeslgxxb/owr/{name}', 'regex' => '#^/scfmeslgxxb/owr/(?P<name>[^/]+)$#', 'start' => '/scfmeslgxxb/owr/', 'methods' => 'PATCH,', ), ), 'nsxvzlbnncjfishmp' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/nsxvzlbnncjfishmp/h/{name}', 'regex' => '#^/nsxvzlbnncjfishmp/h/(?P<name>[^/]+)$#', 'start' => '/nsxvzlbnncjfishmp/h/', 'methods' => 'GET,', ), ), 'mf' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/mf/axqmwvxkbrvkli/ln/{name}', 'regex' => '#^/mf/axqmwvxkbrvkli/ln/(?P<name>[^/]+)$#', 'start' => '/mf/axqmwvxkbrvkli/', 'methods' => 'GET,', ), ), 'svpdwqhjaa' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/svpdwqhjaa/wzg/{name}', 'regex' => '#^/svpdwqhjaa/wzg/(?P<name>[^/]+)$#', 'start' => '/svpdwqhjaa/wzg/', 'methods' => 'GET,', ), ), 'xyujpqqqlstx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/xyujpqqqlstx/{name}', 'regex' => '#^/xyujpqqqlstx/(?P<name>[^/]+)$#', 'start' => '/xyujpqqqlstx/', 'methods' => 'GET,', ), ), 'ulhuit' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ulhuit/pdurizbcrl/{name}', 'regex' => '#^/ulhuit/pdurizbcrl/(?P<name>[^/]+)$#', 'start' => '/ulhuit/pdurizbcrl/', 'methods' => 'PATCH,', ), ), 'rcegdxju' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/rcegdxju/urfxsxyai/{name}', 'regex' => '#^/rcegdxju/urfxsxyai/(?P<name>[^/]+)$#', 'start' => '/rcegdxju/urfxsxyai/', 'methods' => 'PATCH,', ), ), 'vclyrxxwih' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/vclyrxxwih/{name}', 'regex' => '#^/vclyrxxwih/(?P<name>[^/]+)$#', 'start' => '/vclyrxxwih/', 'methods' => 'GET,', ), ), 'xhvmrudy' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/xhvmrudy/{name}', 'regex' => '#^/xhvmrudy/(?P<name>[^/]+)$#', 'start' => '/xhvmrudy/', 'methods' => 'POST,', ), ), 'opngw' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/opngw/ujsoynfjrunyh/{name}', 'regex' => '#^/opngw/ujsoynfjrunyh/(?P<name>[^/]+)$#', 'start' => '/opngw/ujsoynfjrunyh/', 'methods' => 'PUT,', ), ), 'oswp' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/oswp/jowjjbiw/bo/et/{name}', 'regex' => '#^/oswp/jowjjbiw/bo/et/(?P<name>[^/]+)$#', 'start' => '/oswp/jowjjbiw/', 'methods' => 'PUT,', ), ), 'mpwhqf' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/mpwhqf/zuw/{name}', 'regex' => '#^/mpwhqf/zuw/(?P<name>[^/]+)$#', 'start' => '/mpwhqf/zuw/', 'methods' => 'GET,', ), ), 'akyqaquhpepjz' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/akyqaquhpepjz/{name}', 'regex' => '#^/akyqaquhpepjz/(?P<name>[^/]+)$#', 'start' => '/akyqaquhpepjz/', 'methods' => 'GET,', ), ), 'leveifiugaf' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/leveifiugaf/{name}', 'regex' => '#^/leveifiugaf/(?P<name>[^/]+)$#', 'start' => '/leveifiugaf/', 'methods' => 'GET,', ), ), 'fhdkh' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/fhdkh/{name}', 'regex' => '#^/fhdkh/(?P<name>[^/]+)$#', 'start' => '/fhdkh/', 'methods' => 'POST,', ), ), 'ofle' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ofle/nrxfk/efqswmbqo/of/{name}', 'regex' => '#^/ofle/nrxfk/efqswmbqo/of/(?P<name>[^/]+)$#', 'start' => '/ofle/nrxfk/', 'methods' => 'DELETE,', ), ), 'tcvpwuehqkx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/tcvpwuehqkx/{name}', 'regex' => '#^/tcvpwuehqkx/(?P<name>[^/]+)$#', 'start' => '/tcvpwuehqkx/', 'methods' => 'GET,', ), ), 'ixjluqujuikmddcsiof' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ixjluqujuikmddcsiof/{name}', 'regex' => '#^/ixjluqujuikmddcsiof/(?P<name>[^/]+)$#', 'start' => '/ixjluqujuikmddcsiof/', 'methods' => 'PATCH,', ), ), 'jzc' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/jzc/hycrsfyhv/fcszbp/{name}', 'regex' => '#^/jzc/hycrsfyhv/fcszbp/(?P<name>[^/]+)$#', 'start' => '/jzc/hycrsfyhv/', 'methods' => 'GET,', ), ), 'ppgmwmrb' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ppgmwmrb/zp/{name}', 'regex' => '#^/ppgmwmrb/zp/(?P<name>[^/]+)$#', 'start' => '/ppgmwmrb/zp/', 'methods' => 'POST,', ), ), 'dmlhwuw' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/dmlhwuw/q/{name}', 'regex' => '#^/dmlhwuw/q/(?P<name>[^/]+)$#', 'start' => '/dmlhwuw/q/', 'methods' => 'DELETE,', ), ), 'wcqnqe' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/wcqnqe/sqreg/{name}', 'regex' => '#^/wcqnqe/sqreg/(?P<name>[^/]+)$#', 'start' => '/wcqnqe/sqreg/', 'methods' => 'GET,', ), ), 'fnxt' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/fnxt/heuqnyg/calix/{name}', 'regex' => '#^/fnxt/heuqnyg/calix/(?P<name>[^/]+)$#', 'start' => '/fnxt/heuqnyg/', 'methods' => 'DELETE,', ), ), 'cgnlqop' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/cgnlqop/jqdn/yghefon/{name}', 'regex' => '#^/cgnlqop/jqdn/yghefon/(?P<name>[^/]+)$#', 'start' => '/cgnlqop/jqdn/', 'methods' => 'DELETE,', ), ), 'jlaypbizioycub' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/jlaypbizioycub/{name}', 'regex' => '#^/jlaypbizioycub/(?P<name>[^/]+)$#', 'start' => '/jlaypbizioycub/', 'methods' => 'PUT,', ), ), 'qagrdyuyvmcdlbvmes' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/qagrdyuyvmcdlbvmes/{name}', 'regex' => '#^/qagrdyuyvmcdlbvmes/(?P<name>[^/]+)$#', 'start' => '/qagrdyuyvmcdlbvmes/', 'methods' => 'PATCH,', ), ), 'kqceagbds' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/kqceagbds/{name}', 'regex' => '#^/kqceagbds/(?P<name>[^/]+)$#', 'start' => '/kqceagbds/', 'methods' => 'PUT,', ), ), 'supuczb' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/supuczb/{name}', 'regex' => '#^/supuczb/(?P<name>[^/]+)$#', 'start' => '/supuczb/', 'methods' => 'PATCH,', ), ), 'pf' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/pf/waq/{name}', 'regex' => '#^/pf/waq/(?P<name>[^/]+)$#', 'start' => '/pf/waq/', 'methods' => 'GET,', ), ), 'e' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/e/iqzxmdeb/{name}', 'regex' => '#^/e/iqzxmdeb/(?P<name>[^/]+)$#', 'start' => '/e/iqzxmdeb/', 'methods' => 'PATCH,', ), 1 => array ( 'handler' => 'handler_func', 'original' => '/e/kvterkohu/yhmompc/{name}', 'regex' => '#^/e/kvterkohu/yhmompc/(?P<name>[^/]+)$#', 'start' => '/e/kvterkohu/', 'methods' => 'PUT,', ), ), 'akvrvikkjtqgfxperek' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/akvrvikkjtqgfxperek/{name}', 'regex' => '#^/akvrvikkjtqgfxperek/(?P<name>[^/]+)$#', 'start' => '/akvrvikkjtqgfxperek/', 'methods' => 'POST,', ), ), 'pryww' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/pryww/jzobv/{name}', 'regex' => '#^/pryww/jzobv/(?P<name>[^/]+)$#', 'start' => '/pryww/jzobv/', 'methods' => 'PUT,', ), ), 'ceiulgxolthn' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ceiulgxolthn/mw/{name}', 'regex' => '#^/ceiulgxolthn/mw/(?P<name>[^/]+)$#', 'start' => '/ceiulgxolthn/mw/', 'methods' => 'PATCH,', ), ), 'copasqiiv' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/copasqiiv/{name}', 'regex' => '#^/copasqiiv/(?P<name>[^/]+)$#', 'start' => '/copasqiiv/', 'methods' => 'PUT,', ), ), 'rrfvpr' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/rrfvpr/xpet/dzznvqep/{name}', 'regex' => '#^/rrfvpr/xpet/dzznvqep/(?P<name>[^/]+)$#', 'start' => '/rrfvpr/xpet/', 'methods' => 'DELETE,', ), ), 'zgxgdsvsff' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/zgxgdsvsff/doseyxqfyk/{name}', 'regex' => '#^/zgxgdsvsff/doseyxqfyk/(?P<name>[^/]+)$#', 'start' => '/zgxgdsvsff/doseyxqfyk/', 'methods' => 'DELETE,', ), ), 'xgo' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/xgo/hdnrgyg/dwvywevn/{name}', 'regex' => '#^/xgo/hdnrgyg/dwvywevn/(?P<name>[^/]+)$#', 'start' => '/xgo/hdnrgyg/', 'methods' => 'DELETE,', ), ), 'fsulscbvzl' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/fsulscbvzl/hcs/{name}', 'regex' => '#^/fsulscbvzl/hcs/(?P<name>[^/]+)$#', 'start' => '/fsulscbvzl/hcs/', 'methods' => 'PUT,', ), ), 'bdhfbbjhc' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/bdhfbbjhc/{name}', 'regex' => '#^/bdhfbbjhc/(?P<name>[^/]+)$#', 'start' => '/bdhfbbjhc/', 'methods' => 'GET,', ), ), 'dn' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/dn/fqzk/tblcfpf/{name}', 'regex' => '#^/dn/fqzk/tblcfpf/(?P<name>[^/]+)$#', 'start' => '/dn/fqzk/', 'methods' => 'POST,', ), ), 'ss' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ss/msu/qilk/gygjcggkdii/{name}', 'regex' => '#^/ss/msu/qilk/gygjcggkdii/(?P<name>[^/]+)$#', 'start' => '/ss/msu/', 'methods' => 'PATCH,', ), ), 'vbuj' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/vbuj/muq/la/nmjpx/{name}', 'regex' => '#^/vbuj/muq/la/nmjpx/(?P<name>[^/]+)$#', 'start' => '/vbuj/muq/', 'methods' => 'PUT,', ), ), 'mlebatehdvqi' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/mlebatehdvqi/o/f/{name}', 'regex' => '#^/mlebatehdvqi/o/f/(?P<name>[^/]+)$#', 'start' => '/mlebatehdvqi/o/', 'methods' => 'GET,', ), ), 'krykabeov' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/krykabeov/{name}', 'regex' => '#^/krykabeov/(?P<name>[^/]+)$#', 'start' => '/krykabeov/', 'methods' => 'GET,', ), ), 'dx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/dx/r/inego/{name}', 'regex' => '#^/dx/r/inego/(?P<name>[^/]+)$#', 'start' => '/dx/r/', 'methods' => 'PATCH,', ), ), 'gabfpoh' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/gabfpoh/{name}', 'regex' => '#^/gabfpoh/(?P<name>[^/]+)$#', 'start' => '/gabfpoh/', 'methods' => 'GET,', ), ), 'pskgev' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/pskgev/fhp/j/{name}', 'regex' => '#^/pskgev/fhp/j/(?P<name>[^/]+)$#', 'start' => '/pskgev/fhp/', 'methods' => 'PATCH,', ), ), 'sbyzllbmwjijs' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/sbyzllbmwjijs/{name}', 'regex' => '#^/sbyzllbmwjijs/(?P<name>[^/]+)$#', 'start' => '/sbyzllbmwjijs/', 'methods' => 'PATCH,', ), ), 'ce' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ce/xtweqnufj/{name}', 'regex' => '#^/ce/xtweqnufj/(?P<name>[^/]+)$#', 'start' => '/ce/xtweqnufj/', 'methods' => 'PUT,', ), ), 'aueoy' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/aueoy/{name}', 'regex' => '#^/aueoy/(?P<name>[^/]+)$#', 'start' => '/aueoy/', 'methods' => 'PATCH,', ), ), 'hoqkfq' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/hoqkfq/fljhsavta/{name}', 'regex' => '#^/hoqkfq/fljhsavta/(?P<name>[^/]+)$#', 'start' => '/hoqkfq/fljhsavta/', 'methods' => 'POST,', ), ), 'xs' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/xs/mpexxrx/ughr/ob/{name}', 'regex' => '#^/xs/mpexxrx/ughr/ob/(?P<name>[^/]+)$#', 'start' => '/xs/mpexxrx/', 'methods' => 'POST,', ), ), 'qnmmrhm' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/qnmmrhm/eo/y/{name}', 'regex' => '#^/qnmmrhm/eo/y/(?P<name>[^/]+)$#', 'start' => '/qnmmrhm/eo/', 'methods' => 'GET,', ), ), 'ejbqtrzse' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ejbqtrzse/{name}', 'regex' => '#^/ejbqtrzse/(?P<name>[^/]+)$#', 'start' => '/ejbqtrzse/', 'methods' => 'GET,', ), ), 'sgxaydlwy' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/sgxaydlwy/{name}', 'regex' => '#^/sgxaydlwy/(?P<name>[^/]+)$#', 'start' => '/sgxaydlwy/', 'methods' => 'GET,', ), ), 'mhdit' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/mhdit/at/dryxjgiqo/omv/{name}', 'regex' => '#^/mhdit/at/dryxjgiqo/omv/(?P<name>[^/]+)$#', 'start' => '/mhdit/at/', 'methods' => 'PUT,', ), ), 'jkrwsyhirf' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/jkrwsyhirf/{name}', 'regex' => '#^/jkrwsyhirf/(?P<name>[^/]+)$#', 'start' => '/jkrwsyhirf/', 'methods' => 'PATCH,', ), ), 'gigxmvmgyhgkg' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/gigxmvmgyhgkg/{name}', 'regex' => '#^/gigxmvmgyhgkg/(?P<name>[^/]+)$#', 'start' => '/gigxmvmgyhgkg/', 'methods' => 'DELETE,', ), ), 'zjzz' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/zjzz/j/o/{name}', 'regex' => '#^/zjzz/j/o/(?P<name>[^/]+)$#', 'start' => '/zjzz/j/', 'methods' => 'PUT,', ), ), 'rlwgkmmenaylydr' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/rlwgkmmenaylydr/{name}', 'regex' => '#^/rlwgkmmenaylydr/(?P<name>[^/]+)$#', 'start' => '/rlwgkmmenaylydr/', 'methods' => 'GET,', ), ), 'femsgrazj' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/femsgrazj/{name}', 'regex' => '#^/femsgrazj/(?P<name>[^/]+)$#', 'start' => '/femsgrazj/', 'methods' => 'GET,', ), ), 'vkwbabjnfhyfaubicgj' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/vkwbabjnfhyfaubicgj/{name}', 'regex' => '#^/vkwbabjnfhyfaubicgj/(?P<name>[^/]+)$#', 'start' => '/vkwbabjnfhyfaubicgj/', 'methods' => 'PATCH,', ), ), 'dtdkkazypaqjquhxhowf' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/dtdkkazypaqjquhxhowf/{name}', 'regex' => '#^/dtdkkazypaqjquhxhowf/(?P<name>[^/]+)$#', 'start' => '/dtdkkazypaqjquhxhowf/', 'methods' => 'POST,', ), ), 'vdypmijbggekmw' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/vdypmijbggekmw/{name}', 'regex' => '#^/vdypmijbggekmw/(?P<name>[^/]+)$#', 'start' => '/vdypmijbggekmw/', 'methods' => 'PUT,', ), ), 'jnhpy' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/jnhpy/cbvd/tztsj/{name}', 'regex' => '#^/jnhpy/cbvd/tztsj/(?P<name>[^/]+)$#', 'start' => '/jnhpy/cbvd/', 'methods' => 'PUT,', ), ), 'kwm' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/kwm/hwtlqlqr/{name}', 'regex' => '#^/kwm/hwtlqlqr/(?P<name>[^/]+)$#', 'start' => '/kwm/hwtlqlqr/', 'methods' => 'DELETE,', ), ), 'wkwdxrgygknrfkxend' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/wkwdxrgygknrfkxend/{name}', 'regex' => '#^/wkwdxrgygknrfkxend/(?P<name>[^/]+)$#', 'start' => '/wkwdxrgygknrfkxend/', 'methods' => 'GET,', ), ), 'yqikysm' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/yqikysm/qbdfd/{name}', 'regex' => '#^/yqikysm/qbdfd/(?P<name>[^/]+)$#', 'start' => '/yqikysm/qbdfd/', 'methods' => 'GET,', ), ), 'jlvznqoverhinphtmrf' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/jlvznqoverhinphtmrf/{name}', 'regex' => '#^/jlvznqoverhinphtmrf/(?P<name>[^/]+)$#', 'start' => '/jlvznqoverhinphtmrf/', 'methods' => 'PATCH,', ), ), 'cz' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/cz/vqhqhm/jru/o/{name}', 'regex' => '#^/cz/vqhqhm/jru/o/(?P<name>[^/]+)$#', 'start' => '/cz/vqhqhm/', 'methods' => 'GET,', ), ), 'ixkaszcmsoccxnpj' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ixkaszcmsoccxnpj/{name}', 'regex' => '#^/ixkaszcmsoccxnpj/(?P<name>[^/]+)$#', 'start' => '/ixkaszcmsoccxnpj/', 'methods' => 'POST,', ), ), 'gmrd' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/gmrd/iqsryo/qx/{name}', 'regex' => '#^/gmrd/iqsryo/qx/(?P<name>[^/]+)$#', 'start' => '/gmrd/iqsryo/', 'methods' => 'POST,', ), ), 'jyddq' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/jyddq/p/{name}', 'regex' => '#^/jyddq/p/(?P<name>[^/]+)$#', 'start' => '/jyddq/p/', 'methods' => 'PUT,', ), ), 'lbxhznxiyi' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/lbxhznxiyi/{name}', 'regex' => '#^/lbxhznxiyi/(?P<name>[^/]+)$#', 'start' => '/lbxhznxiyi/', 'methods' => 'PUT,', ), ), 'nhnjho' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/nhnjho/l/{name}', 'regex' => '#^/nhnjho/l/(?P<name>[^/]+)$#', 'start' => '/nhnjho/l/', 'methods' => 'PUT,', ), ), 'oentjnsusknbne' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/oentjnsusknbne/{name}', 'regex' => '#^/oentjnsusknbne/(?P<name>[^/]+)$#', 'start' => '/oentjnsusknbne/', 'methods' => 'GET,', ), ), 'iivxzshh' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/iivxzshh/w/{name}', 'regex' => '#^/iivxzshh/w/(?P<name>[^/]+)$#', 'start' => '/iivxzshh/w/', 'methods' => 'POST,', ), ), 'prxjoqjtlck' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/prxjoqjtlck/{name}', 'regex' => '#^/prxjoqjtlck/(?P<name>[^/]+)$#', 'start' => '/prxjoqjtlck/', 'methods' => 'PUT,', ), ), 'dkzibp' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/dkzibp/bydgbylorggaj/{name}', 'regex' => '#^/dkzibp/bydgbylorggaj/(?P<name>[^/]+)$#', 'start' => '/dkzibp/bydgbylorggaj/', 'methods' => 'POST,', ), ), 'gdybyg' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/gdybyg/oo/h/ra/ufw/{name}', 'regex' => '#^/gdybyg/oo/h/ra/ufw/(?P<name>[^/]+)$#', 'start' => '/gdybyg/oo/', 'methods' => 'PUT,', ), ), 'brxzyjtironwl' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/brxzyjtironwl/car/{name}', 'regex' => '#^/brxzyjtironwl/car/(?P<name>[^/]+)$#', 'start' => '/brxzyjtironwl/car/', 'methods' => 'PUT,', ), ), 'grslgtegwx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/grslgtegwx/{name}', 'regex' => '#^/grslgtegwx/(?P<name>[^/]+)$#', 'start' => '/grslgtegwx/', 'methods' => 'GET,', ), ), 'zxvvyq' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/zxvvyq/{name}', 'regex' => '#^/zxvvyq/(?P<name>[^/]+)$#', 'start' => '/zxvvyq/', 'methods' => 'PATCH,', ), ), 'qz' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/qz/wjfn/{name}', 'regex' => '#^/qz/wjfn/(?P<name>[^/]+)$#', 'start' => '/qz/wjfn/', 'methods' => 'GET,', ), ), 'ini' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ini/cpam/aikwj/{name}', 'regex' => '#^/ini/cpam/aikwj/(?P<name>[^/]+)$#', 'start' => '/ini/cpam/', 'methods' => 'DELETE,', ), ), 'jew' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/jew/om/{name}', 'regex' => '#^/jew/om/(?P<name>[^/]+)$#', 'start' => '/jew/om/', 'methods' => 'GET,', ), ), 'trjzgykmo' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/trjzgykmo/yeyug/m/qaqjm/{name}', 'regex' => '#^/trjzgykmo/yeyug/m/qaqjm/(?P<name>[^/]+)$#', 'start' => '/trjzgykmo/yeyug/', 'methods' => 'GET,', ), ), 'dra' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/dra/auuxfxujompqs/{name}', 'regex' => '#^/dra/auuxfxujompqs/(?P<name>[^/]+)$#', 'start' => '/dra/auuxfxujompqs/', 'methods' => 'GET,', ), ), 'xnutu' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/xnutu/yd/{name}', 'regex' => '#^/xnutu/yd/(?P<name>[^/]+)$#', 'start' => '/xnutu/yd/', 'methods' => 'GET,', ), ), 'adx' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/adx/zydn/{name}', 'regex' => '#^/adx/zydn/(?P<name>[^/]+)$#', 'start' => '/adx/zydn/', 'methods' => 'POST,', ), ), 'qszm' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/qszm/l/ut/{name}', 'regex' => '#^/qszm/l/ut/(?P<name>[^/]+)$#', 'start' => '/qszm/l/', 'methods' => 'DELETE,', ), ), 'npqxp' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/npqxp/{name}', 'regex' => '#^/npqxp/(?P<name>[^/]+)$#', 'start' => '/npqxp/', 'methods' => 'POST,', ), ), 'ilssz' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ilssz/lop/{name}', 'regex' => '#^/ilssz/lop/(?P<name>[^/]+)$#', 'start' => '/ilssz/lop/', 'methods' => 'GET,', ), ), 'tfkg' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/tfkg/w/{name}', 'regex' => '#^/tfkg/w/(?P<name>[^/]+)$#', 'start' => '/tfkg/w/', 'methods' => 'GET,', ), ), 'p' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/p/bnsenoofzjwlongmcpz/{name}', 'regex' => '#^/p/bnsenoofzjwlongmcpz/(?P<name>[^/]+)$#', 'start' => '/p/bnsenoofzjwlongmcpz/', 'methods' => 'GET,', ), ), 'tn' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/tn/lgyaojcpqi/{name}', 'regex' => '#^/tn/lgyaojcpqi/(?P<name>[^/]+)$#', 'start' => '/tn/lgyaojcpqi/', 'methods' => 'PATCH,', ), ), 'prkpfywsdn' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/prkpfywsdn/sgufzpf/mwh/{name}', 'regex' => '#^/prkpfywsdn/sgufzpf/mwh/(?P<name>[^/]+)$#', 'start' => '/prkpfywsdn/sgufzpf/', 'methods' => 'GET,', ), ), 'gh' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/gh/k/vkxifnye/{name}', 'regex' => '#^/gh/k/vkxifnye/(?P<name>[^/]+)$#', 'start' => '/gh/k/', 'methods' => 'GET,', ), ), 'vixorz' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/vixorz/{name}', 'regex' => '#^/vixorz/(?P<name>[^/]+)$#', 'start' => '/vixorz/', 'methods' => 'GET,', ), ), 'ciatfrhgtxzg' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ciatfrhgtxzg/{name}', 'regex' => '#^/ciatfrhgtxzg/(?P<name>[^/]+)$#', 'start' => '/ciatfrhgtxzg/', 'methods' => 'DELETE,', ), ), 'hrdazzhjpf' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/hrdazzhjpf/{name}', 'regex' => '#^/hrdazzhjpf/(?P<name>[^/]+)$#', 'start' => '/hrdazzhjpf/', 'methods' => 'POST,', ), ), 'vpcza' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/vpcza/{name}', 'regex' => '#^/vpcza/(?P<name>[^/]+)$#', 'start' => '/vpcza/', 'methods' => 'GET,', ), ), 'oo' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/oo/mmz/hj/sloqcon/{name}', 'regex' => '#^/oo/mmz/hj/sloqcon/(?P<name>[^/]+)$#', 'start' => '/oo/mmz/', 'methods' => 'GET,', ), ), 'ptxxps' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ptxxps/b/yhrq/m/{name}', 'regex' => '#^/ptxxps/b/yhrq/m/(?P<name>[^/]+)$#', 'start' => '/ptxxps/b/', 'methods' => 'PATCH,', ), ), 'ppvglcz' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ppvglcz/{name}', 'regex' => '#^/ppvglcz/(?P<name>[^/]+)$#', 'start' => '/ppvglcz/', 'methods' => 'GET,', ), ), 'zffhh' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/zffhh/{name}', 'regex' => '#^/zffhh/(?P<name>[^/]+)$#', 'start' => '/zffhh/', 'methods' => 'GET,', ), ), 'bdj' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/bdj/psujbuayngwirzvfk/{name}', 'regex' => '#^/bdj/psujbuayngwirzvfk/(?P<name>[^/]+)$#', 'start' => '/bdj/psujbuayngwirzvfk/', 'methods' => 'GET,', ), ), 'wernq' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/wernq/{name}', 'regex' => '#^/wernq/(?P<name>[^/]+)$#', 'start' => '/wernq/', 'methods' => 'GET,', ), ), 'bdkrfdiwcenxmfwopn' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/bdkrfdiwcenxmfwopn/{name}', 'regex' => '#^/bdkrfdiwcenxmfwopn/(?P<name>[^/]+)$#', 'start' => '/bdkrfdiwcenxmfwopn/', 'methods' => 'DELETE,', ), ), 'btj' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/btj/bjm/{name}', 'regex' => '#^/btj/bjm/(?P<name>[^/]+)$#', 'start' => '/btj/bjm/', 'methods' => 'GET,', ), ), 'alj' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/alj/o/u/{name}', 'regex' => '#^/alj/o/u/(?P<name>[^/]+)$#', 'start' => '/alj/o/', 'methods' => 'POST,', ), ), 'gof' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/gof/kwf/xkb/{name}', 'regex' => '#^/gof/kwf/xkb/(?P<name>[^/]+)$#', 'start' => '/gof/kwf/', 'methods' => 'PATCH,', ), ), 'odwc' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/odwc/pzqvgbs/jyxadwi/{name}', 'regex' => '#^/odwc/pzqvgbs/jyxadwi/(?P<name>[^/]+)$#', 'start' => '/odwc/pzqvgbs/', 'methods' => 'PATCH,', ), ), 'plqhchuhicrvqyf' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/plqhchuhicrvqyf/{name}', 'regex' => '#^/plqhchuhicrvqyf/(?P<name>[^/]+)$#', 'start' => '/plqhchuhicrvqyf/', 'methods' => 'PUT,', ), ), 'tbelxgtzti' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/tbelxgtzti/{name}', 'regex' => '#^/tbelxgtzti/(?P<name>[^/]+)$#', 'start' => '/tbelxgtzti/', 'methods' => 'GET,', ), ), 'nnwcskvpeehbmip' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/nnwcskvpeehbmip/uj/{name}', 'regex' => '#^/nnwcskvpeehbmip/uj/(?P<name>[^/]+)$#', 'start' => '/nnwcskvpeehbmip/uj/', 'methods' => 'DELETE,', ), ), 'txtyps' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/txtyps/fvk/arjdoenklsj/{name}', 'regex' => '#^/txtyps/fvk/arjdoenklsj/(?P<name>[^/]+)$#', 'start' => '/txtyps/fvk/', 'methods' => 'GET,', ), ), 'mqw' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/mqw/kty/lc/ywxm/ibvq/{name}', 'regex' => '#^/mqw/kty/lc/ywxm/ibvq/(?P<name>[^/]+)$#', 'start' => '/mqw/kty/', 'methods' => 'PATCH,', ), ), 'ulccly' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ulccly/{name}', 'regex' => '#^/ulccly/(?P<name>[^/]+)$#', 'start' => '/ulccly/', 'methods' => 'PUT,', ), ), 'sjtaxqbo' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/sjtaxqbo/{name}', 'regex' => '#^/sjtaxqbo/(?P<name>[^/]+)$#', 'start' => '/sjtaxqbo/', 'methods' => 'DELETE,', ), ), 'oiatg' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/oiatg/nfu/bhokkud/bwc/j/w/{name}', 'regex' => '#^/oiatg/nfu/bhokkud/bwc/j/w/(?P<name>[^/]+)$#', 'start' => '/oiatg/nfu/', 'methods' => 'PUT,', ), ), 'ne' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ne/cyafl/u/meunfyst/{name}', 'regex' => '#^/ne/cyafl/u/meunfyst/(?P<name>[^/]+)$#', 'start' => '/ne/cyafl/', 'methods' => 'GET,', ), ), 'dbd' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/dbd/gw/{name}', 'regex' => '#^/dbd/gw/(?P<name>[^/]+)$#', 'start' => '/dbd/gw/', 'methods' => 'POST,', ), ), 'ojpal' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/ojpal/{name}', 'regex' => '#^/ojpal/(?P<name>[^/]+)$#', 'start' => '/ojpal/', 'methods' => 'PATCH,', ), ), 'xhpusm' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/xhpusm/{name}', 'regex' => '#^/xhpusm/(?P<name>[^/]+)$#', 'start' => '/xhpusm/', 'methods' => 'POST,', ), ), 'wndjwmm' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/wndjwmm/y/n/tmgast/{name}', 'regex' => '#^/wndjwmm/y/n/tmgast/(?P<name>[^/]+)$#', 'start' => '/wndjwmm/y/', 'methods' => 'PATCH,', ), ), 'dntf' => array ( 0 => array ( 'handler' => 'handler_func', 'original' => '/dntf/hnpnvwqfyidjw/{name}', 'regex' => '#^/dntf/hnpnvwqfyidjw/(?P<name>[^/]+)$#', 'start' => '/dntf/hnpnvwqfyidjw/', 'methods' => 'GET,', ), ), ), // vague routes 'vagueRoutes' => array ( ), );
779c7eba171e469336d49070b77f42300aa0930e
[ "Markdown", "PHP" ]
4
PHP
dulumao/php-srouter
39cebc44e40cc2fa71d28029e440056ee24d04a5
7fe29c54d8c9a2029594a45e1eb63c41f45931f5
refs/heads/main
<repo_name>joaquinFarall/alkemy-nodejs-challenge<file_sep>/src/routes/authentication.js const express = require('express'); const router = express.Router(); const pool = require('../database'); // function to validate the email adress function validateEmail(email) { const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } // GET routes router.get('/signup', (req, res) => { if(req.session.loggedin) return res.redirect('/home'); res.render('signup'); }); router.get('/login', (req, res) => { if(req.session.loggedin) return res.redirect('/home'); res.render('login'); }); router.get('/logout', (req, res) => { if(!req.session.loggedin) return res.redirect('/'); req.session.user = null; req.session.loggedin = false; req.flash('success_msg', 'Successfully logged out'); res.redirect('/'); }); // POST routes router.post('/signup', async (req, res) => { let {fullname, email, password, <PASSWORD>} = req.body; // validate email if(!validateEmail(email)){ req.flash('error_msg', 'Invalid email. Try again'); return res.redirect('/signup'); } let emailCheck = await pool.query('SELECT * FROM users WHERE email = ?', [email]); if(emailCheck.length > 0){ req.flash('error_msg', 'The selected email is already in use'); return res.redirect('/signup'); } // check if passwords match if(password != <PASSWORD>){ req.flash('error_msg', 'Passwords do not match. Try again'); return res.redirect('/signup'); } let newUser = { email, password, fullname, balance: 0 }; let query = 'INSERT INTO users SET ?'; await pool.query(query, [newUser]); req.flash('success_msg', 'User created successfully') res.redirect('/login'); }); router.post('/login', async (req, res) => { let {email, password} = req.body; let query = 'SELECT * FROM users WHERE email = ? AND password = ?'; let user = await pool.query(query, [email, password]); if(user.length > 0){ req.session.loggedin = true; req.session.user = user[0]; res.redirect('/home'); }else{ req.flash('error_msg', 'Incorrect email or password. Try again'); res.redirect('/login'); } }); module.exports = router;<file_sep>/database.sql CREATE DATABASE alkemy_challenge_db; USE alkemy_challenge_db; CREATE TABLE users( id INT(11) NOT NULL AUTO_INCREMENT, email VARCHAR(150) NOT NULL UNIQUE, password VARCHAR(60) NOT NULL, fullname VARCHAR(100) NOT NULL, balance INT(11) NOT NULL, PRIMARY KEY(id) ); CREATE TABLE transactions( id INT(11) NOT NULL AUTO_INCREMENT, amount INT(11) NOT NULL, type VARCHAR(10) NOT NULL, category VARCHAR(50) NOT NULL, user_id INT(11) NOT NULL, date DATE NOT NULL, CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id), PRIMARY KEY(id) ); <file_sep>/src/app.js const express = require('express'); const ejs = require('ejs'); const path = require('path'); const flash = require('connect-flash'); const session = require('express-session'); const MySQLStore = require('express-mysql-session'); const { database } = require('./connection'); // initializations const app = express(); // settings app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); // middlewares app.use(express.urlencoded({ extended: false })); app.use(express.json()); app.use(session({ secret: 'alkemyChallenge', resave: false, saveUninitialized: false, store: new MySQLStore(database) })); app.use(flash()); // global variables app.use((req, res, next) => { app.locals.success_msg = req.flash('success_msg'); app.locals.error_msg = req.flash('error_msg'); next(); }); // public app.use(express.static(path.join(__dirname, 'public'))); // routes app.use(require('./routes/index')); app.use(require('./routes/authentication')); app.use(require('./routes/transactions')); // server app.listen(app.get('port'), () => { console.log('server started on port ' + app.get('port')); });<file_sep>/src/database.js const mysql = require('mysql'); const {promisify} = require('util'); const {database} = require('./connection'); const pool = mysql.createPool(database); pool.getConnection((err, connection) => { if(err) return console.log(err); if(connection) connection.release(); console.log('DB is connected'); return; }); pool.query = promisify(pool.query); module.exports = pool;<file_sep>/README.md # Alkemy's acceleration Node.js challenge ## By: <NAME> ### To use: configure connection.js file with your own settings for MySQL <file_sep>/src/routes/transactions.js const express = require('express'); const router = express.Router(); const pool = require('../database'); // function to format the dates from the db as yyyy-mm-dd function formatDate(date) { year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); if (day < 10) { day = '0' + day; } if (month < 10) { month = '0' + month; } return year + '-' + month + '-' + day; } // function to validate date's input function isValidDate(dateString) { var regEx = /^\d{4}-\d{2}-\d{2}$/; if (!dateString.match(regEx)) return false; // Invalid format var d = new Date(dateString); var dNum = d.getTime(); if (!dNum && dNum !== 0) return false; // NaN value, Invalid date return d.toISOString().slice(0, 10) === dateString; } // GET routes router.get('/home', async (req, res) => { if (!req.session.loggedin) { req.flash('error_msg', 'Log in to access this page'); return res.redirect('/login'); } let user = req.session.user; let query = 'SELECT * FROM transactions WHERE user_id = ? ORDER BY id DESC limit 10'; let transactions = await pool.query(query, [user.id]); // format date to display transactions.forEach((transaction) => { transaction.date = formatDate(transaction.date); }); res.render('home', { transactions, user }); }); router.get('/transactions/new', (req, res) => { if (!req.session.loggedin) { req.flash('error_msg', 'Log in to access this page'); return res.redirect('/login'); } res.render('new-transaction'); }); router.get('/transactions', async (req, res) => { if (!req.session.loggedin) { req.flash('error_msg', 'Log in to access this page'); return res.redirect('/login'); } let user = req.session.user; let h1 = 'TRANSACTIONS'; let query = 'SELECT * FROM transactions WHERE user_id = ? ORDER BY date DESC'; let transactions = await pool.query(query, [user.id]); // format date to display transactions.forEach((transaction) => { transaction.date = formatDate(transaction.date); }) res.render('transactions', { h1, transactions }); }); router.get('/transactions/deposits', async (req, res) => { if (!req.session.loggedin) { req.flash('error_msg', 'Log in to access this page'); return res.redirect('/login'); } let user = req.session.user; let h1 = 'DEPOSITS'; let query = 'SELECT * FROM transactions WHERE user_id = ? AND type = "deposit" ORDER BY date DESC'; let transactions = await pool.query(query, [user.id]); // format date to display transactions.forEach((transaction) => { transaction.date = formatDate(transaction.date); }) res.render('transactions', { h1, transactions }); }); router.get('/transactions/extractions', async (req, res) => { if (!req.session.loggedin) { req.flash('error_msg', 'Log in to access this page'); return res.redirect('/login'); } let user = req.session.user; let h1 = 'EXTRACTIONS'; let query = 'SELECT * FROM transactions WHERE user_id = ? AND type = "extraction" ORDER BY date DESC'; let transactions = await pool.query(query, [user.id]); // format date to display transactions.forEach((transaction) => { transaction.date = formatDate(transaction.date); }) res.render('transactions', { h1, transactions }); }); router.get('/transactions/:category', async (req, res) => { if (!req.session.loggedin) { req.flash('error_msg', 'Log in to access this page'); return res.redirect('/login'); } let { category } = req.params; let h1 = category.toUpperCase(); let user = req.session.user; let query = 'SELECT * FROM transactions WHERE user_id = ? AND category = ? ORDER BY date DESC'; let transactions = await pool.query(query, [user.id, category]); // format date to display transactions.forEach((transaction) => { transaction.date = formatDate(transaction.date); }) res.render('transactions', { h1, transactions }); }); router.get('/transactions/edit/:id', async (req, res) => { if (!req.session.loggedin) { req.flash('error_msg', 'Log in to access this page'); return res.redirect('/login'); } let { id } = req.params; let query = 'SELECT * FROM transactions WHERE id = ?' let transaction = await pool.query(query, [id]); // format date to display transaction[0].date = formatDate(transaction[0].date); res.render('edit-transaction', { transaction: transaction[0] }); }); router.get('/transactions/delete/:id', async (req, res) => { if (!req.session.loggedin) { req.flash('error_msg', 'Log in to access this page'); return res.redirect('/login'); } let { id } = req.params; let user = req.session.user; // update user's balance with the deleted transaction's amount let oldTransaction = await pool.query('SELECT * FROM transactions WHERE id = ?', [id]); let balance = parseFloat(user.balance); if (oldTransaction[0].type == 'deposit') { balance = balance - parseFloat(oldTransaction[0].amount); } else if (oldTransaction[0].type == 'extraction') { balance = balance + parseFloat(oldTransaction[0].amount); } req.session.user.balance = balance; await pool.query('UPDATE users SET balance = ' + balance + ' WHERE id = ?', [user.id]); // delete transaction let query = 'DELETE FROM transactions WHERE id = ?'; await pool.query(query, [id]); req.flash('success_msg', 'Transaction deleted successfully'); res.redirect('/transactions'); }); router.get('*', (req, res) => { res.render('notfound', { session: req.session }); }); // POST routes router.post('/transactions/new', async (req, res) => { if (!req.session.loggedin) { req.flash('error_msg', 'Log in to access this page'); return res.redirect('/login'); } let { amount, concept, type, category, date } = req.body; let user = req.session.user; // validate amount if (amount < 1) { req.flash('error_msg', 'Please insert a valid amount'); return res.redirect('/transactions/new'); } // validate category if (category == "null") { req.flash('error_msg', "Please select the transaction's category"); return res.redirect('/transactions/new'); } // validate date if (!isValidDate(date)) { req.flash('error_msg', 'Please insert a valid date'); return res.redirect('/transactions/new'); } let balance = 0; if (type == 'deposit') { balance = parseFloat(user.balance) + parseFloat(amount); } else if (type == 'extraction') { balance = parseFloat(user.balance) - parseFloat(amount); } else { // if type isn't deposit or amount it's invalid req.flash('error_msg', "Please select the transaction's type"); return res.redirect('/transactions/new'); } // update balance of the user in the session and in the db req.session.user.balance = balance; let query = 'UPDATE users SET balance = ' + balance + ' WHERE id = ?'; await pool.query(query, [user.id]); newTransaction = { concept, amount, type, category, user_id: user.id, date }; query = 'INSERT INTO transactions SET ?'; await pool.query(query, [newTransaction]); req.flash('success_msg', 'Transaction completed successfully'); res.redirect('/transactions/new'); }); router.post('/transactions/edit/:id', async (req, res) => { if (!req.session.loggedin) { req.flash('error_msg', 'Log in to access this page'); return res.redirect('/login'); } let { amount, concept, category, date } = req.body; let { id } = req.params; // validate amount if (amount < 1) { req.flash('error_msg', 'Please insert a valid amount'); return res.redirect('/transactions/edit/' + id); } // validate date if (!isValidDate(date)) { req.flash('error_msg', 'Please insert a valid date'); return res.redirect('/transactions/edit/' + id); } let user = req.session.user; // update user's balance with the new transaction's amount let oldTransaction = await pool.query('SELECT * FROM transactions WHERE id = ?', [id]); let balance = parseFloat(user.balance); if (oldTransaction[0].type == 'deposit') { let diff = parseFloat(oldTransaction[0].amount) - parseFloat(amount); balance = balance - diff; } else if (oldTransaction[0].type == 'extraction') { let diff = parseFloat(oldTransaction[0].amount) - parseFloat(amount); balance = balance + diff; } req.session.user.balance = balance; await pool.query('UPDATE users SET balance = ' + balance + ' WHERE id = ?', [user.id]); // update transaction let query = 'UPDATE transactions SET concept = ?, amount = ?, category = ?, date = ? WHERE id = ?'; await pool.query(query, [concept, amount, category, date, id]); req.flash('success_msg', 'Transaction edited successfully'); res.redirect('/transactions'); }); module.exports = router;
91af17f4af86f20d2252e2b927f5d55a39623f17
[ "JavaScript", "SQL", "Markdown" ]
6
JavaScript
joaquinFarall/alkemy-nodejs-challenge
e10e7c196a3dae3848a0f150e987c24465db42ca
3759243e21f092af431e5ff8661e7f8058945207
refs/heads/master
<file_sep>package ch.brotzilla.neat.math; public class ExtendedTanhFunction extends ExtendedActivationFunction { public ExtendedTanhFunction() { super("neat.math.extended.tanh", "Hyperbolic Tangent", "Returns the hyperbolic tangent of the argument."); setSynapseDefault(0, 2.5); } @Override protected double _compute(double activation, double[] synapses) { return 2.0d / (1.0d + Math.exp(-2.0d * activation)) - 1.0d; } } <file_sep>package ch.brotzilla.neat.genome; import gnu.trove.impl.unmodifiable.TUnmodifiableIntSet; import gnu.trove.iterator.TIntIterator; import gnu.trove.set.TIntSet; import gnu.trove.set.hash.TIntHashSet; import java.util.Arrays; import java.util.Iterator; import ch.brotzilla.neat.Debug; import ch.brotzilla.neat.math.ActivationFunction; import com.google.common.base.Preconditions; public class Node implements Iterable<Integer> { private final NodeType type; private final int innovationNumber; private ActivationFunction activationFunction; private double[] synapseDefaults; private final TIntSet links, linksWrapper; void add(Link link) { Preconditions.checkState(type.isTargetNode(), type + " nodes do not support links"); Preconditions.checkNotNull(link, "The parameter 'link' must not be null"); Preconditions.checkArgument(link.getTargetNode() == innovationNumber, "The target node of the parameter 'link' has to be equal to " + innovationNumber); if (Debug.EnableIntegrityChecks) { Preconditions.checkState(!links.contains(link.getInnovationNumber()), "This node already contains a link with with the innovation number " + link.getInnovationNumber()); } links.add(link.getInnovationNumber()); } void remove(Link link) { Preconditions.checkState(type.isTargetNode(), type + " nodes do not support links"); Preconditions.checkNotNull(link, "The parameter 'link' must not be null"); Preconditions.checkArgument(link.getTargetNode() == innovationNumber, "The target node of the parameter 'link' has to be equal to " + innovationNumber); final boolean removed = links.remove(link.getInnovationNumber()); Preconditions.checkArgument(removed, "The parameter 'link' is not part of this node"); } public Node(NodeType type, int innovationNumber, ActivationFunction activationFunction, double[] synapseDefaults) { Preconditions.checkNotNull(type, "The parameter 'type' must not be null"); Preconditions.checkArgument(innovationNumber > 0, "The parameter 'innovationNumber' has to be greater than zero"); this.type = type; this.innovationNumber = innovationNumber; if (type.isInputNode()) { Preconditions.checkArgument(activationFunction == null, "The parameter 'activationFunction' has to be null for input nodes"); Preconditions.checkArgument(synapseDefaults == null, "The parameter 'synapseDefaults' has to be null for input nodes"); this.activationFunction = null; this.synapseDefaults = null; } else { Preconditions.checkNotNull(activationFunction, "The parameter 'activationFunction' must not be null"); this.activationFunction = activationFunction; if (activationFunction.getNumberOfSynapses() > 0) { if (synapseDefaults == null) { this.synapseDefaults = activationFunction.copySynapseDefaults(); } else { Preconditions.checkArgument(synapseDefaults.length == activationFunction.getNumberOfSynapses(), "The length of the parameter 'synapseDefaults' has to be equal to " + activationFunction.getNumberOfSynapses()); this.synapseDefaults = Arrays.copyOf(synapseDefaults, synapseDefaults.length); } } else { Preconditions.checkArgument(synapseDefaults == null, "The parameter 'synapseDefaults' has to be null"); this.synapseDefaults = null; } } links = new TIntHashSet(); linksWrapper = new TUnmodifiableIntSet(links); } public Node(NodeType type, int innovationNumber, ActivationFunction activationFunction) { this(type, innovationNumber, activationFunction, null); } public Node(NodeType type, int innovationNumber) { this(type, innovationNumber, null, null); } public Node(Node source) { Preconditions.checkNotNull(source, "The parameter 'source' must not be null"); type = source.type; innovationNumber = source.innovationNumber; activationFunction = source.activationFunction; synapseDefaults = (source.synapseDefaults == null ? null : Arrays.copyOf(source.synapseDefaults, source.synapseDefaults.length)); links = new TIntHashSet(source.links); linksWrapper = new TUnmodifiableIntSet(links); } public NodeType getType() { return type; } public int getInnovationNumber() { return innovationNumber; } public ActivationFunction getActivationFunction() { return activationFunction; } public void setActivationFunction(ActivationFunction activationFunction, double[] synapseDefaults) { if (type.isInputNode()) { throw new UnsupportedOperationException("Input nodes cannot have activation functions"); } Preconditions.checkNotNull(activationFunction, "The parameter 'activationFunction' must not be null"); this.activationFunction = activationFunction; if (activationFunction.getNumberOfSynapses() > 0) { if (synapseDefaults == null) { this.synapseDefaults = activationFunction.copySynapseDefaults(); } else { Preconditions.checkArgument(synapseDefaults.length == activationFunction.getNumberOfSynapses(), "The length of the parameter 'synapseDefaults' has to be equal to " + activationFunction.getNumberOfSynapses()); this.synapseDefaults = Arrays.copyOf(synapseDefaults, synapseDefaults.length); } } else { Preconditions.checkArgument(synapseDefaults == null, "The parameter 'synapseDefaults' has to be null"); this.synapseDefaults = null; } } public double[] copySynapseDefaults() { if (type.isInputNode()) { return null; } return Arrays.copyOf(synapseDefaults, synapseDefaults.length); } public double[] getSynapseDefaults() { return synapseDefaults; } public TIntSet getLinks() { return linksWrapper; } public int getNumberOfLinks() { return links.size(); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other instanceof Node) { final Node node = (Node) other; return type == node.type && innovationNumber == node.innovationNumber && activationFunction == node.activationFunction && Arrays.equals(synapseDefaults, node.synapseDefaults) && links.equals(node.links); } return false; } @Override public Node clone() { return new Node(this); } public Iterator<Integer> iterator() { return new LinkIterator(links.iterator()); } private static class LinkIterator implements Iterator<Integer> { private final TIntIterator it; public LinkIterator(TIntIterator it) { Preconditions.checkNotNull(it, "The parameter 'it' must not be null"); this.it = it; } public boolean hasNext() { return it.hasNext(); } public Integer next() { return it.next(); } public void remove() { throw new UnsupportedOperationException(); } } } <file_sep>package ch.brotzilla.neat.math; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.util.List; import com.google.common.base.Preconditions; import ch.brotzilla.neat.math.ActivationFunctionDisplay.FunctionEntry; public class ActivationFunctionRenderer { private static final BasicStroke Stroke1 = new BasicStroke(1), Stroke2 = new BasicStroke(2); private final Screen screen; private BufferedImage buffer; private Graphics2D g; private static class Screen { private int border, x, y, width, height, gridWidth, gridHeight; private boolean render; private double sectionX, sectionY, sectionSize, stepX; public Screen(int border, int width, int height, double beginX, double beginY, double sectionSize) { Preconditions.checkArgument(border >= 0, "The parameter 'border' has to be greater than or equal to zero"); Preconditions.checkArgument(width >= 0, "The parameter 'width' has to be greater than or equal to zero"); Preconditions.checkArgument(height >= 0, "The parameter 'height' has to be greater than or equal to zero"); Preconditions.checkArgument(sectionSize > 0.0, "The parameter 'sectionSize' has to be greater than zero"); this.border = border; x = border; y = border; this.width = width; this.height = height; gridWidth = Math.max(0, width - 2 * border); gridHeight = Math.max(0, height - 2 * border); render = (gridWidth >= 20) && (gridHeight >= 20); this.sectionX = beginX; this.sectionY = beginY; this.sectionSize = sectionSize; if (render) { stepX = 1.0d / gridWidth; } } public void setBorder(int value) { Preconditions.checkArgument(value >= 0, "The parameter 'value' has to be greater than or equal to zero"); border = value; x = border; y = border; gridWidth = Math.max(0, width - 2 * border); gridHeight = Math.max(0, height - 2 * border); render = (gridWidth >= 20) && (gridHeight >= 20); if (render) { stepX = 1.0d / gridWidth; } } public void setSize(int width, int height) { Preconditions.checkArgument(width >= 0, "The parameter 'width' has to be greater than or equal to zero"); Preconditions.checkArgument(height >= 0, "The parameter 'height' has to be greater than or equal to zero"); this.width = width; this.height = height; gridWidth = Math.max(0, width - 2 * border); gridHeight = Math.max(0, height - 2 * border); render = (gridWidth >= 20) && (gridHeight >= 20); if (render) { stepX = 1.0d / gridWidth; } } public int tx(double v) { return x + (int) Math.round(gridWidth * (v - sectionX) / sectionSize); } public int ty(double v) { return y + (int) Math.round(gridHeight * (v - sectionY) / sectionSize); } } private void renderLine(double x1, double y1, double x2, double y2) { g.drawLine(screen.tx(x1), screen.ty(y1), screen.tx(x2), screen.ty(y2)); } private void clearScreen() { g.setBackground(Color.white); g.clearRect(0, 0, screen.width, screen.height); } private double trunc(double v, double stepSize) { double tmp = v * (1.0 / stepSize); if (tmp > 0) { return Math.floor(tmp) * stepSize; } if (tmp < 0) { return Math.ceil(tmp) * stepSize; } return tmp; } private void renderGrid(Color color, double stepSize) { g.setStroke(Stroke1); g.setColor(color); final int steps = (int) Math.round(screen.sectionSize / stepSize) + 1; final double beginX = trunc(screen.sectionX, stepSize); for (int i = 0; i < steps; i++) { final double x = beginX + (stepSize * i); if (x < screen.sectionX) continue; if (x > screen.sectionX + screen.sectionSize) break; renderLine(x, screen.sectionY, x, screen.sectionY + screen.sectionSize); } final double beginY = trunc(screen.sectionY, stepSize); for (int i = 0; i < steps; i++) { final double y = beginY + (stepSize * i); if (y < screen.sectionY) continue; if (y > screen.sectionY + screen.sectionSize) break; renderLine(screen.sectionX, y, screen.sectionX + screen.sectionSize, y); } } private void renderFunctions(List<FunctionEntry> functions) { g.setStroke(Stroke2); g.setClip(screen.x, screen.y, screen.gridWidth, screen.gridHeight); for (final FunctionEntry entry : functions) { if (!entry.getActive()) { continue; } final ActivationFunctionWrapper f = entry.getActivationFunction(); double x = screen.sectionX + screen.stepX, xprev = screen.sectionX, yprev = -f.compute(screen.sectionX); g.setColor(entry.getColor()); while (x < screen.sectionX + screen.sectionSize) { final double y = -f.compute(x); renderLine(xprev, yprev, x, y); xprev = x; yprev = y; x += screen.stepX; } } g.setClip(0, 0, screen.width, screen.height); } public ActivationFunctionRenderer() { screen = new Screen(30, 0, 0, -1.1, -1.1, 2.2); } public boolean isReady() { return buffer != null; } public BufferedImage getBuffer() { return buffer; } public int getBorder() { return screen.border; } public void setBorder(int value) { screen.setBorder(value); } public int getWidth() { return screen.width; } public int getHeight() { return screen.height; } public void setSize(int width, int height) { if (width == 0 || height == 0) { screen.setSize(0, 0); buffer = null; g = null; } else if (buffer == null || buffer.getWidth() != width || buffer.getHeight() != height) { screen.setSize(width, height); buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); g = (Graphics2D) buffer.getGraphics(); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } } public int getGridWidth() { return screen.gridWidth; } public int getGridHeight() { return screen.gridHeight; } public double getSectionPosX() { return screen.sectionX; } public double getSectionPosY() { return screen.sectionY; } public void setSectionPos(double x, double y) { screen.sectionX = x; screen.sectionY = y; } public void addSectionPosDelta(double dx, double dy) { setSectionPos(screen.sectionX + dx, screen.sectionY + dy); } public void addSectionPosDelta(double delta) { setSectionPos(screen.sectionX + delta, screen.sectionY + delta); } public double getSectionSize() { return screen.sectionSize; } public void setSectionSize(double value) { value = Math.max(0.1, value); screen.sectionSize = value; } public void addSectionSizeDelta(double delta) { setSectionSize(screen.sectionSize + delta); } public void addZoomDelta(double delta) { addSectionPosDelta(-delta / 4); addSectionSizeDelta(delta / 2); } public void resetSection() { screen.sectionX = -1.0; screen.sectionY = -1.0; screen.sectionSize = 2.0; } public void render(List<FunctionEntry> functions) { Preconditions.checkState(buffer != null, "The renderer is not ready"); clearScreen(); if (screen.render) { renderGrid(Color.lightGray, 0.1); renderGrid(Color.gray, 1.0); renderFunctions(functions); } } } <file_sep>package ch.brotzilla.neat.math; import java.util.List; import com.google.common.base.Preconditions; public abstract class ExtendedActivationFunction extends ActivationFunction { private double rectify(double v, double r) { if (r > 0.0) { if (v < 0) return -v; } else if (r < 0.0) { if (v > 0) return -v; } return v; } @Override protected void initializeDefaultSynapses(List<ActivationFunctionSynapse> synapses) { final ActivationFunctionSynapse.Builder builder = new ActivationFunctionSynapse.Builder(); synapses.add(builder.setName("input-scale") .setDescription("Scales the input value of the activation function.") .setDefaultValue(1.0) .setViewerLowerBound(-10.0) .setViewerUpperBound(10.0) .build()); synapses.add(builder.setName("input-shift") .setDescription("Shifts the input value of the activation function.") .setDefaultValue(0.0) .setViewerLowerBound(-10.0) .setViewerUpperBound(10.0) .build()); synapses.add(builder.setName("output-scale") .setDescription("Scales the output value of the activation function.") .setDefaultValue(1.0) .setViewerLowerBound(-10.0) .setViewerUpperBound(10.0) .build()); synapses.add(builder.setName("output-shift") .setDescription("Shifts the output value of the activation function.") .setDefaultValue(0.0) .setViewerLowerBound(-10.0) .setViewerUpperBound(10.0) .build()); synapses.add(builder.setName("rectify") .setDescription("If greater than 0, mapps all negative output values to positive ones. If less than 0, mapps all positive output values to negative ones. If equal to 0, the output values remain unchanged.") .setDefaultValue(0.0) .setViewerLowerBound(-1.0) .setViewerUpperBound(1.0) .build()); } protected abstract double _compute(double activation, double[] synapses); protected ExtendedActivationFunction(String id, String name, String description) { super(id, name, description); } @Override public double compute(double[] synapses) { Preconditions.checkNotNull(synapses, "The parameter 'synapses' must not be null"); Preconditions.checkArgument(synapses.length >= getNumberOfSynapses(), "The length of the parameter 'synapses' has to be greater than or equal to " + getNumberOfSynapses()); return rectify(_compute(synapses[0] * synapses[1] + synapses[2], synapses), synapses[5]) * synapses[3] + synapses[4]; } } <file_sep>package ch.brotzilla.neat.evolution; import java.util.List; import com.google.common.base.Preconditions; public class SingleThreadingStrategy implements ThreadingStrategy { public SingleThreadingStrategy() {} public void run(List<Specimen> population, EvolutionConfig config) { final EvaluationStrategy evaluationStrategy = config.getEvaluationStrategyProvider().provide(config); Preconditions.checkNotNull(evaluationStrategy, "The evaluation strategy provider must not return null"); for (final Specimen specimen : population) { evaluationStrategy.evaluate(specimen, config); } } } <file_sep>brotzilla-neat ======== An implementation of the NEAT algorithm. (NeuroEvolution of Augmenting Topologies) <file_sep>package ch.brotzilla.neat.math; import java.util.Collections; import java.util.List; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; public abstract class ActivationFunction { public static final double Pi = Math.PI; public static final double TwoPi = 2 * Math.PI; private final String id, name, description; private final List<ActivationFunctionSynapse> synapses; private final int numberOfSynapses; private List<ActivationFunctionSynapse> initializeSynapses() { final List<ActivationFunctionSynapse> result = Lists.newArrayList(); final ActivationFunctionSynapse.Builder builder = new ActivationFunctionSynapse.Builder(); result.add(builder.setName("input") .setDescription("The input of the activation function.") .setDefaultValue(0.0) .setViewerLowerBound(-10.0) .setViewerUpperBound(10.0) .build()); initializeDefaultSynapses(result); return Collections.unmodifiableList(result); } protected abstract void initializeDefaultSynapses(List<ActivationFunctionSynapse> synapses); protected ActivationFunction(String id, String name, String description) { Preconditions.checkNotNull(id, "The parameter 'id' must not be null"); Preconditions.checkArgument(!id.trim().isEmpty(), "The parameter 'id' must not be empty"); Preconditions.checkNotNull(name, "The parameter 'name' must not be null"); Preconditions.checkArgument(!name.trim().isEmpty(), "The parameter 'name' must not be empty"); Preconditions.checkNotNull(description, "The parameter 'description' must not be null"); Preconditions.checkArgument(!description.trim().isEmpty(), "The parameter 'description' must not be empty"); this.id = id; this.name = name; this.description = description; synapses = initializeSynapses(); Preconditions.checkState(synapses.size() > 0, "Internal Error: An activation function requires at least one synapse"); Preconditions.checkState("input".equals(synapses.get(0).getName()), "Internal Error: The first synapse has to be named 'input'"); numberOfSynapses = synapses.size(); } public String getID() { return id; } public String getName() { return name; } public String getDescription() { return description; } public List<ActivationFunctionSynapse> getSynapses() { return synapses; } public int getNumberOfSynapses() { return numberOfSynapses; } public double[] copySynapseDefaults() { final double[] result = new double[numberOfSynapses]; int i = 0; for (final ActivationFunctionSynapse synapse : synapses) { result[i++] = synapse.getDefaultValue(); } return result; } public double getSynapseDefault(int index) { return synapses.get(index).getDefaultValue(); } public void setSynapseDefault(int synapse, double value) { synapses.get(synapse).setDefaultValue(value); } public abstract double compute(double[] synapses); } <file_sep>package ch.brotzilla.neat.evolution; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.hash.TIntObjectHashMap; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; public class Speciation implements Iterable<Species> { private static final SpeciesComparator speciesComparator = new SpeciesComparator(); private final List<Species> list, listWrapper; private final TIntObjectMap<Species> map; private void add(List<Species> speciesList, boolean copy) { for (Species species : speciesList) { Preconditions.checkState(!map.containsKey(species.getId()), "Only unique species ids are supported (duplicate id: " + species.getId() + ")"); if (copy) { species = species.clone(); } map.put(species.getId(), species); list.add(species); } Collections.sort(list, speciesComparator); } public Speciation(List<Species> speciesList, boolean copy) { Preconditions.checkNotNull(speciesList, "The parameter 'speciesList' must not be null"); list = Lists.newArrayList(); listWrapper = Collections.unmodifiableList(list); map = new TIntObjectHashMap<Species>(); add(speciesList, copy); } public Speciation(Speciation source) { Preconditions.checkNotNull(source, "The parameter 'source' must not be null"); list = Lists.newArrayList(); listWrapper = Collections.unmodifiableList(list); map = new TIntObjectHashMap<Species>(); add(source.list, true); } public List<Species> getSpecies() { return listWrapper; } public Species getSpecies(int index) { return list.get(index); } public Species getSpeciesById(int id) { return map.get(id); } public void sortAllSpecies(Comparator<Specimen> comparator) { Preconditions.checkNotNull(comparator, "The parameter 'comparator' must not be null"); for (final Species species : list) { species.sort(comparator); } } public Iterator<Species> iterator() { return listWrapper.iterator(); } @Override public Speciation clone() { return new Speciation(this); } private static class SpeciesComparator implements Comparator<Species> { public int compare(Species a, Species b) { Preconditions.checkNotNull(a, "The parameter 'a' must not be null"); Preconditions.checkNotNull(b, "The parameter 'b' must not be null"); if (a.getId() < b.getId()) return -1; if (a.getId() > b.getId()) return 1; return 0; } } } <file_sep>package ch.brotzilla.cppns.images; import java.awt.image.BufferedImage; import java.awt.image.WritableRaster; import ch.brotzilla.cppns.patterns.PatternGenerator; import com.google.common.base.Preconditions; public class ImageGenerator { private final ImageType type; private final Section section; private PatternGenerator generator; private BufferedImage image; private WritableRaster raster; private int[] colorPixels; private byte[] grayPixels; private short[] grayHDPixels; private void allocateImage(int width, int height) { Preconditions.checkArgument(width > 0, "The parameter 'width' has to be greater than zero"); Preconditions.checkArgument(height > 0, "The parameter 'height' has to be greater than zero"); image = new BufferedImage(width, height, type.getBufferedImageType()); raster = image.getRaster(); colorPixels = null; grayPixels = null; grayHDPixels = null; switch (type) { case Gray: grayPixels = (byte[]) raster.getDataElements(0, 0, width, height, null); break; case GrayHighDefinition: grayHDPixels = (short[]) raster.getDataElements(0, 0, width, height, null); break; default: colorPixels = (int[]) raster.getDataElements(0, 0, width, height, null); } } private int scale(double value) { final int result = value < 0 ? (int) (-value * 255) : (int) (value * 255); if (result > 255) return 255; return result; } private int scaleHD(double value) { final int result = value < 0 ? (int) (-value * 65535) : (int) (value * 65535); if (result > 65535) return 65535; return result; } private int encodeColorAlphaPixel(double a, double r, double g, double b) { return (scale(a) << 24) | (scale(r) << 16) | (scale(g) << 8) | scale(b); } private int encodeColorPixel(double r, double g, double b) { return 0xFF000000 | (scale(r) << 16) | (scale(g) << 8) | scale(b); } private int encodeGrayAlphaPixel(double a, double v) { final int vv = scale(v); return (scale(a) << 24) | (vv << 16) | (vv << 8) | vv; } private short encodeGrayHDPixel(double v) { return (short) (scaleHD(v) & 0xFFFF); } private byte encodeGrayPixel(double v) { return (byte) (scale(v) & 0xFF); } private void generateColorAlphaImage() { final double[] output = new double[4]; final int w = getWidth(), h = getHeight(); final double stepX = section.getWidth() / w, stepY = section.getHeight() / h; for (int y = 0; y < h; y++) { final double yy = section.getY() + (stepY * y); for (int x = 0; x < w; x++) { final double xx = section.getX() + (stepX * x); final int index = y * w + x; generator.generate(xx, yy, output); colorPixels[index] = encodeColorAlphaPixel(output[0], output[1], output[2], output[3]); } } raster.setDataElements(0, 0, w, h, colorPixels); } private void generateColorImage() { final double[] output = new double[3]; final int w = getWidth(), h = getHeight(); final double stepX = section.getWidth() / w, stepY = section.getHeight() / h; for (int y = 0; y < h; y++) { final double yy = section.getY() + (stepY * y); for (int x = 0; x < w; x++) { final double xx = section.getX() + (stepX * x); final int index = y * w + x; generator.generate(xx, yy, output); colorPixels[index] = encodeColorPixel(output[0], output[1], output[2]); } } raster.setDataElements(0, 0, w, h, colorPixels); } private void generateHighDefinitionGrayImage() { final double[] output = new double[1]; final int w = getWidth(), h = getHeight(); final double stepX = section.getWidth() / w, stepY = section.getHeight() / h; for (int y = 0; y < h; y++) { final double yy = section.getY() + (stepY * y); for (int x = 0; x < w; x++) { final double xx = section.getX() + (stepX * x); final int index = y * w + x; generator.generate(xx, yy, output); grayHDPixels[index] = encodeGrayHDPixel(output[0]); } } raster.setDataElements(0, 0, w, h, grayHDPixels); } private void generateGrayAlphaImage() { final double[] output = new double[2]; final int w = getWidth(), h = getHeight(); final double stepX = section.getWidth() / w, stepY = section.getHeight() / h; for (int y = 0; y < h; y++) { final double yy = section.getY() + (stepY * y); for (int x = 0; x < w; x++) { final double xx = section.getX() + (stepX * x); final int index = y * w + x; generator.generate(xx, yy, output); colorPixels[index] = encodeGrayAlphaPixel(output[0], output[1]); } } raster.setDataElements(0, 0, w, h, colorPixels); } private void generateGrayImage() { final double[] output = new double[1]; final int w = getWidth(), h = getHeight(); final double stepX = section.getWidth() / w, stepY = section.getHeight() / h; for (int y = 0; y < h; y++) { final double yy = section.getY() + (stepY * y); for (int x = 0; x < w; x++) { final double xx = section.getX() + (stepX * x); final int index = y * w + x; generator.generate(xx, yy, output); grayPixels[index] = encodeGrayPixel(output[0]); } } raster.setDataElements(0, 0, w, h, grayPixels); } public ImageGenerator(int width, int height, ImageType type, PatternGenerator generator) { Preconditions.checkNotNull(type, "The parameter 'type' must not be null"); Preconditions.checkNotNull(generator, "The parameter 'generator' must not be null"); Preconditions.checkArgument(generator.getOutputSize() == type.getPatternGeneratorOutputSize(), "The output size of the parameter 'generator' has to be equal to " + type.getPatternGeneratorOutputSize()); this.type = type; this.section = new Section(-1, -1, 2, 2); this.generator = generator; allocateImage(width, height); } public ImageType getType() { return type; } public Section getSection() { return section; } public PatternGenerator getPatternGenerator() { return generator; } public BufferedImage getImage() { return image; } public int getWidth() { return image.getWidth(); } public int getHeight() { return image.getHeight(); } public void setSize(int width, int height) { if (width != image.getWidth() || height != image.getHeight()) { allocateImage(width, height); } } public void generate() { switch (type) { case Gray: generateGrayImage(); break; case GrayAlpha: generateGrayAlphaImage(); break; case GrayHighDefinition: generateHighDefinitionGrayImage(); break; case Color: generateColorImage(); break; case ColorAlpha: generateColorAlphaImage(); break; default: throw new UnsupportedOperationException(); } } } <file_sep>package ch.brotzilla.neat.math; import com.google.common.base.Preconditions; public class ActivationFunctionSynapse { private String name, description; private double defaultValue, viewerLowerBound, viewerUpperBound; private ActivationFunctionSynapse() {} public String getName() { return name; } public String getDescription() { return description; } public double getDefaultValue() { return defaultValue; } public void setDefaultValue(double value) { Preconditions.checkState(!Double.isInfinite(value) && !Double.isNaN(value), "The parameter 'value' has to be a valid double value (neither infinity nor nan are allowed)"); defaultValue = value; } public double getViewerLowerBound() { return viewerLowerBound; } public double getViewerUpperBound() { return viewerUpperBound; } @Override public ActivationFunctionSynapse clone() { final ActivationFunctionSynapse p = new ActivationFunctionSynapse(); p.name = name; p.description = description; p.defaultValue = defaultValue; p.viewerLowerBound = viewerLowerBound; p.viewerUpperBound = viewerUpperBound; return p; } public static class Builder { private final ActivationFunctionSynapse p; public Builder() { p = new ActivationFunctionSynapse(); } public Builder setName(String value) { Preconditions.checkNotNull(value, "The parameter 'value' must not be null"); Preconditions.checkArgument(!value.trim().isEmpty(), "The parameter 'value' must not be empty"); p.name = value; return this; } public Builder setDescription(String value) { Preconditions.checkNotNull(value, "The parameter 'value' must not be null"); Preconditions.checkArgument(!value.trim().isEmpty(), "The parameter 'value' must not be empty"); p.description = value; return this; } public Builder setDefaultValue(double value) { Preconditions.checkState(!Double.isInfinite(value) && !Double.isNaN(value), "The parameter 'value' has to be a valid double value (neither infinity nor nan are allowed)"); p.defaultValue = value; return this; } public Builder setViewerLowerBound(double value) { Preconditions.checkState(!Double.isInfinite(value) && !Double.isNaN(value), "The parameter 'value' has to be a valid double value (neither infinity nor nan are allowed)"); p.viewerLowerBound = value; return this; } public Builder setViewerUpperBound(double value) { Preconditions.checkState(!Double.isInfinite(value) && !Double.isNaN(value), "The parameter 'value' has to be a valid double value (neither infinity nor nan are allowed)"); p.viewerUpperBound = value; return this; } public ActivationFunctionSynapse build() { Preconditions.checkState(p.name != null, "The property 'name' must not be null"); Preconditions.checkState(!p.name.trim().isEmpty(), "The property 'name' must not be empty"); Preconditions.checkState(p.description != null, "The property 'description' must not be null"); Preconditions.checkState(!p.description.trim().isEmpty(), "The property 'description' must not be empty"); Preconditions.checkState(!Double.isInfinite(p.defaultValue) && !Double.isNaN(p.defaultValue), "The property 'defaultValue' has to be a valid double value (neither infinity nor nan are allowed)"); Preconditions.checkState(!Double.isInfinite(p.viewerLowerBound) && !Double.isNaN(p.viewerLowerBound), "The property 'viewerLowerBound' has to be a valid double value (neither infinity nor nan are allowed)"); Preconditions.checkState(!Double.isInfinite(p.viewerUpperBound) && !Double.isNaN(p.viewerUpperBound), "The property 'viewerUpperBound' has to be a valid double value (neither infinity nor nan are allowed)"); Preconditions.checkState(p.viewerLowerBound < p.viewerUpperBound, "The property 'viewerLowerBound' has to be less than the property 'viewerUpperBound'"); return p.clone(); } } } <file_sep>package ch.brotzilla.neat.evolution.speciation; import gnu.trove.impl.Constants; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.hash.TIntObjectHashMap; import java.util.Iterator; import java.util.List; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import ch.brotzilla.neat.evolution.Speciation; import ch.brotzilla.neat.evolution.SpeciationStrategy; import ch.brotzilla.neat.evolution.Species; import ch.brotzilla.neat.evolution.Specimen; public class KMeansSpeciationStrategy implements SpeciationStrategy { private final int maxIterations; private final boolean reuseExistingSpecies; private final Entries entries; public KMeansSpeciationStrategy(int numberOfSpecies, int minSpeciesSize, int maxIterations, boolean reuseExistingSpecies) { Preconditions.checkArgument(numberOfSpecies > 1, "The parameter 'numberOfSpecies' has to be greater than 1"); Preconditions.checkArgument(minSpeciesSize >= 0, "The parameter 'minSpeciesSize' has to be greater than or equal to zero"); Preconditions.checkArgument(maxIterations > 0, "The parameter 'maxIterations' has to be greater than zero"); this.maxIterations = maxIterations; this.reuseExistingSpecies = reuseExistingSpecies; entries = new Entries(numberOfSpecies, minSpeciesSize, reuseExistingSpecies); } public int getNumberOfSpecies() { return entries.numberOfSpecies; } public int getMaxIterations() { return maxIterations; } public int getMinSpeciesSize() { return entries.minSpeciesSize; } public boolean getReuseExistingSpecies() { return reuseExistingSpecies; } public Speciation speciate(List<Specimen> population) { entries.beginSpeciation(population); int iterations = 0; do { entries.performSpeciation(population); if (entries.minSpeciesSize > 0 && entries.handleEmptySpecies()) { iterations = 0; } ++iterations; } while (entries.changes > (population.size() / 20) && iterations < maxIterations); return speciate(); } private Speciation speciate() { final List<Species> speciation = Lists.newArrayList(); for (final Entry e : entries) { speciation.add(new Species(e.id, e.list, false)); } return new Speciation(speciation, false); } private static class Entries implements Iterable<Entry> { public final int numberOfSpecies, minSpeciesSize; public final TIntObjectMap<Entry> entries; public final boolean reuseExistingSpecies; public int nextId = 1, changes; public Entries(int numberOfSpecies, int minSpeciesSize, boolean reuseExistingSpecies) { Preconditions.checkArgument(numberOfSpecies > 1, "The parameter 'numberOfSpecies' has to be greater than 1"); Preconditions.checkArgument(minSpeciesSize >= 0, "The parameter 'minSpeciesSize' has to be greater than or equal to zero"); this.numberOfSpecies = numberOfSpecies; this.minSpeciesSize = minSpeciesSize; this.reuseExistingSpecies = reuseExistingSpecies; entries = new TIntObjectHashMap<Entry>(Constants.DEFAULT_CAPACITY, Constants.DEFAULT_LOAD_FACTOR, 0); } public int nextId() { return nextId++; } public int findNearest(Specimen specimen) { Preconditions.checkNotNull(specimen, "The parameter 'specimen' must not be null"); Entry result = null; double nearest = 0; for (final Entry e : this) { final double distance = e.getCentroid().distance(specimen.getGenome()); if (result == null || distance < nearest) { result = e; nearest = distance; } } return Preconditions.checkNotNull(result, "Internal Error: No nearest entry found").id; } public int findEmptyId() { for (final Entry e : this) { if (e.list.size() < minSpeciesSize) { return e.id; } } return 0; } public Entry findLargestEntry() { Entry result = null; int max = 0; for (final Entry e : this) { final int size = e.list.size(); if (result == null || size > max) { result = e; max = size; } } return Preconditions.checkNotNull(result, "Internal Error: No largest entry found"); } public void beginSpeciation(List<Specimen> population) { if (entries.isEmpty()) { initializeSpeciation(population); } else { resumeSpeciation(population); } computeCentroids(); } public void initializeSpeciation(List<Specimen> population) { Preconditions.checkNotNull(population, "The parameter 'population' must not be null"); Preconditions.checkState(entries.isEmpty(), "Internal Error: Speciation has already been initialized"); for (int i = 0; i < numberOfSpecies; i++) { final int nextId = nextId(); entries.put(nextId, new Entry(nextId)); } int i = 0; while (i < population.size()) { for (final Entry e : this) { e.add(population.get(i++)); if (i >= population.size()) break; } } } public void resumeSpeciation(List<Specimen> population) { Preconditions.checkNotNull(population, "The parameter 'population' must not be null"); Preconditions.checkState(entries.size() == numberOfSpecies, "Internal Error: " + entries.size() + " entries found (" + numberOfSpecies + " expected)"); clear(); for (final Specimen specimen : population) { final int nearest = findNearest(specimen); Preconditions.checkNotNull(entries.get(nearest), "Internal Error: Entry not found: " + nearest).add(specimen); } } public void performSpeciation(List<Specimen> population) { Preconditions.checkNotNull(population, "The parameter 'population' must not be null"); clear(); for (final Specimen specimen : population) { final int nearest = findNearest(specimen); if (nearest != specimen.getSpecies()) { changes++; } Preconditions.checkNotNull(entries.get(nearest), "Internal Error: Entry not found: " + nearest).add(specimen); } computeCentroids(); } public boolean handleEmptySpecies() { final int emptyId = findEmptyId(); if (emptyId > 0) { final Entry largestEntry = findLargestEntry(); final Entry largestEntryReplacement = new Entry(largestEntry.id); final Entry newEntry = new Entry(reuseExistingSpecies ? emptyId : nextId()); for (int i = 0; i < largestEntry.list.size(); i++) { final Specimen specimen = largestEntry.list.get(i); if (i % 2 == 0) { largestEntryReplacement.add(specimen); } else { newEntry.add(specimen); } } largestEntryReplacement.compute(); newEntry.compute(); changes += newEntry.list.size(); entries.put(largestEntry.id, largestEntryReplacement); if (reuseExistingSpecies) { entries.put(emptyId, newEntry); } else { entries.remove(emptyId); entries.put(newEntry.id, newEntry); } // call recursively to handle multiple empty entries handleEmptySpecies(); return true; } return false; } public void computeCentroids() { for (final Entry e : this) { e.compute(); } } public void clear() { changes = 0; for (final Entry e : this) { e.clear(); } } public Iterator<Entry> iterator() { Preconditions.checkState(entries != null, "Internal Error: No entries available"); Preconditions.checkState(entries.size() == numberOfSpecies, "Internal Error: " + entries.size() + " entries found (" + numberOfSpecies + " expected)"); return entries.valueCollection().iterator(); } } private static class Entry { public final int id; public final List<Specimen> list; public final CentroidCalculator calculator; public Centroid centroid_; public Entry(int id) { Preconditions.checkArgument(id > 0, "The parameter 'id' has to be greater than zero"); this.id = id; list = Lists.newArrayList(); calculator = new CentroidCalculator(); } public Centroid getCentroid() { return Preconditions.checkNotNull(centroid_, "Internal Error: Centroid not available"); } public void add(Specimen specimen) { Preconditions.checkNotNull(specimen, "The parameter 'specimen' must not be null"); specimen.setSpecies(id); list.add(specimen); calculator.add(specimen.getGenome()); } public void compute() { centroid_ = calculator.compute(); } public void clear() { list.clear(); calculator.clear(); } } } <file_sep>package ch.brotzilla.neat.math; public class ExtendedDecliningSawtoothFunction extends ExtendedDecliningActivationFunction { public ExtendedDecliningSawtoothFunction() { super("neat.math.extended.declining.sawtooth", "Periodic Declining Sawtooth", "Computes a periodic, declining sawtooth function."); } @Override protected double _compute(double activation, double[] synapses) { return (activation < 0.0 ? 2.0 : 0.0) + (2.0 * (activation % 1.0) - 1.0); } } <file_sep>package ch.brotzilla.cppns; import java.io.File; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import ch.brotzilla.cppns.genomes.ActivationFunctionProvider; import ch.brotzilla.cppns.genomes.BasicGenomeGenerator; import ch.brotzilla.cppns.genomes.GenomeGenerator; import ch.brotzilla.cppns.genomes.StochasticActivationFunctionProvider; import ch.brotzilla.cppns.images.ImageGenerator; import ch.brotzilla.cppns.images.ImageType; import ch.brotzilla.cppns.patterns.PatternGenerator; import ch.brotzilla.cppns.patterns.BasicPatternGenerator; import ch.brotzilla.neat.evolution.Rng; import ch.brotzilla.neat.expression.NEATGenomeExpressor; import ch.brotzilla.neat.genome.Genome; import ch.brotzilla.neat.genome.Genomes; import ch.brotzilla.neat.history.HistoryList; import ch.brotzilla.neat.math.ActivationFunction; import ch.brotzilla.neat.math.ExtendedDecliningCosFunction; import ch.brotzilla.neat.math.ExtendedDecliningSawtoothFunction; import ch.brotzilla.neat.math.ExtendedDecliningSquareFunction; import ch.brotzilla.neat.math.ExtendedDecliningTriangleFunction; import ch.brotzilla.neat.math.ExtendedGaussianFunction; import ch.brotzilla.neat.math.ExtendedLinearFunction; import ch.brotzilla.neat.math.ExtendedLogFunction; import ch.brotzilla.neat.math.ExtendedModifiedTanhFunction; import ch.brotzilla.neat.math.ExtendedPeriodicCosFunction; import ch.brotzilla.neat.math.ExtendedPeriodicSawtoothFunction; import ch.brotzilla.neat.math.ExtendedPeriodicSquareFunction; import ch.brotzilla.neat.math.ExtendedPeriodicTriangleFunction; import ch.brotzilla.neat.math.ExtendedSignumFunction; import ch.brotzilla.neat.math.ExtendedSqrtFunction; import ch.brotzilla.neat.math.ExtendedTanhFunction; import ch.brotzilla.util.MersenneTwister; public class Test { private static class TestRng implements Rng { private final MersenneTwister rng; public TestRng(long seed) { rng = new MersenneTwister(seed); } public int nextInt() { return rng.nextInt(); } public int nextInt(int n) { return rng.nextInt(n); } public int nextInt(int low, int high) { throw new UnsupportedOperationException(); } public double nextDouble() { return rng.nextDouble(); } } private static String format(int i) { if (i < 10) { return "00" + i; } if (i < 100) { return "0" + i; } return "" + i; } private static ActivationFunction getRandomActivationFunction(Rng rng) { switch (rng.nextInt(5)) { case 0: return new ExtendedPeriodicCosFunction(); case 1: return new ExtendedPeriodicTriangleFunction(); case 2: return new ExtendedDecliningCosFunction(); case 3: return new ExtendedPeriodicTriangleFunction(); case 4: return new ExtendedTanhFunction(); default: throw new UnsupportedOperationException(); } } private static ActivationFunctionProvider getActivationFunctionProvider() { final StochasticActivationFunctionProvider result = new StochasticActivationFunctionProvider(); // result.add(new ExtendedDecliningCosFunction(), 1); // result.add(new ExtendedDecliningSawtoothFunction(), 1); // result.add(new ExtendedDecliningSquareFunction(), 1); // result.add(new ExtendedDecliningTriangleFunction(), 1); // result.add(new ExtendedPeriodicCosFunction(), 1); result.add(new ExtendedPeriodicSawtoothFunction(), 1); result.add(new ExtendedPeriodicSquareFunction(), 1); result.add(new ExtendedPeriodicTriangleFunction(), 1); // result.add(new ExtendedTanhFunction(), 1); // result.add(new ExtendedModifiedTanhFunction(), 1); // result.add(new ExtendedGaussianFunction(), 1); // result.add(new ExtendedLinearFunction(), 1); // result.add(new ExtendedLogFunction(), 1); // result.add(new ExtendedSignumFunction(), 1); // result.add(new ExtendedSqrtFunction(), 1); return result; } public static void main(String[] args) throws IOException { final ImageType type = ImageType.Gray; final HistoryList historyList = new HistoryList(); final TestRng rng = new TestRng(new Random().nextLong()); final ActivationFunctionProvider activationFunctionProvider = getActivationFunctionProvider(); final BasicGenomeGenerator genomeGenerator = new BasicGenomeGenerator(historyList, activationFunctionProvider); genomeGenerator.setRecurrentLinkProbability(0.01); genomeGenerator.setSynapseLinkProbability(0.1); final NEATGenomeExpressor expressor = new NEATGenomeExpressor(); for (int i = 0; i < 100; i++) { System.out.println("Generating image " + (i + 1) + " of 100..."); final PatternGenerator pattern = new BasicPatternGenerator(expressor.express(genomeGenerator.generate(type, rng))); final ImageGenerator generator = new ImageGenerator(200, 200, type, pattern); generator.getSection().setBounds(-1, -1, 2, 2); generator.generate(); ImageIO.write(generator.getImage(), "PNG", new File("./pics/test" + format(i) + ".png")); } } } <file_sep>package ch.brotzilla.neat.evolution.speciation; import java.util.List; import com.google.common.collect.Lists; import ch.brotzilla.neat.evolution.Speciation; import ch.brotzilla.neat.evolution.SpeciationStrategy; import ch.brotzilla.neat.evolution.Species; import ch.brotzilla.neat.evolution.Specimen; public class NoSpeciationStrategy implements SpeciationStrategy { public Speciation speciate(List<Specimen> population) { for (final Specimen specimen : population) { specimen.setSpecies(1); } final List<Species> list = Lists.newArrayList(); list.add(new Species(1, population, false)); return new Speciation(list, false); } } <file_sep>package ch.brotzilla.neat.math; public class ExtendedSqrtFunction extends ExtendedActivationFunction { public ExtendedSqrtFunction() { super("neat.math.extended.sqrt", "Square Root", "Returns the positive square root of the argument. Negative input values are mapped to negative output values."); } @Override protected double _compute(double activation, double[] synapses) { if (activation < 0) { return -Math.sqrt(-activation); } return Math.sqrt(activation); } } <file_sep>package ch.brotzilla.neat.math; public class ExtendedDecliningTriangleFunction extends ExtendedDecliningActivationFunction { public ExtendedDecliningTriangleFunction() { super("neat.math.extended.declining.triangle", "Periodic Declining Triangle", "Computes a periodic, declining triangle function."); } @Override protected double _compute(double activation, double[] synapses) { return (2.0 * Math.asin(Math.cos(TwoPi * activation))) / Pi; } } <file_sep>package ch.brotzilla.neat.evolution.speciation; import gnu.trove.impl.Constants; import gnu.trove.map.TIntDoubleMap; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.hash.TIntDoubleHashMap; import gnu.trove.map.hash.TIntObjectHashMap; import ch.brotzilla.neat.Debug; import ch.brotzilla.neat.genome.Genome; import ch.brotzilla.neat.genome.Link; import ch.brotzilla.neat.genome.Node; import com.google.common.base.Preconditions; public class CentroidCalculator { private final TIntObjectMap<NodeEntry> nodes; private final TIntObjectMap<LinkEntry> links; public CentroidCalculator() { nodes = new TIntObjectHashMap<NodeEntry>(); links = new TIntObjectHashMap<LinkEntry>(); } public void add(Genome genome) { Preconditions.checkNotNull(genome, "The parameter 'genome' must not be null"); for (final Node node : genome) { if (node.getType().isInputNode()) continue; NodeEntry entry = nodes.get(node.getInnovationNumber()); if (entry == null) { entry = new NodeEntry(node); nodes.put(node.getInnovationNumber(), entry); } else { entry.add(node); } } for (final Link link : genome.getLinks()) { LinkEntry entry = links.get(link.getInnovationNumber()); if (entry == null) { entry = new LinkEntry(link); links.put(link.getInnovationNumber(), entry); } else { entry.add(link); } } } public Centroid compute() { final TIntObjectMap<double[]> nc = new TIntObjectHashMap<double[]>(Constants.DEFAULT_CAPACITY, Constants.DEFAULT_LOAD_FACTOR, 0); final TIntDoubleMap lc = new TIntDoubleHashMap(Constants.DEFAULT_CAPACITY, Constants.DEFAULT_LOAD_FACTOR, 0, Double.NaN); for (final NodeEntry entry : nodes.valueCollection()) { if (Debug.EnableIntegrityChecks) { Preconditions.checkState(!nc.containsKey(entry.id), "Node entries have to be unique"); } nc.put(entry.id, entry.compute()); } for (final LinkEntry entry : links.valueCollection()) { if (Debug.EnableIntegrityChecks) { Preconditions.checkState(!lc.containsKey(entry.id), "Link entries have to be unique"); } lc.put(entry.id, entry.compute()); } return new Centroid(nc, lc); } public void clear() { nodes.clear(); links.clear(); } private static class NodeEntry { private final int id; private int count; private final double[] totals; public NodeEntry(Node node) { Preconditions.checkNotNull(node, "The parameter 'node' must not be null"); id = node.getInnovationNumber(); count = 1; totals = node.copySynapseDefaults(); } public void add(Node node) { Preconditions.checkNotNull(node, "The parameter 'node' must not be null"); Preconditions.checkArgument(node.getInnovationNumber() == id, "The innovation number of the node has to be " + id); final double[] synapses = node.getSynapseDefaults(); Preconditions.checkState(totals.length == synapses.length, "The node with the id " + node.getInnovationNumber() + " is expected to have exactly " + totals.length + " synapses"); count++; for (int i = 0; i < synapses.length; i++) { totals[i] += synapses[i]; } } public double[] compute() { final double[] result = new double[totals.length]; for (int i = 0; i < result.length; i++) { result[i] = totals[i] / count; } return result; } } private static class LinkEntry { private final int id; private int count; private double total; public LinkEntry(Link link) { Preconditions.checkNotNull(link, "The parameter 'link' must not be null"); id = link.getInnovationNumber(); count = 1; total = link.getWeight(); } public void add(Link link) { Preconditions.checkNotNull(link, "The parameter 'link' must not be null"); Preconditions.checkArgument(link.getInnovationNumber() == id, "The innovation number of the link has to be " + id); count++; total += link.getWeight(); } public double compute() { return total / count; } } }<file_sep>package ch.brotzilla.neat.genome; import ch.brotzilla.neat.history.LinkHistoryKey; import ch.brotzilla.neat.history.LinkInnovation; import com.google.common.base.Preconditions; public class Link { private final int innovationNumber, sourceNode, targetNode, targetSynapse; private double weight; public Link(int innovationNumber, int sourceNode, int targetNode, int targetSynapse) { Preconditions.checkArgument(innovationNumber > 0, "The parameter 'innovationNumber' has to be greater than zero"); Preconditions.checkArgument(sourceNode > 0, "The parameter 'sourceNode' has to be greater than zero"); Preconditions.checkArgument(targetNode > 0, "The parameter 'targetNode' has to be greater than zero"); Preconditions.checkArgument(targetSynapse >= 0, "The parameter 'targetSynapse' has to be greater than or equal to zero"); this.innovationNumber = innovationNumber; this.sourceNode = sourceNode; this.targetNode = targetNode; this.targetSynapse = targetSynapse; } public Link(int innovationNumber, LinkHistoryKey key) { Preconditions.checkArgument(innovationNumber > 0, "The parameter 'innovationNumber' has to be greater than zero"); Preconditions.checkNotNull(key, "The parameter 'key' must not be null"); this.innovationNumber = innovationNumber; this.sourceNode = key.getSourceNode(); this.targetNode = key.getTargetNode(); this.targetSynapse = key.getTargetSynapse(); } public Link(LinkInnovation innovation) { Preconditions.checkNotNull(innovation, "The parameter 'innovation' must not be null"); this.innovationNumber = innovation.getLinkInnovationNumber(); this.sourceNode = innovation.getLinkHistoryKey().getSourceNode(); this.targetNode = innovation.getLinkHistoryKey().getTargetNode(); this.targetSynapse = innovation.getLinkHistoryKey().getTargetSynapse(); } public Link(Link source) { Preconditions.checkNotNull(source, "The parameter 'source' must not be null"); innovationNumber = source.innovationNumber; sourceNode = source.sourceNode; targetNode = source.targetNode; targetSynapse = source.targetSynapse; weight = source.weight; } public int getInnovationNumber() { return innovationNumber; } public int getSourceNode() { return sourceNode; } public int getTargetNode() { return targetNode; } public int getTargetSynapse() { return targetSynapse; } public double getWeight() { return weight; } public void setWeight(double value) { weight = value; } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other instanceof Link) { final Link link = (Link) other; return innovationNumber == link.innovationNumber && sourceNode == link.sourceNode && targetNode == link.targetNode && targetSynapse == link.targetSynapse && weight == link.weight; } return false; } @Override public Link clone() { return new Link(this); } } <file_sep>package ch.brotzilla.neat.genome; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.hash.TIntObjectHashMap; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import ch.brotzilla.neat.Debug; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; public class Genome implements Iterable<Node> { private Node biasNode; private final List<Node> inputNodes, hiddenNodes, outputNodes, inputWrapper, hiddenWrapper, outputWrapper; private final List<Link> links, linksWrapper; private final TIntObjectMap<Node> nodesMap; private final TIntObjectMap<Link> linksMap; private int inputSize, hiddenSize, outputSize, totalSize; private double sigma = 0.2; private void add(Link link, boolean updateTargetNode) { Preconditions.checkNotNull(link, "The parameter 'link' must not be null"); Preconditions.checkArgument(!linksMap.containsKey(link.getInnovationNumber()), "The genome already contains a link with the innovation number " + link.getInnovationNumber()); if (Debug.EnableIntegrityChecks) { final Node sourceNode = nodesMap.get(link.getSourceNode()); Preconditions.checkArgument(sourceNode != null, "The genome does not contain a source node with the innovation number " + link.getSourceNode()); final Node targetNode = nodesMap.get(link.getTargetNode()); Preconditions.checkArgument(targetNode != null, "The genome does not contain a target node with the innovation number " + link.getTargetNode()); Preconditions.checkArgument(targetNode.getType().isTargetNode(), "The node with the innovation number " + targetNode.getInnovationNumber() + " has to be of type Hidden or Output"); } if (updateTargetNode) { final Node targetNode = nodesMap.get(link.getTargetNode()); Preconditions.checkArgument(targetNode != null, "The genome does not contain a target node with the innovation number " + link.getTargetNode()); targetNode.add(link); } links.add(link); linksMap.put(link.getInnovationNumber(), link); } private void removeLinkFromNode(Link link) { Preconditions.checkNotNull(link, "The parameter 'link' must not be null"); final Node targetNode = nodesMap.get(link.getTargetNode()); Preconditions.checkArgument(targetNode != null, "The genome does not contain a target node with the innovation number " + link.getTargetNode()); targetNode.remove(link); } private Node removeNodeFromLists(int index) { Preconditions.checkElementIndex(index, totalSize, "The parameter 'index'"); if (biasNode != null) { if (index == 0) { final Node result = biasNode; biasNode = null; return result; } --index; } if (index < inputSize) { return inputNodes.remove(index); } index -= inputSize; if (index < hiddenSize) { return hiddenNodes.remove(index); } index -= hiddenSize; return outputNodes.remove(index); } private void decrementSizes(NodeType type) { if (type == NodeType.Input) { --inputSize; } else if (type == NodeType.Hidden) { --hiddenSize; } else if (type == NodeType.Output) { --outputSize; } --totalSize; } private void incrementSizes(NodeType type) { if (type == NodeType.Input) { ++inputSize; } else if (type == NodeType.Hidden) { ++hiddenSize; } else if (type == NodeType.Output) { ++outputSize; } ++totalSize; } public Genome() { inputNodes = Lists.newArrayList(); hiddenNodes = Lists.newArrayList(); outputNodes = Lists.newArrayList(); inputWrapper = Collections.unmodifiableList(inputNodes); hiddenWrapper = Collections.unmodifiableList(hiddenNodes); outputWrapper = Collections.unmodifiableList(outputNodes); links = Lists.newArrayList(); linksWrapper = Collections.unmodifiableList(links); nodesMap = new TIntObjectHashMap<Node>(); linksMap = new TIntObjectHashMap<Link>(); } public Genome(Genome source) { this(); Preconditions.checkNotNull(source, "The parameter 'source' must not be null"); for (final Node node : source) { add(node.clone()); } for (final Link link : source.links) { add(link.clone(), false); } inputSize = source.inputSize; hiddenSize = source.hiddenSize; totalSize = source.totalSize; } public final int getNumberOfNodes() { return totalSize; } public final int getNumberOfInputNodes() { return inputSize; } public final int getNumberOfHiddenNodes() { return hiddenSize; } public final int getNumberOfOutputNodes() { return outputSize; } public final Node getBiasNode() { return biasNode; } public final List<Node> getInputNodes() { return inputWrapper; } public final List<Node> getHiddenNodes() { return hiddenWrapper; } public final List<Node> getOutputNodes() { return outputWrapper; } public Iterator<Node> iterator() { return new NodesIterator(); } public final List<Link> getLinks() { return linksWrapper; } public final double getSigma() { return sigma; } public final void setSigma(double value) { sigma = value; } public final Node getNodeByIndex(int index) { Preconditions.checkElementIndex(index, totalSize, "The parameter 'index'"); if (biasNode != null) { if (index == 0) { return biasNode; } --index; } if (index < inputSize) { return inputNodes.get(index); } index -= inputSize; if (index < hiddenSize) { return hiddenNodes.get(index); } index -= hiddenSize; return outputNodes.get(index); } public final Node getNodeByInnovation(int innovationNumber) { Preconditions.checkArgument(innovationNumber > 0, "The parameter 'innovationNumber' has to be greater than zero"); return nodesMap.get(innovationNumber); } public final Link getLinkByIndex(int index) { return links.get(index); } public final Link getLinkByInnovation(int innovationNumber) { Preconditions.checkArgument(innovationNumber > 0, "The parameter 'innovationNumber' has to be greater than zero"); return linksMap.get(innovationNumber); } public final void add(Node node) { Preconditions.checkNotNull(node, "The parameter 'node' must not be null"); Preconditions.checkArgument(!nodesMap.containsKey(node.getInnovationNumber()), "The genome already contains a node with the innovation number " + node.getInnovationNumber()); if (node.getType() == NodeType.Bias) { Preconditions.checkArgument(biasNode == null, "The genome already contains a bias node"); biasNode = node; } else { node.getType().selectNodesList(inputNodes, hiddenNodes, outputNodes).add(node); } nodesMap.put(node.getInnovationNumber(), node); incrementSizes(node.getType()); } public final void add(Link link) { add(link, true); } public final void remove(Node node) { Preconditions.checkNotNull(node, "The parameter 'node' must not be null"); if (node.getType() == NodeType.Bias) { Preconditions.checkArgument(node == biasNode, "The parameter 'node' is not part of this genome"); biasNode = null; } else { Preconditions.checkArgument(node.getType().selectNodesList(inputNodes, hiddenNodes, outputNodes).remove(node), "The parameter 'node' is not part of this genome"); } nodesMap.remove(node.getInnovationNumber()); decrementSizes(node.getType()); } public final void removeNodeByIndex(int index) { Preconditions.checkElementIndex(index, totalSize, "The parameter 'index'"); final Node node = removeNodeFromLists(index); nodesMap.remove(node.getInnovationNumber()); decrementSizes(node.getType()); } public final void removeNodeByInnovation(int innovationNumber) { Preconditions.checkArgument(innovationNumber > 0, "The parameter 'innovationNumber' has to be greater than zero"); final Node node = nodesMap.remove(innovationNumber); Preconditions.checkArgument(node != null, "The genome does not contain a node with the innovation number " + innovationNumber); if (node == biasNode) { biasNode = null; } else { node.getType().selectNodesList(inputNodes, hiddenNodes, outputNodes).remove(node); } decrementSizes(node.getType()); } public final void remove(Link link) { Preconditions.checkNotNull(link, "The parameter 'link' must not be null"); Preconditions.checkArgument(links.remove(link), "The parameter 'link' is not part of this genome"); linksMap.remove(link.getInnovationNumber()); removeLinkFromNode(link); } public final void removeLinkByIndex(int index) { final Link link = links.remove(index); linksMap.remove(link.getInnovationNumber()); removeLinkFromNode(link); } public final void removeLinkByInnovation(int innovationNumber) { Preconditions.checkArgument(innovationNumber > 0, "The parameter 'innovationNumber' has to be greater than zero"); final Link link = linksMap.remove(innovationNumber); Preconditions.checkArgument(link != null, "The genome does not contain a link with the innovation number " + innovationNumber); links.remove(link); removeLinkFromNode(link); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other instanceof Genome) { final Genome genome = (Genome) other; if (inputNodes.size() != genome.inputNodes.size() || hiddenNodes.size() != genome.hiddenNodes.size() || outputNodes.size() != genome.outputNodes.size()) { return false; } if (links.size() != genome.links.size()) { return false; } if (!(biasNode == null ? genome.biasNode == null : biasNode.equals(genome.biasNode))) { return false; } if (!inputNodes.equals(genome.inputNodes)) { return false; } if (!hiddenNodes.equals(genome.hiddenNodes)) { return false; } if (!outputNodes.equals(genome.outputNodes)) { return false; } if (!links.equals(genome.links)) { return false; } return true; } return false; } @Override public Genome clone() { return new Genome(this); } private class NodesIterator implements Iterator<Node> { private final int expectedSize; private final Iterator<Node>[] iterators; private Iterator<Node> iterator; private int nextIterator; private Iterator<Node>[] initIterators() { final int numIterators = (biasNode != null ? 1 : 0) + (inputSize > 0 ? 1 : 0) + (hiddenSize > 0 ? 1 : 0) + (outputNodes.size() > 0 ? 1 : 0); if (numIterators > 0) { @SuppressWarnings("unchecked") final Iterator<Node>[] result = new Iterator[numIterators]; int index = 0; if (biasNode != null) { result[index++] = new BiasNodeIterator(); } if (inputSize > 0) { result[index++] = inputNodes.iterator(); } if (hiddenSize > 0) { result[index++] = hiddenNodes.iterator(); } if (outputNodes.size() > 0) { result[index] = outputNodes.iterator(); } return result; } return null; } public NodesIterator() { expectedSize = totalSize; iterators = initIterators(); iterator = (iterators == null ? null : iterators[0]); nextIterator = 1; } public boolean hasNext() { return iterator != null && iterator.hasNext(); } public Node next() { if (totalSize != expectedSize) { throw new ConcurrentModificationException(); } if (iterator == null) { throw new NoSuchElementException(); } final Node node = iterator.next(); if (!iterator.hasNext()) { if (nextIterator < iterators.length) { iterator = iterators[nextIterator++]; } else { iterator = null; } } return node; } public void remove() { throw new UnsupportedOperationException(); } } private class BiasNodeIterator implements Iterator<Node> { private boolean hasNext = true; public BiasNodeIterator() {} public boolean hasNext() { return hasNext; } public Node next() { hasNext = false; return biasNode; } public void remove() { throw new UnsupportedOperationException(); } } } <file_sep>package ch.brotzilla.cppns.images; import com.google.common.base.Preconditions; public class Section { private double x = -1, y = -1, width = 2, height = 2; public Section(double x, double y, double width, double height) { Preconditions.checkArgument(width > 0, "The parameter 'width' has to be greater than zero"); Preconditions.checkArgument(height > 0, "The parameter 'height' has to be greater than zero"); this.x = x; this.y = y; this.width = width; this.height = height; } public Section(Section source) { Preconditions.checkNotNull(source, "The parameter 'source' must not be null"); x = source.x; y = source.y; width = source.width; height = source.height; } public double getX() { return x; } public void setX(double value) { x = value; } public double getY() { return y; } public void setY(double value) { y = value; } public void setPosition(double x, double y) { this.x = x; this.y = y; } public void setPosition(Section value) { Preconditions.checkNotNull(value, "The parameter 'value' must not be null"); x = value.x; y = value.y; } public double getWidth() { return width; } public void setWidth(double value) { Preconditions.checkArgument(value > 0, "The parameter 'value' has to be greater than zero"); width = value; } public double getHeight() { return height; } public void setHeight(double value) { Preconditions.checkArgument(value > 0, "The parameter 'value' has to be greater than zero"); height = value; } public void setSize(double width, double height) { Preconditions.checkArgument(width > 0, "The parameter 'width' has to be greater than zero"); Preconditions.checkArgument(height > 0, "The parameter 'height' has to be greater than zero"); this.width = width; this.height = height; } public void setSize(Section value) { Preconditions.checkNotNull(value, "The parameter 'value' must not be null"); width = value.width; height = value.height; } public void setBounds(double x, double y, double width, double height) { Preconditions.checkArgument(width > 0, "The parameter 'width' has to be greater than zero"); Preconditions.checkArgument(height > 0, "The parameter 'height' has to be greater than zero"); this.x = x; this.y = y; this.width = width; this.height = height; } public void setBounds(Section value) { Preconditions.checkNotNull(value, "The parameter 'value' must not be null"); x = value.x; y = value.y; width = value.width; height = value.height; } } <file_sep>package ch.brotzilla.neat.math; public class ExtendedModifiedTanhFunction extends ExtendedActivationFunction { public ExtendedModifiedTanhFunction() { super("neat.math.extended.modified-tanh", "Modified Hyperbolic Tangent", "Returns the hyperbolic tangent of the argument. The argument will first be raised to the power of 3."); setSynapseDefault(0, 1.5); } @Override protected double _compute(double activation, double[] synapses) { final double a = activation * activation * activation; return 2.0d / (1.0d + Math.exp(-2.0d * a)) - 1.0d; } } <file_sep>package ch.brotzilla.cppns.genomes; import ch.brotzilla.neat.evolution.Rng; import ch.brotzilla.neat.math.ActivationFunction; public interface ActivationFunctionProvider { ActivationFunction[] provide(int count, Rng rng); ActivationFunction provide(Rng rng); } <file_sep>package ch.brotzilla.neat.evolution; public interface EvaluationStrategyProvider { EvaluationStrategy provide(EvolutionConfig config); } <file_sep>package ch.brotzilla.neat.math; public class ExtendedModifiedElliottFunction extends ExtendedActivationFunction { public ExtendedModifiedElliottFunction() { super("neat.math.extended.modified-elliott", "Modified Elliott", "The elliott function is higher-speed approximation of the hyperbolic tangent and sigmoid functions. The argument will first be raised to the power of 3."); setSynapseDefault(0, 2.5); setSynapseDefault(1, 2.0); } @Override protected double _compute(double activation, double[] synapses) { final double a = activation < 0.0 ? -activation : activation; final double b = a * a * a; return activation / (1.0 + b); } } <file_sep>package ch.brotzilla.neat.neuralnet; import java.util.Arrays; import com.google.common.base.Preconditions; import ch.brotzilla.neat.Debug; import ch.brotzilla.neat.math.ActivationFunction; public abstract class Neuron { protected final int neuronIndex; protected final ActivationFunction activationFunction; protected final Connection[] connections; protected final double[] synapseDefaults; protected final double[] synapseInputs; protected abstract void setActivation(NeuralNet nn, double activation); void compute(NeuralNet nn) { for (int i = 0; i < synapseInputs.length; i++) { synapseInputs[i] = synapseDefaults[i]; } for (final Connection c : connections) { synapseInputs[c.getSynapse()] += c.getValue(nn); } setActivation(nn, activationFunction.compute(synapseInputs)); } public Neuron(int neuronIndex, ActivationFunction activationFunction, double[] synapseDefaults, Connection[] connections) { Preconditions.checkNotNull(activationFunction, "The parameter 'activationFunction' must not be null"); Preconditions.checkNotNull(synapseDefaults, "The parameter 'synapseDefaults' must not be null"); Preconditions.checkArgument(synapseDefaults.length == activationFunction.getNumberOfSynapses(), "The length of the parameter 'synapseDefaults' has to be equal to " + activationFunction.getNumberOfSynapses()); Preconditions.checkNotNull(connections, "The parameter 'connections' must not be null"); Preconditions.checkArgument(connections.length > 0, "The length of the parameter 'connections' has to be greater than zero"); if (Debug.EnableIntegrityChecks) { for (int i = 0; i < connections.length; i++) { final Connection c = connections[i]; Preconditions.checkNotNull(c, "The parameter 'connections[" + i + "]' must not be null"); Preconditions.checkElementIndex(c.getSynapse(), activationFunction.getNumberOfSynapses(), "The synapse of the parameter 'connections[" + i + "]'"); } } this.neuronIndex = neuronIndex; this.activationFunction = activationFunction; this.connections = Arrays.copyOf(connections, connections.length); this.synapseDefaults = Arrays.copyOf(synapseDefaults, synapseDefaults.length); this.synapseInputs = new double[activationFunction.getNumberOfSynapses()]; } public int getNeuronIndex() { return neuronIndex; } public ActivationFunction getActivationFunction() { return activationFunction; } public int getNumberOfConnections() { return connections.length; } public Connection getConnection(int index) { return connections[index]; } } <file_sep>package ch.brotzilla.neat.math; public class ExtendedPeriodicSquareFunction extends ExtendedActivationFunction { public ExtendedPeriodicSquareFunction() { super("neat.math.extended.periodic.square", "Periodic Square", "Computes a periodic square function."); } @Override protected double _compute(double activation, double[] synapses) { return Math.signum(Math.cos(TwoPi * activation)); } } <file_sep>package ch.brotzilla.cppns.genomes; import ch.brotzilla.neat.evolution.Rng; import ch.brotzilla.neat.history.HistoryList; import ch.brotzilla.neat.math.ActivationFunction; import com.google.common.base.Preconditions; public abstract class AbstractGenomeGenerator implements GenomeGenerator { private final HistoryList historyList; private final ActivationFunctionProvider activationFunctionProvider; private final ActivationFunction outputActivationFunction; protected ActivationFunction[] provideActivationFunctions(int count, Rng rng) { return activationFunctionProvider.provide(count, rng); } protected ActivationFunction provideActivationFunction(Rng rng) { return activationFunctionProvider.provide(rng); } public AbstractGenomeGenerator(HistoryList historyList, ActivationFunctionProvider activationFunctionProvider, ActivationFunction outputActivationFunction) { Preconditions.checkNotNull(historyList, "The parameter 'historyList' must not be null"); Preconditions.checkNotNull(activationFunctionProvider, "The parameter 'activationFunctionProvider' must not be null"); this.historyList = historyList; this.activationFunctionProvider = activationFunctionProvider; this.outputActivationFunction = outputActivationFunction; } public HistoryList getHistoryList() { return historyList; } public ActivationFunctionProvider getActivationFunctionProvider() { return activationFunctionProvider; } public ActivationFunction getOutputActivationFunction() { return outputActivationFunction; } } <file_sep>package ch.brotzilla.neat.math; public class ExtendedDecliningSquareFunction extends ExtendedDecliningActivationFunction { public ExtendedDecliningSquareFunction() { super("neat.math.extended.declining.square", "Periodic Declining Square", "Computes a periodic, declining square function."); } @Override protected double _compute(double activation, double[] synapses) { return Math.signum(Math.cos(TwoPi * activation)); } } <file_sep>package ch.brotzilla.neat.evolution; import java.util.List; public interface PopulationProvider { List<Specimen> providePopulation(EvolutionConfig config); } <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>ch.brotzilla</groupId> <artifactId>neat</artifactId> <version>0.0.1-preAlpha</version> <name>Brotzilla NEAT</name> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source/> <target/> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <executions> <execution> <id>attach-sources</id> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version> </dependency> <dependency> <groupId>net.sf.trove4j</groupId> <artifactId>trove4j</artifactId> <version>3.0.3</version> </dependency> </dependencies> <description>Implementation of the NEAT (neuro evolution of augmenting topologies) method for evolving neural networks.</description> </project><file_sep>package ch.brotzilla.neat.evolution; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; public class Species implements Iterable<Specimen> { private final int id; private final List<Specimen> specimens, specimensWrapper; public Species(int id, List<Specimen> specimens, boolean copy) { Preconditions.checkArgument(id > 0, "The parameter 'id' has to be greater than zero"); Preconditions.checkNotNull(specimens, "The parameter 'specimens' must not be null"); this.id = id; this.specimens = Lists.newArrayListWithCapacity(specimens.size()); this.specimensWrapper = Collections.unmodifiableList(this.specimens); for (final Specimen specimen : specimens) { Preconditions.checkArgument(specimen.getSpecies() == id, "The parameter 'specimens' may only contain specimens with species id " + id); this.specimens.add(copy ? specimen.clone() : specimen); } } public Species(Species source) { Preconditions.checkNotNull(source, "The parameter 'source' must not be null"); id = source.id; specimens = Lists.newArrayListWithCapacity(source.size()); specimensWrapper = Collections.unmodifiableList(specimens); for (final Specimen specimen : source) { specimens.add(specimen.clone()); } } public int getId() { return id; } public List<Specimen> getSpecimens() { return specimensWrapper; } public int size() { return specimens.size(); } public Specimen getSpecimen(int index) { return specimens.get(index); } public void sort(Comparator<Specimen> comparator) { Preconditions.checkNotNull(comparator, "The parameter 'comparator' must not be null"); Collections.sort(specimens, comparator); } public Iterator<Specimen> iterator() { return specimensWrapper.iterator(); } @Override public Species clone() { return new Species(this); } } <file_sep>package ch.brotzilla.neat.neuralnet; public class OutputNeuronConnection extends NeuronConnection { public OutputNeuronConnection(int neuronIndex, int synapse, double weight) { super(neuronIndex, synapse, weight); } @Override public double getValue(NeuralNet nn) { return nn.getOutputNeuronActivation(neuronIndex) * weight; } } <file_sep>package ch.brotzilla.neat.evolution; public interface StopCondition { boolean isSatisfied(); } <file_sep>package ch.brotzilla.cppns.genomes; import java.util.List; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import ch.brotzilla.neat.evolution.Rng; import ch.brotzilla.neat.math.ActivationFunction; public class StochasticActivationFunctionProvider implements ActivationFunctionProvider { private final List<Entry> functions; private double computeTotalProbability() { double result = 0; for (final Entry e : functions) { result += e.probability; } return result; } public double[] computeSlots(int count, double total) { final double[] slots = new double[functions.size()]; int slot = 0; double sum = 0; for (final Entry e : functions) { sum += e.probability / total; slots[slot++] = sum; } return slots; } private static class Entry { private final ActivationFunction function; private final double probability; public Entry(ActivationFunction function, double probability) { Preconditions.checkNotNull(function, "The parameter 'function' must not be null"); Preconditions.checkArgument(probability > 0, "The parameter 'probability' has to be greater than zero"); this.function = function; this.probability = probability; } } public StochasticActivationFunctionProvider() { functions = Lists.newArrayList(); } public int size() { return functions.size(); } public void add(ActivationFunction function, double probability) { functions.add(new Entry(function, probability)); } public ActivationFunction[] provide(int count, Rng rng) { Preconditions.checkArgument(count > 0, "The parameter 'count' has to be greater than zero"); Preconditions.checkNotNull(rng, "The paramter 'rng' must not be null"); final ActivationFunction[] result = new ActivationFunction[count]; final double pointerSize = rng.nextDouble() / count; final double total = computeTotalProbability(); final double[] slots = computeSlots(count, total); int slot = 0; for (int i = 0; i < count; i++) { final double pointer = pointerSize * (i + 1); while (slots[slot] <= pointer) { ++slot; } result[i] = functions.get(slot).function; } return result; } public ActivationFunction provide(Rng rng) { return provide(1, rng)[0]; } } <file_sep>package ch.brotzilla.neat.evolution; import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; import com.google.common.base.Preconditions; public class Objectives implements Iterable<Objective> { private Objective[] objectives; public Objectives(Objective... objectives) { Preconditions.checkNotNull(objectives, "The parameter 'objectives' must not be null"); Preconditions.checkArgument(objectives.length > 0, "The length of the parameter 'objectives' has to be greater than zero"); for (int i = 0; i < objectives.length; i++) { Preconditions.checkNotNull(objectives[i], "The parameter 'objectives[i]' must not be null"); } this.objectives = Arrays.copyOf(objectives, objectives.length); } public int getNumberOfObjectives() { return objectives.length; } public Objective get(int index) { return objectives[index]; } public Iterator<Objective> iterator() { return new ObjectivesIterator(objectives); } private static class ObjectivesIterator implements Iterator<Objective> { private final Objective[] objectives; private int current = -1; public ObjectivesIterator(Objective[] objectives) { this.objectives = objectives; } public boolean hasNext() { return current + 1 < objectives.length; } public Objective next() { if (!hasNext()) { throw new NoSuchElementException(); } return objectives[++current]; } public void remove() { throw new UnsupportedOperationException(); } } } <file_sep>package ch.brotzilla.neat.math; public class ExtendedGaussianFunction extends ExtendedActivationFunction { public ExtendedGaussianFunction() { super("neat.math.extended.gaussian", "Gaussian", "Returns the gaussian of the argument."); setSynapseDefault(0, 2.5); } @Override protected double _compute(double activation, double[] synapses) { return Math.exp(-activation * activation); } } <file_sep>package ch.brotzilla.cppns.genomes; import com.google.common.base.Preconditions; import ch.brotzilla.cppns.images.ImageType; import ch.brotzilla.neat.evolution.Rng; import ch.brotzilla.neat.genome.Genome; import ch.brotzilla.neat.genome.Link; import ch.brotzilla.neat.genome.Node; import ch.brotzilla.neat.genome.NodeType; import ch.brotzilla.neat.history.HistoryList; import ch.brotzilla.neat.history.LinkInnovation; import ch.brotzilla.neat.math.ActivationFunction; public class BasicGenomeGenerator extends AbstractGenomeGenerator { private int minHiddenNodes = 1, maxHiddenNodes = 3, minLinksPerNode = 1, maxLinksPerNode = 6; private double recurrentLinkProbability = 0.1, synapseLinkProbability = 0.1; public BasicGenomeGenerator(HistoryList historyList, ActivationFunctionProvider activationFunctionProvider, ActivationFunction outputActivationFunction) { super(historyList, activationFunctionProvider, outputActivationFunction); } public BasicGenomeGenerator(HistoryList historyList, ActivationFunctionProvider activationFunctionProvider) { super(historyList, activationFunctionProvider, null); } public int getMinHiddenNodes() { return minHiddenNodes; } public void setMinHiddenNodes(int value) { Preconditions.checkArgument(value > 0, "The parameter 'value' has to be greater than zero"); minHiddenNodes = value; } public int getMaxHiddenNodes() { return maxHiddenNodes; } public void setMaxHiddenNodes(int value) { Preconditions.checkArgument(value > minHiddenNodes, "The parameter 'value' has to be greater than " + minHiddenNodes); maxHiddenNodes = value; } public void setMinMaxHiddenNodes(int min, int max) { Preconditions.checkArgument(min > 0, "The parameter 'min' has to be greater than zero"); Preconditions.checkArgument(max > minHiddenNodes, "The parameter 'max' has to be greater than " + min); minHiddenNodes = min; maxHiddenNodes = max; } public int getMinLinksPerNode() { return minLinksPerNode; } public void setMinLinksPerNode(int value) { Preconditions.checkArgument(value > 0, "The parameter 'value' has to be greater than zero"); minLinksPerNode = value; } public int getMaxLinksPerNode() { return maxLinksPerNode; } public void setMaxLinksPerNode(int value) { Preconditions.checkArgument(value > minLinksPerNode, "The parameter 'value' has to be greater than " + minLinksPerNode); maxLinksPerNode = value; } public void setMinMaxLinksPerNode(int min, int max) { Preconditions.checkArgument(min > 0, "The parameter 'min' has to be greater than zero"); Preconditions.checkArgument(max > minLinksPerNode, "The parameter 'max' has to be greater than " + min); minLinksPerNode = min; maxLinksPerNode = max; } public double getRecurrentLinkProbability() { return recurrentLinkProbability; } public void setRecurrentLinkProbability(double value) { Preconditions.checkArgument(value >= 0, "The parameter 'value' has to be greater than zero"); recurrentLinkProbability = value; } public double getSynapseLinkProbability() { return synapseLinkProbability; } public void setSynapseLinkProbability(double value) { Preconditions.checkArgument(value >= 0, "The parameter 'value' has to be greater than zero"); synapseLinkProbability = value; } public Genome generate(ImageType imageType, Rng rng) { final HistoryList h = getHistoryList(); final ActivationFunction outFunc = getOutputActivationFunction(); final int numInputNodes = 2; final int numHiddenNodes = minHiddenNodes + rng.nextInt(maxHiddenNodes - minHiddenNodes + 1); final int numOutputNodes = imageType.getPatternGeneratorOutputSize(); final int numNodes = numInputNodes + numHiddenNodes + numOutputNodes; final int numActivationFunctions = numHiddenNodes + (outFunc == null ? numOutputNodes : 0); final int[] innovations = new int[numNodes]; final Genome result = new Genome(); final ActivationFunction[] activationFunctions = provideActivationFunctions(numActivationFunctions, rng); int nextFunc = 0; for (int i = 0; i < numInputNodes; i++) { final int innovation = h.getInputNeuronInnovationNumber(i); innovations[i] = innovation; result.add(new Node(NodeType.Input, innovation)); } for (int i = 0; i < numHiddenNodes; i++) { final int innovation = h.getHiddenNeuronInnovationNumber(i); innovations[numInputNodes + i] = innovation; result.add(new Node(NodeType.Hidden, innovation, activationFunctions[nextFunc++])); } for (int i = 0; i < numOutputNodes; i++) { final int innovation = h.getOutputNeuronInnovationNumber(i); innovations[numInputNodes + numHiddenNodes + i] = innovation; result.add(new Node(NodeType.Output, innovation, outFunc == null ? activationFunctions[nextFunc++] : outFunc)); } for (int i = numInputNodes; i < numNodes; i++) { final int numLinks = minLinksPerNode + rng.nextInt(maxLinksPerNode - minLinksPerNode + 1); for (int j = 0; j < numLinks; j++) { final Node targetNode = result.getNodeByInnovation(innovations[i]); final int numSynapses = targetNode.getSynapseDefaults().length; final int targetSynapse = numSynapses > 1 && rng.nextDouble() < synapseLinkProbability ? 1 + rng.nextInt(numSynapses - 1) : 0; final int sourceNode = rng.nextDouble() < recurrentLinkProbability ? innovations[i + rng.nextInt(numNodes - i)] : innovations[rng.nextInt(i)]; final LinkInnovation linkInnovation = h.getLinkInnovation(sourceNode, targetNode.getInnovationNumber(), targetSynapse); if (result.getLinkByInnovation(linkInnovation.getLinkInnovationNumber()) == null) { final Link link = new Link(linkInnovation); link.setWeight(rng.nextDouble() * 3 - 1.5); result.add(link); } } } return result; } } <file_sep>package ch.brotzilla.neat; public class Debug { private Debug() {} /** * Enables additional integrity checks. <br> * Such checks are only there for debugging and are not part of the normal functionality of a class or method. */ public static final boolean EnableIntegrityChecks = true; } <file_sep>package ch.brotzilla.neat.evolution; public interface EvaluationStrategy { void evaluate(Specimen specimen, EvolutionConfig config); } <file_sep>package ch.brotzilla.neat.genome.index; import ch.brotzilla.neat.genome.Link; import ch.brotzilla.neat.genome.Node; public interface IndexStrategy { boolean indexBiasNode(); boolean indexInputNodes(); boolean indexHiddenNodes(); boolean indexOutputNodes(); boolean indexLinks(); int nextBiasIndex(Node node); int nextInputIndex(Node node); int nextHiddenIndex(Node node); int nextOutputIndex(Node node); int nextLinkIndex(Link link); } <file_sep>package ch.brotzilla.neat.evolution.speciation; import java.util.Arrays; import gnu.trove.impl.Constants; import gnu.trove.map.TIntDoubleMap; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.hash.TIntDoubleHashMap; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.procedure.TIntDoubleProcedure; import gnu.trove.procedure.TIntObjectProcedure; import ch.brotzilla.neat.genome.Genome; import ch.brotzilla.neat.genome.Link; import ch.brotzilla.neat.genome.Node; import com.google.common.base.Preconditions; public class Centroid { private final TIntObjectMap<double[]> nodes; private final TIntDoubleMap links; Centroid(TIntObjectMap<double[]> nodes, TIntDoubleMap links) { Preconditions.checkNotNull(nodes, "The parameter 'nodes' must not be null"); Preconditions.checkNotNull(links, "The parameter 'links' must not be null"); this.nodes = nodes; this.links = links; } public Centroid(Genome genome) { Preconditions.checkNotNull(genome, "The parameter 'genome' must not be null"); nodes = new TIntObjectHashMap<double[]>(); links = new TIntDoubleHashMap(); for (final Node node : genome) { nodes.put(node.getInnovationNumber(), node.copySynapseDefaults()); } for (final Link link : genome.getLinks()) { links.put(link.getInnovationNumber(), link.getWeight()); } } public Centroid(Centroid source) { Preconditions.checkNotNull(source, "The parameter 'source' must not be null"); final TIntObjectMap<double[]> n = new TIntObjectHashMap<double[]>(Constants.DEFAULT_CAPACITY, Constants.DEFAULT_LOAD_FACTOR, 0); final TIntDoubleMap l = new TIntDoubleHashMap(Constants.DEFAULT_CAPACITY, Constants.DEFAULT_LOAD_FACTOR, 0, Double.NaN); source.nodes.forEachEntry(new TIntObjectProcedure<double[]>() { public boolean execute(int key, double[] value) { n.put(key, Arrays.copyOf(value, value.length)); return true; } }); source.links.forEachEntry(new TIntDoubleProcedure() { public boolean execute(int key, double value) { l.put(key, value); return true; } }); this.nodes = n; this.links = l; } public double distance(Genome genome) { Preconditions.checkNotNull(genome, "The parameter 'genome' must not be null"); double result = 0; for (final Node node : genome) { if (node.getType().isInputNode()) continue; final double[] a = node.getSynapseDefaults(), b = nodes.get(node.getInnovationNumber()); if (b == null) { for (int i = 0; i < a.length; i++) { result += a[i] * a[i]; } } else { Preconditions.checkState(a.length == b.length, "Internal Error: Unable to compute distance"); for (int i = 0; i < a.length; i++) { final double d = a[i] - b[i]; result += d * d; } } } for (final Link link : genome.getLinks()) { final double a = link.getWeight(); if (links.containsKey(link.getInnovationNumber())) { final double b = links.get(link.getInnovationNumber()); final double d = a - b; result += d * d; } else { result += a * a; } } return result; } @Override public Centroid clone() { return new Centroid(this); } }
9b3738ae42a5697bd5cf7458d7f2826d0bd5dad5
[ "Markdown", "Java", "Maven POM" ]
41
Java
ManuelBrotz/brotzilla-neat
691c977424ec41806c2f8792e84f99cffbbbac7d
926359154b5f985dd0063132cfe55adffb43b34e
refs/heads/master
<file_sep>require 'spec_helper' describe Event do before(:each) do @event = build(:event) end it "has an facebook event id" do @event.should respond_to(:fid) end it "has start time" do @event.should respond_to(:start_at) end it "has end time" do @event.should respond_to(:end_at) end it "has event calendar" do Event.included_modules.should include(EventCalendar::InstanceMethods) end it "belongs to an user" do @event.should respond_to(:user) end it "belongs to a city" do @event.should respond_to(:city) end context "validations" do it "requires a city" do @event.city = nil @event.should_not be_valid @event.errors[:city].should include(i18n 'errors.messages.blank') end it "requires an event facebook id" do @event.fid = nil @event.should_not be_valid @event.errors[:fid].should include(i18n 'errors.messages.blank') end it "requires a start day" do @event.start_at = nil @event.should_not be_valid @event.errors[:start_at].should include(i18n 'errors.messages.blank') end it "validates that start day is not greater than end day" do @event.start_at = Date.today @event.end_at = Date.today - 1 @event.should_not be_valid @event.errors[:end_at].should include(i18n 'errors.messages.event.end_before_start') end it "defaults end date day to start day, if none given" do @event.start_at = DateTime.civil(2011, 1, 1) @event.end_at = nil @event.save.should be_true @event.end_at.should == DateTime.civil(2011, 1, 1) end it "tries to guess if the event is really multiday and limits it" do @event.start_at = DateTime.parse('3rd Feb 2012 08:00:00 PM') @event.end_at = DateTime.parse('4th Feb 2012 06:00:00 AM') #shouldn`t coun't as multiday event @event.save.should be_true @event.end_at.should be <= DateTime.parse('4th Feb 2012 11:59:00 PM') end end context "given it receives valid attributes" do it "should save successfully" do @event.save.should == true end end context "tags" do before do create(:event, :fid => '41', :tag_list => "first, 2, four, three, rock, last") end specify "should retain inserted order" do Event.find_by_fid(41).tag_list.should == ["first", "2", "four", "three", "rock", "last"] end end end <file_sep>class RenameUserToUserId < ActiveRecord::Migration def up rename_column :events, :user, :user_id end def down rename_column :events, :user_id, :user end end <file_sep>require 'spec_helper' describe TransientEvent do before do @model = TransientEvent.new end it_behaves_like "ActiveModel" it "allows [] access to attributes" do lambda { TransientEvent.new[:x] }.should_not raise_exception(NoMethodError) end end <file_sep>class OmniauthUser < ActiveRecord::Migration def up create_table :users, :force => true do |t| t.string :email t.boolean :active, :default => true t.string :name t.string :provider t.string :uid t.string :oauth_token t.datetime :oauth_expires_at t.datetime :last_request_at t.datetime :current_login_at t.datetime :last_login_at t.string :current_login_ip t.string :last_login_ip t.string :persistence_token t.timestamps end end def down create_table "users", :force => true do |t| t.integer "facebook_uid", :limit => 8 t.string "access_token" t.string "email" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.string "persistence_token" t.integer "login_count", :default => 0, :null => false t.integer "failed_login_count", :default => 0, :null => false t.datetime "last_request_at" t.datetime "current_login_at" t.datetime "last_login_at" t.string "current_login_ip" t.string "last_login_ip" t.boolean "active" t.integer "location_id", :limit => 8 end end end <file_sep>//TODO: use CSS instead //$(document).ready(function(){ // // $(document).on("mouseenter mouseleave", ".label", function(){ // $(this).toggleClass("hover"); // }); // //}); <file_sep>class ActiveRecord::Base def self.most_recent_updated_at select("updated_at").order("updated_at DESC").limit(1).first.try(:updated_at) end def self.most_recent_created_at select("created_at").order("created_at DESC").limit(1).first.try(:created_at) end end <file_sep>class User < ActiveRecord::Base acts_as_authentic do |c| c.session_class = Session end #associations has_many :events #validations validates :uid, :presence => true validates :oauth_token, :presence => true validates :email, :presence => true, :format => {:with => Authlogic::Regex.email, :message => I18n.t('errors.messages.email_invalid')} def self.from_omniauth(auth) where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user| user.email = auth.info.email user.provider = auth.provider user.uid = auth.uid user.name = auth.info.name user.oauth_token = auth.credentials.token user.oauth_expires_at = Time.at(auth.credentials.expires_at) user.save! end end end <file_sep>root = "/home/ubuntu/apps/fubuia/current" working_directory root pid "#{root}/tmp/pids/unicorn.pid" stderr_path "#{root}/log/unicorn.log" stdout_path "#{root}/log/unicorn.log" listen "/tmp/unicorn.fubuia.sock" worker_processes 2 timeout 30 <file_sep># coding: UTF-8 class EventsController < ApplicationController caches_action :show, :cache_path => Proc.new {|c| { :xhr => request.xhr? }.merge c.params }, :expires_in => 3.hours def show @event_db = Event.find(params[:id]) @graph = Koala::Facebook::API.new(app_access_token) @multiquery = @graph.fql_multiquery({"event"=>"select eid, name, creator, privacy, pic_small, pic_big, location, description, venue, start_time, end_time, attending_count from event where eid = #{@event_db.fid}","creator"=>"select name, pic_small, profile_url from user where uid in (select creator from #event)"}) @event = FacebookEvent.new(@multiquery['event'][0]) @creator = TransientUser.new(@multiquery["creator"][0]) if @multiquery["creator"][0] render :partial => "show", :layout => false end def new #Explanation about the process render :file => "/events/new" end def start_import require_login! @graph = Koala::Facebook::API.new(current_user.oauth_token) @events_data_from_fql = @graph.fql_query("select eid, name, creator, privacy, pic_small, pic_big, location, venue, start_time, end_time from event where eid in (SELECT eid FROM event_member WHERE uid=me())") @events = @events_data_from_fql.map { |efql| FacebookEvent.new(efql)} #@events.reject! {|e| e.creator != current_user.facebook_uid } ##reject events not created by this user @events.reject! {|e| Time.zone.parse(e.start_time) < Time.now } #XXX danger ##reject past events @events.reject! {|e| e.privacy.upcase != "OPEN"} #reject private events @events.sort_by! {|e| e.start_time} end def import require_login! raise ActionController::RoutingError.new('Not found') if params[:eid].blank? @eid = params[:eid] #@graph = Koala::Facebook::API.new(app_access_token) @graph = Koala::Facebook::API.new(current_user.oauth_token) @multiquery = @graph.fql_multiquery({"event"=>"select eid, name, creator, privacy, pic_small, pic_big, location, venue, start_time, end_time from event where eid = #{@eid}","creator"=>"select name, pic_small, profile_url from user where uid in (select creator from #event)"}) @event = FacebookEvent.new( @multiquery["event"][0] ) @creator = TransientUser.new( @multiquery["creator"][0] ) #TODO: resolve this shit raise ActionController::RoutingError.new("Esse evento é privado!") if @event.privacy != "OPEN" #reject private events # raise ActionController::RoutingError.new('Esse evento já passou!') if @event.end_time < Time.now.to_i #reject past events XXX danger # raise ActionController::RoutingError.new("Esse evento não é seu!") if @event.creator != current_user.facebook_uid #reject events not created by this user #@event_db = Event.find_or_initialize_by_fid(@event.eid) #TODO: why keep this? #@event_db.attributes = {:user => current_user, :city => @city, :start_at => Time.at(@event.start_time).to_datetime, :end_at => Time.at(@event.end_time).to_datetime } #@event_db.attributes = { :active => false } unless @event_db.active? #raise UnexpectedException unless @event_db.save if request.xhr? render :partial => "import", :layout => false end end #TODO possible security flaw here def create require_login! @graph = Koala::Facebook::API.new(current_user.oauth_token) @multiquery = @graph.fql_multiquery({"event"=>"select eid, name, creator, privacy, pic_small, pic_big, location, description, venue, start_time, end_time from event where eid = #{params[:id]}","creator"=>"select name, pic_small, profile_url from user where uid in (select creator from #event)"}) @event = FacebookEvent.new( @multiquery["event"][0] ) @creator = TransientUser.new( @multiquery["creator"][0] ) @event_db = Event.find_or_initialize_by_fid(params[:id]) @event_db.attributes = {:user => current_user, :city => @city, :start_at => Time.zone.parse(@event.start_time.to_s), :end_at => Time.zone.parse(@event.end_time.to_s)} @event_db.tag_list = params[:event][:tag_list] if @event_db.save @event_db.update_attribute(:active, true) flash[:notice] = "Sucesso :)" render :action => "show" else #OPTIMIZE flash[:error] = "Puts! Deu algum problema... tenta denovo, se não resolver me avise plz." render :action => "import" end end def edit require_login! end def update require_login! end def destroy require_login! end end <file_sep>require 'spec_helper' describe "Authentications" do before do Koala::Facebook::API.any_instance.stubs(:fql_query).returns({}) OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new({ :provider => 'facebook', :uid => '1234567', :info => { :email => '<EMAIL>', :name => '<NAME>', }, :credentials => { :token => 'ABCDEF...', :expires_at => 1321747205, :expires => true } }) end context "Logged out" do it "should display login button" do visit '/' page.should have_selector '#login' end end context "Logging in" do context "if user has allowed access to app" do it "redirects to root with the user signed in" do visit login_path page.should have_content i18n('messages.login_success') end end context "Logged in" do before(:each) do visit login_path end specify "page should display the users name" do visit '/' page.should have_content "<NAME>" end specify "page should display a logout link" do visit '/' page.should have_selector "#logout" end context "Logging out" do specify "clicking on logout should log the user out" do visit '/' click_on 'logout' page.should have_selector "#login" page.should have_content i18n('messages.logout_success') end end end end end <file_sep>#coding: utf-8 class CalendarController < ApplicationController def index #used by calendar helper @month = Time.zone.now.month @year = Time.zone.now.year #// lotsa variables @shift = params[:shift].to_i strip_start = Date.today - 3 + @shift strip_end = Date.today + 4 + @shift today = Date.today + @shift # needed so I don't cache wrong shit @tags = Rails.cache.fetch "tags-#{today.to_s}-#{Tagging.most_recent_created_at.to_i}" do Tag.event_tags_for_date_range(Date.today - 3 + @shift, Date.today + 3 + @shift).in_city(@city) end @tag = Tag.find_by_name(params[:tag]) if params[:tag].present? flash[:error] = "Tag não encontrada" if params[:tag].present? && @tag.nil? @events = Rails.cache.fetch "events-#{today.to_s}-#{Event.most_recent_updated_at.to_i}-#{@tag}" do if @tag events = @city.events.for_date_range(strip_start, strip_end + 1).active.tagged_with(@tag) else events = @city.events.for_date_range(strip_start, strip_end + 1).active # ? end query = "select eid, name, description, creator, privacy, pic_small, pic_big, location, venue, start_time, end_time from event where eid in (%s)" % events.map(&:fid).join(',') @graph = Koala::Facebook::API.new(app_access_token) event_hashes = Hash[events.map { |e| [e.fid, e] }] #1 events_from_fql = @graph.fql_query(query) @events = events_from_fql.map do |efql| #2 FacebookEvent.new(efql.merge( event_hashes[efql["eid"]].attributes_for_facebook_event )) unless event_hashes[efql["eid"]].blank? end.compact end @event_strips = Event.create_event_strips(strip_start, strip_end, @events) respond_to do |format| format.html {} format.js {} end end end <file_sep>require 'spec_helper' describe TransientUser do before do @model = TransientUser.new end it_behaves_like "ActiveModel" end <file_sep>module ApplicationHelper def flash_messages flash.collect do |key, msg| content_tag(:div, :id => key, :class => "msg_box msg_#{key}") do msg end end.join.html_safe end def tag_span(tag) if tag.kind_of?(Tag) css_class = "label" css_class << " label-#{tag.css_class}" if tag.css content_tag(:span, :class => css_class) do tag.name end.html_safe end end end <file_sep>require 'tag_extensions' ActionDispatch::Callbacks.to_prepare do ActsAsTaggableOn::Tag.class_eval do include TagExtensions end end <file_sep>require 'ostruct' class TransientEvent < OpenStruct include ActiveModel::Validations include ActiveModel::Conversion extend ActiveModel::Naming def initialize(hash={}) super(hash) end def persisted? false end def to_model self end # EventCalendar uses this form of attribute access # faking AR behaviour def [](attr_name) self.instance_variable_get("@#{attr_name}") end end <file_sep># coding: utf-8 module DummyResponses def events_query JSON('[ { "eid": 105417699523664, "name": "<NAME> - Eu vou!", "description": "OpenBar até o último cliente.", "creator": 1, "privacy": "OPEN", "location": "No mundo inteiro", "venue": { "street": "", "city": "", "state": "", "country": "" }, "start_time": "2012-01-26T22:00:00-02:00", "end_time": "2012-01-26T22:00:00-02:00" }, { "eid": 226420880736785, "name": "<NAME>!", "creator": 100001678599737, "privacy": "OPEN", "location": "Ceará", "venue": { "street": "", "city": "", "state": "", "country": "" }, "start_time": "2012-01-31T07:30:00-02:00", "end_time": "2012-01-31T10:30:00-02:00" }, { "eid": 317163524988819, "name": "<NAME>", "creator": 1, "privacy": "OPEN", "location": "Club 904 (Clube da ASCEB - 904 Sul)", "venue": { "street": "", "city": "", "state": "", "country": "", "latitude": -15.800694566667, "longitude": -47.900688083333, "id": 212762192067615 }, "start_time": "2012-01-29T04:30:00-02:00", "end_time": "2012-01-29T10:30:00-02:00" }, { "eid": 372742442742194, "name": "teste", "creator": 1, "privacy": "SECRET", "location": "Asd photographe", "venue": { "street": "", "city": "", "state": "", "country": "", "latitude": 48.508703720942, "longitude": 2.463682145747, "id": 242509969118609 }, "start_time": "2012-01-26T12:00:00-02:00", "end_time": "2012-01-26T15:00:00-02:00" }, { "eid": 228651767221196, "name": "<NAME>", "creator": 1, "privacy": "SECRET", "location": "SQN 208 Bloco H", "venue": { "street": "", "city": "", "state": "", "country": "" }, "start_time": "2012-01-22T01:00:00-02:00", "end_time": "2012-01-22T05:30:00-02:00" } ]') end def multiquery {"event"=> [{"eid"=>12345, "name"=>"<NAME> - Eu vou!", "description" => "OpenBar até o último cliente.", "creator"=>1, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc4/174576_105417699523664_1684222_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc4/50236_105417699523664_1798087_n.jpg", "location"=>"No mundo inteiro", "venue"=>{"street"=>"", "city"=>"", "state"=>"", "country"=>""}, "start_time"=>"2012-01-26T22:00:00-02:00", "end_time"=>"2012-01-26T22:00:00-02:00"}], "creator"=> [{"name"=>"<NAME>", "pic_small"=> "x.jpg", "profile_url"=>"http://www.facebook.com/breno.salgado"}]} end def fubevents JSON( '[{ "eid": 11, "name": "Good Bye Facebook.", "creator": null, "privacy": "OPEN", "pic_small": "http://profile.ak.fbcdn.net/hprofile-ak-snc6/261178_282928705156573_1060948663_n.jpg", "pic_big": "http://profile.ak.fbcdn.net/hprofile-ak-snc6/261178_282928705156573_1060948663_n.jpg", "location": null, "venue": [ ], "start_time": "2012-10-05", "end_time": null }, { "eid": 22, "name": "Quinta (04/10) 5uinto c/ Wildkats (Hot Creations/Inglaterra)", "creator": 151166391585616, "privacy": "OPEN", "pic_small": "http://profile.ak.fbcdn.net/hprofile-ak-ash4/203561_290935981021454_1452509486_n.jpg", "pic_big": "http://profile.ak.fbcdn.net/hprofile-ak-ash4/203561_290935981021454_1452509486_n.jpg", "location": "Club 904 (Clube da ASCEB - 904 Sul)", "venue": { "id": 212762192067615 }, "start_time": "2012-10-04T22:00:00-0300", "end_time": null }, { "eid": 33, "name": "Tributo ao Led Zeppelin (Whole Lotta Led) & <NAME>", "creator": 100000377043343, "privacy": "OPEN", "pic_small": "http://profile.ak.fbcdn.net/hprofile-ak-snc7/373158_425965267461184_1555052634_n.jpg", "pic_big": "http://profile.ak.fbcdn.net/hprofile-ak-snc7/373158_425965267461184_1555052634_n.jpg", "location": "Velvet Pub", "venue": { "id": 172371102815700 }, "start_time": "2012-10-04", "end_time": null }, { "eid": 44, "name": "COVER NIGHT :: OASIS + THE KILLERS :: DIA 04/10", "creator": 100002340451025, "privacy": "OPEN", "pic_small": "http://profile.ak.fbcdn.net/hprofile-ak-ash4/211101_475839089123532_2038471914_n.jpg", "pic_big": "http://profile.ak.fbcdn.net/hprofile-ak-ash4/211101_475839089123532_2038471914_n.jpg", "location": "ORilley Irish Pub (409 sul)", "venue": { "name": "ORilley Irish Pub (409 sul)" }, "start_time": "2012-10-04", "end_time": null }, { "eid": 55, "name": "LIFE - 29.09 - ** Tributo a Mamonas Assassinas**", "creator": 100002068784255, "privacy": "OPEN", "pic_small": "http://profile.ak.fbcdn.net/hprofile-ak-snc6/276823_278377805595894_1692876072_n.jpg", "pic_big": "http://profile.ak.fbcdn.net/hprofile-ak-snc6/276823_278377805595894_1692876072_n.jpg", "location": "Enchendo Linguica", "venue": { "id": 162013987186580 }, "start_time": "2012-10-29T22:30:00-0300", "end_time": "2012-10-30T05:00:00-0300" }]' ) end [{"eid"=>105417699523664, "name"=>"<NAME> - Eu vou!", "creator"=>770689699, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash3/174576_105417699523664_1684222_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash3/50236_105417699523664_1798087_n.jpg", "location"=>"No mundo inteiro", "venue"=>{"street"=>"", "city"=>"", "state"=>"", "country"=>""}, "start_time"=>"2012-12-21T00:00:00", "end_time"=>"2012-12-21T21:30:00"}, {"eid"=>209093872529307, "name"=>"<NAME>", "creator"=>100001718282505, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/373318_209093872529307_167300439_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/373318_209093872529307_167300439_n.jpg", "location"=>"Brasília", "venue"=>{"id"=>112060958820146}, "start_time"=>"2012-11-17T22:00:00-0200", "end_time"=>nil}, {"eid"=>409054419159603, "name"=>"<NAME> ( Suécia ) em Brasília!!!", "creator"=>580794414, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/276787_409054419159603_1279025964_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/276787_409054419159603_1279025964_n.jpg", "location"=>"Arena Futebol Clube", "venue"=>{"id"=>400754403299330}, "start_time"=>"2012-11-11T21:00:00+0000", "end_time"=>"2012-11-12T02:00:00+0000"}, {"eid"=>143493079124790, "name"=>"<NAME> em Brasília.", "creator"=>100002087911178, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/203533_143493079124790_814593950_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/203533_143493079124790_814593950_n.jpg", "location"=>"Brasília", "venue"=>{"id"=>112060958820146}, "start_time"=>"2012-10-27", "end_time"=>nil}, {"eid"=>472774986066510, "name"=>"Pleiadians", "creator"=>476118485745305, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/373477_472774986066510_941623622_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/373477_472774986066510_941623622_n.jpg", "location"=>"Brasília", "venue"=>{"id"=>112060958820146}, "start_time"=>"2012-10-13T22:00:00-0300", "end_time"=>nil}, {"eid"=>462452360451994, "name"=>"Ritual", "creator"=>1082750743, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/276536_462452360451994_2041926586_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/276536_462452360451994_2041926586_n.jpg", "location"=>nil, "venue"=>[], "start_time"=>"2012-10-13T10:00:00-0300", "end_time"=>"2012-10-14T18:00:00-0300"}, {"eid"=>278377805595894, "name"=>"LIFE - 29.09 - ** Tributo a Mamonas Assassinas**", "creator"=>100002068784255, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/276823_278377805595894_1692876072_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/276823_278377805595894_1692876072_n.jpg", "location"=>"Enchendo Linguica", "venue"=>{"id"=>162013987186580}, "start_time"=>"2012-09-29T22:30:00-0300", "end_time"=>"2012-09-30T05:00:00-0300"}, {"eid"=>374832812584857, "name"=> "::STAGE:: Pink Floyd, Led Zeppelin e The Doors (covers) :: Dia 29/09", "creator"=>100003226216034, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/195775_374832812584857_709941527_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/195775_374832812584857_709941527_n.jpg", "location"=>"Arena Futebol Clube", "venue"=>{"id"=>203531242990250}, "start_time"=>"2012-09-30T01:00:00+0000", "end_time"=>nil}, {"eid"=>361154357299405, "name"=> "PLAY! ** Edição Especial ** comemorando o aniversário dos <NAME>, <NAME>, R@g e Mr. Vicz", "creator"=>100000379203720, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/276733_361154357299405_727239819_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/276733_361154357299405_727239819_n.jpg", "location"=>"Club 904 (Clube da ASCEB - 904 Sul)", "venue"=>{"id"=>212762192067615}, "start_time"=>"2012-09-28T22:30:00-0300", "end_time"=>"2012-09-29T04:30:00-0300"}, {"eid"=>264442383676733, "name"=> "Quinta (27/09) 5uinto c/ <NAME> (Hot Creations/EUA), Hopper e <NAME>", "creator"=>151166391585616, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/276732_264442383676733_379558804_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/276732_264442383676733_379558804_n.jpg", "location"=>"Club 904 (Clube da ASCEB - 904 Sul)", "venue"=>{"id"=>212762192067615}, "start_time"=>"2012-09-27T22:00:00-0300", "end_time"=>nil}, {"eid"=>262027897252207, "name"=>"<NAME>", "creator"=>100002631912270, "privacy"=>"FRIENDS", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/261162_262027897252207_1045732256_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/261162_262027897252207_1045732256_n.jpg", "location"=>"BAR DA TOINHA", "venue"=>{"id"=>191898444193767}, "start_time"=>"2012-09-23T17:00:00-0300", "end_time"=>nil}, {"eid"=>420176171363071, "name"=>"Mixtape - Edição Cinema", "creator"=>1049777208, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/195779_420176171363071_1054064799_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/195779_420176171363071_1054064799_n.jpg", "location"=>"Arena Futebol Clube", "venue"=>{"id"=>400754403299330}, "start_time"=>"2012-09-22T22:00:00-0300", "end_time"=>"2012-09-23T05:00:00-0300"}, {"eid"=>179542028841754, "name"=> "<NAME> e Exploração dos Animais - Weeac Brasília", "creator"=>268512176492431, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/276419_179542028841754_1077961432_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/276419_179542028841754_1077961432_n.jpg", "location"=>"Fonte da Torre de TV de Brasilia", "venue"=>{"id"=>214516298599386}, "start_time"=>"2012-09-22T15:00:00-0300", "end_time"=>"2012-09-22T19:00:00-0300"}, {"eid"=>355802994499151, "name"=>"**** <NAME> <NAME> **** LET'S CLASSIC BABY !!!!!", "creator"=>100000220237313, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/195795_355802994499151_1404063488_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/195795_355802994499151_1404063488_n.jpg", "location"=>"Clube Minas Brasília Tênis Clube", "venue"=>{"id"=>187232997990079}, "start_time"=>"2012-09-22T02:00:00+0000", "end_time"=>nil}, {"eid"=>368603756547880, "name"=>"PLAY!** com dj set de BÁRBARA EUGÊNIA", "creator"=>100000379203720, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/203503_368603756547880_890261331_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/203503_368603756547880_890261331_n.jpg", "location"=>"Club 904 (Clube da ASCEB - 904 Sul)", "venue"=>{"id"=>212762192067615}, "start_time"=>"2012-09-21T22:30:00-0300", "end_time"=>"2012-09-22T04:30:00-0300"}, {"eid"=>371970799539447, "name"=>"<NAME>", "creator"=>100001773230198, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/276548_371970799539447_854659243_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/276548_371970799539447_854659243_n.jpg", "location"=>"Blues Pub", "venue"=>{"id"=>228062383925250}, "start_time"=>"2012-09-21T20:00:00+0200", "end_time"=>nil}, {"eid"=>527227067293029, "name"=> "Quinta (20/09) 5uinto c/ <NAME> (Tronic/Suécia), Uone (LAB/Austrália) e Komka", "creator"=>151166391585616, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/203476_527227067293029_2106948067_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/203476_527227067293029_2106948067_n.jpg", "location"=>"Club 904 (Clube da ASCEB - 904 Sul)", "venue"=>{"id"=>212762192067615}, "start_time"=>"2012-09-21T01:00:00+0000", "end_time"=>nil}, {"eid"=>528435920505051, "name"=>"<NAME>!", "creator"=>153478891439654, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/373463_528435920505051_1710242523_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/373463_528435920505051_1710242523_n.jpg", "location"=>"Cult 22 Rock Bar", "venue"=>{"id"=>108634782560341}, "start_time"=>"2012-09-21T01:00:00+0000", "end_time"=>nil}, {"eid"=>102145739936484, "name"=> "Sábado (15/09) 5uinto & My House apresentam: Inminimax Records & Crunchy Music - 4 anos", "creator"=>151166391585616, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/276944_102145739936484_1485003565_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/276944_102145739936484_1485003565_n.jpg", "location"=>"Ascade", "venue"=>{"id"=>268684499841296}, "start_time"=>"2012-09-15T23:00:00-0300", "end_time"=>nil}, {"eid"=>474703122562064, "name"=>"<NAME>!", "creator"=>1845948167, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/592181_474703122562064_1391707995_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/592181_474703122562064_1391707995_n.jpg", "location"=>"QE 17 Guará II", "venue"=>{"id"=>211584525531131}, "start_time"=>"2012-09-15T22:10:00-0300", "end_time"=>nil}, {"eid"=>424723947574352, "name"=>":: OASIS DAY 2012 :: BRASÍLIA :: 15/09", "creator"=>100002340451025, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc7/373592_424723947574352_980419142_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc7/373592_424723947574352_980419142_n.jpg", "location"=>"Club 904 (Clube da ASCEB - 904 Sul)", "venue"=>{"id"=>212762192067615}, "start_time"=>"2012-09-15T22:00:00-0300", "end_time"=>nil}, {"eid"=>221711854624659, "name"=> "HOJE :: Queens of the Stone Age e The Strokes no GATE'S PUB!!! \\m/", "creator"=>100003436557568, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/592205_221711854624659_1234610015_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/592205_221711854624659_1234610015_n.jpg", "location"=>"Gate's", "venue"=>{"id"=>225915977488908}, "start_time"=>"2012-09-15T22:00:00-0300", "end_time"=>nil}, {"eid"=>219509361509748, "name"=>"<NAME>", "creator"=>623630699, "privacy"=>"SECRET", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/276726_219509361509748_1192967130_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/276726_219509361509748_1192967130_n.jpg", "location"=>"terra da perdição", "venue"=>{"name"=>"terra da perdição"}, "start_time"=>"2012-09-15T22:00:00-0300", "end_time"=>"2012-09-16T04:00:00-0300"}, {"eid"=>188823981221605, "name"=>"<NAME>", "creator"=>1461154272, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/187976_188823981221605_1714351879_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/187976_188823981221605_1714351879_n.jpg", "location"=>"fazenda encontro das águas", "venue"=>{"street"=>"", "city"=>"", "state"=>"", "country"=>""}, "start_time"=>"2012-09-15T16:00:00", "end_time"=>"2012-09-16T16:00:00"}, {"eid"=>434005603302263, "name"=>"<NAME>", "creator"=>1787157911, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/373350_434005603302263_1076695862_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/373350_434005603302263_1076695862_n.jpg", "location"=>"UnB - Teatro de Arena", "venue"=>{"id"=>153641591370997}, "start_time"=>"2012-09-14T22:45:00-0300", "end_time"=>"2012-09-15T04:00:00-0300"}, {"eid"=>104143809739793, "name"=> "PLAY!** com dj set de <NAME> & <NAME> (ex-Bois de Gerião/DF)", "creator"=>100000379203720, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/276819_104143809739793_524216595_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/276819_104143809739793_524216595_n.jpg", "location"=>"Club 904 (Clube da ASCEB - 904 Sul)", "venue"=>{"id"=>212762192067615}, "start_time"=>"2012-09-14T22:30:00-0300", "end_time"=>"2012-09-15T04:30:00-0300"}, {"eid"=>415347068525724, "name"=> "<NAME> - <NAME> (14/09) - Edição de Aniversariantes do Mês na AABB", "creator"=>184910224918656, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/373084_415347068525724_1817854547_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/373084_415347068525724_1817854547_n.jpg", "location"=>"AABB - Brasília", "venue"=>{"id"=>120049138070742}, "start_time"=>"2012-09-14T22:00:00-0300", "end_time"=>"2012-09-15T05:00:00-0300"}, {"eid"=>479283122090259, "name"=>"<NAME>!!!!", "creator"=>100004242275716, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/276879_479283122090259_1666111214_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/276879_479283122090259_1666111214_n.jpg", "location"=>"UnB Subsolo - ICC SUL (ao lado do CANTRO E CAQUI)", "venue"=>{"name"=>"UnB Subsolo - ICC SUL (ao lado do CANTRO E CAQUI)"}, "start_time"=>"2012-09-14T22:00:00-0300", "end_time"=>nil}, {"eid"=>412467852135173, "name"=> "<NAME> 14/09 - Brasília - <NAME> (SP), Bad Motors (SP) e Os Dinamites", "creator"=>248975248507501, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/276891_412467852135173_1185882504_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/276891_412467852135173_1185882504_n.jpg", "location"=>"Funarte", "venue"=>{"id"=>213170942040282}, "start_time"=>"2012-09-14T20:00:00-0300", "end_time"=>nil}, {"eid"=>118663434947435, "name"=>"Quinta (13/09) 5uinto c/ Maxxi Soundsystem (Hot Waves/Inglaterra)", "creator"=>151166391585616, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/211080_118663434947435_230537516_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-snc6/211080_118663434947435_230537516_n.jpg", "location"=>"Club 904 (Clube da ASCEB - 904 Sul)", "venue"=>{"id"=>212762192067615}, "start_time"=>"2012-09-13T22:00:00-0300", "end_time"=>nil}, {"eid"=>113777585438869, "name"=>"MOBIL coleta de eletrônicos na UNB", "creator"=>467520383271680, "privacy"=>"OPEN", "pic_small"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/276736_113777585438869_900678253_t.jpg", "pic_big"=> "http://profile.ak.fbcdn.net/hprofile-ak-ash4/276736_113777585438869_900678253_n.jpg", "location"=>"Minhocão - Unb", "venue"=>{"id"=>186566614767362}, "start_time"=>"2012-09-13T19:00:00-0300", "end_time"=>"2012-09-14T02:00:00-0300"}] end <file_sep># coding: UTF-8 # This file is copied to spec/ when you run 'rails generate rspec:install' ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' require 'rspec/autorun' require 'test_notifier/runner/rspec' require 'capybara/rspec' require 'authlogic/test_case' # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f} RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods config.include Capybara::DSL # ## Mock Framework # # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line: # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/fixtures" # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. config.use_transactional_fixtures = true # If true, the base class of anonymous controllers will be inferred # automatically. This will be the default behavior in future versions of # rspec-rails. config.infer_base_class_for_anonymous_controllers = false Capybara.javascript_driver = :webkit #config.filter_run_excluding :js => true #load seed config.before(:suite) do load "#{Rails.root}/db/seeds.rb" end config.before type: :request do OmniAuth.config.test_mode = true Koala::Facebook::API.any_instance.stubs(:fql_query).returns({}) OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new({ :provider => 'facebook', :uid => '1234567', :info => { :email => '<EMAIL>', :name => '<NAME>', }, :credentials => { :token => 'ABCDEF...', :expires_at => 1321747205, :expires => true } }) end config.around(:each, :subdomain => 'rio') do |example| Capybara.current_session.reset! Capybara.default_host = 'http://rio.example.com' example.run Capybara.default_host = 'http://www.example.com' Capybara.current_session.reset! end config.around(:each, :subdomain => 'brasilia') do |example| Capybara.current_session.reset! Capybara.default_host = 'http://brasilia.example.com' example.run Capybara.default_host = 'http://www.example.com' Capybara.current_session.reset! end # WebServices response mocks config.include DummyResponses end class ActiveRecord::Base mattr_accessor :shared_connection @@shared_connection = nil def self.connection @@shared_connection || retrieve_connection end end ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection def i18n(*params) I18n.t(*params) end ActiveSupport::Deprecation.behavior = Proc.new { |message, callstack| raise message + "\n" + callstack.join("\n ") } <file_sep># encoding: utf-8 require 'spec_helper' describe "Home" do before do @event = create(:event, :fid => 12345678, :active => true, :start_at => Date.today, :end_at => Date.today) @event2 = create(:event, :fid => 666, :active => false, :start_at => Date.today, :end_at => Date.today) @facebook_events = [{"name"=>"Evento 1", "eid"=>12345678}, {"name" => "Evento 2", "eid" => 666}] Koala::Facebook::API.any_instance.stubs(:fql_query).returns(@facebook_events) end describe "menus" do it "should have menu 'contato'" do visit '/' page.should have_selector "#contato" end describe "como funciona" do it "should have menu 'como funciona'" do visit '/' page.should have_selector "#a-como-funciona" page.should have_content i18n 'pages.root.menu.como_funciona' end specify "it points to 'como funciona' section" do visit '/' page.find_link("a-como-funciona")["href"].should match /#como-funciona/ end end end describe "sections" do describe "#como funciona" do it "should exist" do visit '/' page.should have_content i18n 'pages.root.step1' page.should have_content i18n 'pages.root.step2' page.should have_content i18n 'pages.root.step3' page.should have_content i18n 'pages.root.step1_d' page.should have_content i18n 'pages.root.step2_d' page.should have_content i18n 'pages.root.step3_d' end end end it "should display the fast description" do visit '/' page.should have_content i18n 'pages.root.fastdesc_html' end it "should display city name" do visit '/' page.should have_content "Brasília" end it "should display todays date" do Date.stubs(:today).returns(Date.civil(2011, 1, 1)) visit '/' page.should have_content "1 de Janeiro, 2011" end it "should display the weekly calendar" do visit '/' page.should have_selector '.ec-calendar' ['Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb', 'Dom'].each do |day| page.should have_content day end end it "should display new event button" do visit '/' decoded_str = HTMLEntities.new.decode(i18n('pages.events.new')) page.body.should have_content decoded_str page.find_link(decoded_str)["href"].should == new_event_path end context "when there's events" do specify "active events should appear on the calendar" do visit '/' page.find('.ec-calendar').should have_content 'Evento 1' end specify "non active events should not appear on the calendar" do visit '/' page.find('.ec-calendar').should_not have_content 'Evento 2' end context "when event's have tags" do before do @event.tag_list = '1,2' @event2.tag_list = '3' @event2.active = true @event.save @event2.save end it "should display tags from the events" do visit '/' page.should have_link '1' page.should have_link '2' page.should have_link '3' end context "clicking on a tag" do before do visit '/' page.should have_content "Evento 2" end it "should filter events through that tag" do click_on '1' page.should_not have_content "Evento 2" page.should have_content i18n('pages.tags.filtering', :tag => '1') page.should have_link 'x' end specify "clicking on 'limpar' should get back at the original state" do click_on '1' page.should_not have_content "Evento 2" click_link 'x' page.should have_content "Evento 2" end end end end end <file_sep>require 'spec_helper' describe City do it "requires a name" do City.new(:name => nil).should_not be_valid end it "requires a subdomain" do City.new(:subdomain => nil).should_not be_valid end it "has many events" do City.new.should respond_to(:events) end end <file_sep># coding: UTF-8 module TagExtensions def self.included(base) base.class_eval do attr_accessible :css belongs_to :parent, :class_name => "ActsAsTaggableOn::Tag", :foreign_key => 'parent_id' extend ClassMethods include InstanceMethods default_scope group("tags.id, tags.name") scope :join_events, lambda { joins(:taggings).joins("INNER JOIN events ON events.id = taggings.taggable_id").where("taggings.taggable_type = 'Event'") } scope :for_date_range, lambda {|start_at, end_at| where([ "taggings.taggable_type = 'Event' AND events.start_at BETWEEN :start_at AND :end_at OR events.end_at BETWEEN :start_at AND :end_at", { :start_at => start_at.at_beginning_of_day, :end_at => end_at.end_of_day } ]) } scope :event_tags_for_date_range, lambda { |start_at, end_at| join_events().for_date_range(start_at, end_at)} scope :in_city, lambda {|city| where(["events.city_id = ?", city])} end end module ClassMethods #Useless right now, currently no use for counts, hard sql, not scoped def tag_counts_for_date_range(context, start_at, end_at) sql = [ "SELECT tags.*, COUNT(*) AS count FROM tags LEFT OUTER JOIN taggings ON tags.id = taggings.tag_id AND taggings.context = :context INNER JOIN events ON events.id = taggings.taggable_id WHERE taggings.taggable_type = 'Event' AND events.start_at BETWEEN :start_at AND :end_at OR events.end_at BETWEEN :start_at AND :end_at GROUP BY tags.id, tags.name HAVING COUNT(*) > 0", { :context => context, :start_at => start_at.at_beginning_of_day, :end_at => end_at.end_of_day }] find_by_sql(sql) end end module InstanceMethods def css_class if self.css self.name.downcase.gsub(' ', '-') elsif self.parent.present? self.parent.css_class else nil end end end end <file_sep>/* Reviewer JS by <NAME> / DesignCrumbs.com <![CDATA[ */ var J = jQuery.noConflict(); J(document).ready(function() { // Childen Flyout on Menu function mainmenu() { J("#pagemenu ul li ul, #category_menu ul li ul").css({ display: "none" }); // Opera Fix J("#pagemenu ul li, #category_menu ul li").hover(function() { J(this).find('ul:first').css({ visibility: "visible", display: "none" }).show(300); }, function() { J(this).find('ul:first').css({ visibility: "hidden" }); }); } J(document).ready(function() { mainmenu(); }); // Animates the soc nets on hover J("#socnets").delegate("img", "mouseover mouseout", function(e) { if (e.type == 'mouseover') { J("#socnets a img").not(this).dequeue().animate({ opacity: "0.3" }, 300); } else { J("#socnets a img").not(this).dequeue().animate({ opacity: "1" }, 300); } }); // Animates the Sticky Posters on Hover J(function() { J('.featured_post').hover(function() { J(this).find('img.featured_poster').animate({ top: '-9px' }, { queue: false, duration: 200 }); J(this).find('.contest').animate({ top: '7px' }, { queue: false, duration: 200 }); }, function() { J(this).find('img.featured_poster').animate({ top: '9px' }, { queue: false, duration: 400 }); J(this).find('.contest').animate({ top: '25px' }, { queue: false, duration: 400 }); }); }); // Index poster hovers J(document).ready(function() { J('.poster_info_wrap').hover(function() { J(this).children('.description').stop().fadeTo(200, .9); }, function() { J(this).children('.description').stop().fadeTo(200, 0); }); }); }); /* ]]> */<file_sep># coding: UTF-8 class TermRelevancy def initialize(text, words=[]) @text = text @words = words end def rank result = [] for matchthis in @words matchthis.gsub! '-', ' ' h = {frequency:0, tag:matchthis} @text.scan(Regexp.new(matchthis, Regexp::IGNORECASE)) do |match| h[:frequency] += 1 end result << h end max = result.map { |e| e[:frequency]}.max result.each {|h| h[:relevancy] = if max == 0 0 else h[:frequency].to_f / max end } result end end <file_sep>#coding: UTF-8 FactoryGirl.define do factory :user do uid '12345678' oauth_token '<PASSWORD>' sequence(:email) {|n| "<EMAIL>"} end factory :event do fid '12345678' association :user city_id { City.find_by_subdomain('brasilia').id } start_at Date.today active true end factory :city do name 'Brasília' subdomain 'brasilia' end factory :tag do name 'tag' end end <file_sep>module AutoImporters class FubuiaImporter def self.run(options = {}) logger.info "Importer running" # Set user fubuia = User.find_by_email "<EMAIL>" unless fubuia.present? logger.warn "PERFIL dO <NAME>" return end #from = options[:from] || Date.today #to = options[:to] || 2.weeks.from_now graph = Koala::Facebook::API.new(fubuia.oauth_token) # get today's timeprint so we don't grab old events since = Time.now.to_i all = graph.fql_query( "SELECT eid, name, description, creator, privacy, pic_small, pic_big, location, venue, start_time, end_time FROM event WHERE eid IN (SELECT eid FROM event_member WHERE uid=me() AND start_time > #{since})" ) # events we got from FB events = all.map { |efql| FacebookEvent.new(efql)} all_db_events_fids = Event.all.map(&:fid) #reject events we already have events.reject! {|e| all_db_events_fids.include? e.eid } #reject past events events.reject! {|e| Time.zone.parse(e.start_time) < Date.today.to_time } #reject private events events.reject! {|e| e.privacy.upcase != "OPEN" rescue true} city = City.first require 'term_relevancy' hash_log = {:returned => events.count, :created => []} events.each do |event| if Event.create_from_facebook(event, fubuia, city) hash_log[:created] << 1 end end logger.info "Done." logger.info "Returned: #{hash_log[:returned]}" logger.info "Created: #{hash_log[:created].count}" end def self.logger logfile = File.open('./log/imports.log', 'a') logfile.sync = true log = ImporterLogger.new(logfile) end end class ImporterLogger < Logger def format_message(severity, timestamp, progname, msg) "#{timestamp.to_formatted_s(:db)} #{severity} #{msg}\n" end end end <file_sep>require 'spec_helper' describe Tag do before(:each) do @tag = Tag.new end it "has Parent Tag" do @tag.should respond_to(:parent) end context "validations" do it "validates presence of name" do tag = Tag.new tag.should_not be_valid tag.errors[:name].should include(i18n('errors.messages.blank')) end end describe "#css_class" do context ":CSS => true" do it "returns the tag name downcased, without spaces" do t = Tag.new(:name => "mIMi tuTu", :css => true) t.css_class.should == "mimi-tutu" end end context ":CSS => false" do specify "returns nil if no parent" do Tag.new(:name => "naorock", :css => false).css_class.should be_nil end specify "returns parent's #css_class if parent" do parent = create(:tag, :css => true, :name => "rock") child = create(:tag, :css => false, :parent => parent) child.css_class.should == "rock" end end it "returns the parent tag css_class if 'css' if false" do parent = create(:tag, :name => "Rock") child = create(:tag, :name => "Stoner Rock") end end describe ".event_tags_for_date_range scope" do it "should find any tags in events overlaping the range" do @event = create(:event, :tag_list => "1, 2, in", :start_at => Date.today, :end_at => Date.today + 1) @event2 = create(:event, :tag_list => "out", :start_at => Date.today, :end_at => Date.today) @tags = Tag.event_tags_for_date_range(Date.today + 1, Date.today + 3) @tags.should include(Tag.find_by_name("in")) @tags.should_not include(Tag.find_by_name("out")) end end describe ".tag_counts_for_date_range" do it "should find any tags in events overlaping the range" do @event = create(:event, :tag_list => "1, 2, in", :start_at => Date.today, :end_at => Date.today + 1) @event2 = create(:event, :tag_list => "out", :start_at => Date.today, :end_at => Date.today) @tag_counts = Tag.tag_counts_for_date_range("tags", Date.today + 1, Date.today + 3) @tag_counts.should include(Tag.find_by_name("in")) @tag_counts.should_not include(Tag.find_by_name("out")) end context "given there's 3 events today, one with '1' tag, two with '2' tag, three with '3' tag, plus one event tomorrow with tag 3 and one event yesterday with tag 1 and I ask for the tags and counts for TODAY" do before do @event = create(:event, :tag_list => "1, 2, 3", :start_at => Date.today) @event2 = create(:event, :tag_list => "2, 3", :start_at => Date.today) @event3 = create(:event, :tag_list => "3", :start_at => Date.today) @event4 = create(:event, :tag_list => "1", :start_at => Date.today - 1) @event5 = create(:event, :tag_list => "3", :start_at => (Date.today + 1)) @tag_counts = Tag.tag_counts_for_date_range("tags", Date.today, Date.today) end it "returns an array with 3 tags" do @tag_counts.size.should == 3 end it "tag 1 should have 1 as count" do @tag_counts[0].count.should == 1 end it "tag 2 should have 2 as count" do @tag_counts[1].count.should == 2 end it "tag 3 should have 3 as count" do @tag_counts[2].count.should == 3 end end end end <file_sep>source 'http://rubygems.org' gem 'rails' # Bundle edge Rails instead: # gem 'rails', :git => 'git://github.com/rails/rails.git' #gem 'unicorn' #gem 'pg' gem 'rack-escaped-fragment', :git => '<EMAIL>:salgadobreno/rack-escaped-fragment.git' #gem 'hitchens' gem 'activeadmin' gem 'jquery-ui-rails' #for activeadmin gem 'omniauth-facebook' gem 'whenever', :require => false gem 'mysql2' gem 'execjs' gem 'therubyracer' gem 'koala' gem 'authlogic' gem 'twitter-bootstrap-rails' gem 'acts-as-taggable-on', :git => "http://github.com/mbleigh/acts-as-taggable-on.git" #removing git:// link cause of the shitty proxies here gem 'event-calendar', :require => 'event_calendar', :path => 'vendor/event_calendar' #gem 'cancan' #gem 'event-calendar', :require => 'event_calendar', :git => "/home/buzaga/Dropbox/railsapps/event_calendar.git" gem 'sitemap_generator' group :development do gem 'awesome_print' gem 'localtunnel' end group :test, :development do gem 'debugger' gem 'rspec-rails', '~> 2.6' #gem 'ZenTest' #gem 'autotest-rails' gem 'test_notifier' gem 'mocha' end group :mock do gem 'awesome_print' gem 'debugger' gem 'factory_girl_rails' gem 'mocha' end group :test do gem 'factory_girl_rails' gem 'mocha' gem 'capybara' gem 'capybara-webkit' gem 'launchy' gem 'htmlentities', :require => "htmlentities" end # Gems used only for assets and not required # in production environments by default. group :assets do gem 'sass-rails' gem 'less-rails' gem 'coffee-rails' gem 'uglifier' end gem 'jquery-rails' # To use ActiveModel has_secure_password # gem 'bcrypt-ruby', '~> 3.0.0' # Use unicorn as the web server # Deploy with Capistrano #gem 'capistrano' # To use debugger # gem 'ruby-debug19', :require => 'ruby-debug' <file_sep># coding: utf-8 Fubuia::Application.configure do # Settings specified here will take precedence over those in config/application.rb config.after_initialize do load 'spec/support/dummy_responses.rb' Object.class_eval do include DummyResponses end connections_hash = [{"name"=>"<NAME> - Eu vou!", "id"=>"105417699523664"}, {"name"=>"CAMPANHA: CID, DOE SEU SALÁRIO!", "id"=>"226420880736785"}, {"name"=>"LONDON CALLING Summer Edition**show com JOHNNY FLIRT e CASSINO SUPERNOVA", "id"=>"317163524988819"}, {"name"=>"teste", "id"=>"372742442742194"}, {"name"=>"<NAME> China", "id"=>"228651767221196"}] date_today = Date.civil(2012, 1, 26) datetime_today = DateTime.civil(2012,1,26) time_today = datetime_today.to_time Date.stubs(:today).returns(date_today) DateTime.stubs(:now).returns(datetime_today) Time.stubs(:now).returns(time_today) Koala::Facebook::API.any_instance.stubs(:get_connections).with('me', 'events').returns(connections_hash) Koala::Facebook::API.any_instance.stubs(:fql_query).returns(events_query()) end # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = true # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger config.active_support.deprecation = :log # Only use best-standards-support built into browsers config.action_dispatch.best_standards_support = :builtin # Do not compress assets config.assets.compress = false # Expands the lines which load the assets config.assets.debug = true end <file_sep>ActiveAdmin.register Event do filter :id filter :name filter :active filter :start_at index do column :id column :name column :start_at column :end_at column :active column :user_id column "Action" do |event| link_to "Deactivate", deactivate_admin_event_path(event) end default_actions end member_action :deactivate do Event.find(params[:id]).deactivate! redirect_to(:back) end collection_action :new_import, :method => :get do end collection_action :import_event, :method => :post do if params[:fid].present? #TODO: make this shit elegant Event.pull_and_create(params[:fid], User.first, City.first) redirect_to action: :index elsif params[:fids].present? fids = params[:fids].split(/(,|\r\n|\n)/).map(&:strip).reject(&:empty?) fids.each {|f| Event.pull_and_create(f, User.first, City.first)} redirect_to action: :index else flash[:error] = "Please provide a FID, bisho" redirect_to :back end end action_item do link_to "Import", new_import_admin_events_path end end <file_sep>class FacebookEvent < TransientEvent #attr_accessor :eid, :name, :privacy, :pic_small, :pic_big, :location, :venue, :start_time, :end_time, :end_time #attr_accessor :creator #not sure if useful ##for db event overlay #attr_accessor :id, :start_at, :end_at include EventCalendar::InstanceMethods def to_param "#{self.id}-#{self.name.parameterize}" end end <file_sep># coding: UTF-8 class Event < ActiveRecord::Base has_event_calendar acts_as_ordered_taggable belongs_to :city belongs_to :user validates :city, :presence => true validates :fid, :presence => true validates :start_at, :presence => true validate :cant_end_before_it_starts before_save :defaults_end_at_to_start_at before_save :really_multiday? scope :for_date_range, lambda {|start_d, end_d| where(["(start_at < ?) AND (end_at >= ?)", end_d, start_d]).order("start_at ASC") } scope :tagged_with, lambda {|tag_id| joins(:tags).where(["taggings.tag_id = ?", tag_id])} scope :active, lambda { where(:active => true) } def attributes_for_facebook_event #Used when overlaying transient events with DB one attrs = attributes.select {|k,v| ['id','start_at','end_at'].include?(k)} attrs["css_class"] = self.tags.first.try(:css_class) attrs end def deactivate! self.active = false save end def self.pull_and_create(fid, user, city) if fid =~ /facebook.*\d/ # facebook url with event id url = fid fid = url[/(\d+)/] end graph = Koala::Facebook::API.new(user.oauth_token) result = graph.fql_query( "SELECT eid, name, description, creator, privacy, pic_small, pic_big, location, venue, start_time, end_time FROM event WHERE eid = #{fid}" ) if result[0] event = FacebookEvent.new(result[0]) create_from_facebook(event, user, city) else nil end end require 'term_relevancy' def self.create_from_facebook(event, user = default_user(), city) event_db = Event.find_or_initialize_by_fid(event.eid) event_db.attributes = { :name => event.name, :user => user, :city => city, :start_at => Time.zone.parse(event.start_time.to_s), :end_at => Time.zone.parse(event.end_time.to_s) } #autotag tr = TermRelevancy.new event.description, Tag.all.map(&:name) tag_list = tr.rank.reject { |e| e[:relevancy] == 0 }.map { |e| e[:tag] }.compact.join(', ') #/autotag event_db.tag_list = tag_list event_db.active = true event_db.save end private def cant_end_before_it_starts if self.start_at && self.end_at errors.add(:end_at, I18n.t('errors.messages.event.end_before_start')) if self.start_at > self.end_at end end def defaults_end_at_to_start_at self.end_at = self.start_at if self.end_at.blank? end def really_multiday? unless self.end_at.blank? unless self.end_at.to_date === self.start_at.to_date diff = ((self.end_at.to_i - self.start_at.to_i) / 60) / 60 really = diff > 12 unless really self.end_at = self.start_at end end end end end <file_sep>require 'spec_helper' require 'autoimporters' describe "Auto Importers" do describe "FubuiaImporter" do before do #TODO #@already_had = {} date_today = Date.civil(2012, 10, 1) datetime_today = DateTime.civil(2012,10,1) time_today = datetime_today.to_time Date.stubs(:today).returns(date_today) DateTime.stubs(:now).returns(datetime_today) Time.stubs(:now).returns(time_today) @bcount = Event.count @fb_hash = fubevents() #stubs user = FactoryGirl.create(:user, :email => "<EMAIL>") Koala::Facebook::API.any_instance.stubs(:fql_query).returns(@fb_hash) AutoImporters::FubuiaImporter.run end it "should save all new events from Fubuia's profile" do Event.count.should == (@bcount + 5) fids = Event.all.map(&:fid) [11,22,33,44,55].each {|x| fids.should include x} end end end <file_sep>class AddCssAndParentIdToTag < ActiveRecord::Migration def change add_column :tags, :css, :boolean, :default => false add_column :tags, :parent_id, :integer end end <file_sep>namespace :autoimporters do desc "Importa os eventos do perfil do fubuia" task :fubuia => :environment do require 'autoimporters' AutoImporters::FubuiaImporter.run end end <file_sep> $(document).ready(function() { var loadingTimer, popped, route; popped = false; route = crossroads.addRoute('#!/events/{id}', function(id) { $.fancybox('/events/' + id, { type:'ajax', fixed:true, afterLoad:function() { _gaq.push(['_trackPageview', document.location.href]); }, afterClose:function() { history.replaceState(null, '', '/'); crossroads.resetState(); } }) }); $('#calendar').on("click", 'a.e-sesamo', function(e){ //console.log('replaceState'); history.replaceState(null, '', $(this).attr('href')); //console.log('parse'); crossroads.parse($(this).attr('href')); e.preventDefault(); }); $.ajaxSetup({ cache: true }); $(document).on('ajax:beforeSend', 'a.nav-links', function(){ loadingTimer = setTimeout(function() { $('#spinner').fadeIn('fast'); }, 100); }); $(document).ajaxComplete(function(){ clearTimeout(loadingTimer); $('#spinner').fadeOut('fast'); //applyDraggable(); }); $(document).on('keydown', function(e) { if (e.keyCode == 37) { $('#left-arrow').click() } }); $(document).on('keydown', function(e) { if (e.keyCode == 39) { $('#right-arrow').click() } }); //applyDraggable(); $('.mediaTable').mediaTable(); if (history && history.pushState) { $('#calendar').on('click', '#right-arrow, #left-arrow', function(){ //console.log('clicked') popped = true history.pushState(null, '', this.href); }); $(window).on('popstate', function() { //console.log('fired'); popped && $.getScript(location.href); }); } }); <file_sep>class Session < Authlogic::Session::Base authenticate_with User allow_http_basic_auth false end <file_sep># coding: UTF-8 desc "importa os eventos do breno" task :importa => :environment do buzaga = User.find_by_email "<EMAIL>" fubuia = User.find_by_email "<EMAIL>" unless buzaga.present? Rails.logger.warn "PERFIL dO BRENO N DISPONIVEL" return end graph = Koala::Facebook::API.new(buzaga.oauth_token) all = graph.fql_query("select eid, name, creator, privacy, pic_small, pic_big, location, venue, start_time, end_time from event where eid in (SELECT eid FROM event_member WHERE uid=me())") events = all.map { |efql| FacebookEvent.new(efql)} events.map(&:eid).reject! {|eid| Event.all.map(&:fid).include? eid} #reject events we already have #TODO: add autotag events.reject! {|e| Time.zone.parse(e.start_time) < Date.today.to_time } #reject past events events.reject! {|e| e.privacy.upcase != "OPEN" rescue true } #reject private events events.each do |event| event_db = Event.find_or_initialize_by_fid(event.eid) event_db.attributes = {:user => fubuia, :city => City.first, :start_at => Time.zone.parse(event.start_time.to_s), :end_at => Time.zone.parse(event.end_time.to_s)} event_db.active = true event_db.save! end end <file_sep>class RioEvent < TransientEvent #attr_accessor :name, :short_text, :text, :url #attr_accessor :email, :website, :phone #attr_accessor :price, :lgbt, :general_info #attr_accessor :organization, :local #attr_accessor :file #attr_accessor :neighbourhood #attr_accessor :address #attr_accessor :lng, :lat #attr_accessor :start_date, :end_date def initialize(hash={}) h = Hash[hash] h.merge!( h.delete('description') { {} }) h.merge!( h.delete('contactData') { {} }) h.merge!( h.delete('characteristics') { {} }) h.merge!( h.delete('geoResult') { {} }) super(h) end def to_param URI.encode(self.name.gsub(' ', '-')) end end <file_sep>#coding: UTF-8 # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) [ ["Brasília", "brasilia"], ["Rio de Janeiro", "rio"] ].each do |ar| City.find_or_create_by_name_and_subdomain(ar[0], ar[1]) end %w[ rock 0800 gospel dubstep black samba sertanejo open-bar gls brasiliacapitaldorock funk ].each do |tag| Tag.find_or_create_by_name(tag) end if Rails.env.mock? date_today = Date.civil(2012, 1, 26) datetime_today = DateTime.civil(2012,1,26) time_today = datetime_today.to_time Date.stubs(:today).returns(date_today) DateTime.stubs(:now).returns(datetime_today) Time.stubs(:now).returns(time_today) load 'spec/support/dummy_responses.rb' def rand_time(from, to) Time.at(rand_in_range(from.to_f, to.to_f)) end def rand_in_range(from, to) rand * (to - from) + from end random_tags = Tag.all.map(&:name) events_query.each do |x| FactoryGirl.create(:event, :active => true, :city => City.first, :user => User.first, :fid => x["eid"], :start_at => rand_time(DateTime.now - 3.days, DateTime.now + 3.days), :tag_list => random_tags.sample(4).join(',') ) unless Event.where(fid:x["eid"]).present? end end <file_sep>require 'spec_helper' describe User do before do @user = build(:user) end it "has facebook UID" do @user.should respond_to(:uid) end it "has an Oauth Token" do @user.should respond_to(:oauth_token) end it "has an e-mail" do @user.should respond_to(:email) end it "has events" do @user.should respond_to(:events) end context "validations" do it "requires facebook UID" do @user.uid = nil @user.should_not be_valid @user.errors[:uid].should include(i18n 'errors.messages.blank') end it "requires Access Token" do @user.oauth_token = nil @user.should_not be_valid @user.errors[:oauth_token].should include(i18n 'errors.messages.blank') end it "requires a valid e-mail" do @user.email = nil @user.should_not be_valid @user.errors[:email].should include(i18n 'errors.messages.blank') @user.errors[:email].should include(i18n 'errors.messages.email_invalid') end end context "given it receives valid attributes" do it "should save successfully" do @user = build(:user) @user.save.should == true end end end <file_sep>require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "event calendars" do before(:each) do @time = DateTime.new end context "setup" do it "should find the event model" do time = DateTime.now event = Event.new event.start_at = time event.end_at = time event.start_at.should eql( time ) event.end_at.should eql( time ) end it "should load plugin" do lambda { Event.has_event_calendar }.should_not raise_error end it "should use start_at for default field" do Event.start_at_field.should eql('start_at') end it "should use end_at for default field" do Event.end_at_field.should eql('end_at') end end context "not overriding fields" do it "should not alias the start_at method" do event = Event.new event.start_at = @time event.start_at.should eql( @time ) end it "should not alias the end_at method" do event = Event.new event.end_at = @time event.end_at.should eql( @time ) end context "generating database queries" do it "should rely on the standard fields" do yesterday = DateTime.now - 1.day tomorrow = DateTime.now + 1.day event = Event.create(:start_at => yesterday, :end_at => tomorrow) Event.events_for_date_range((Date.today - 1.week ), (Date.today + 1.week)).should eql( [ event ] ) end end end context "overriding fields" do it "should alias the start_at method" do event = CustomEvent.new event.custom_start_at = @time event.custom_start_at.should eql( @time ) event.start_at.should eql( @time ) end it "should alias the end_at method" do event = CustomEvent.new event.custom_end_at = @time event.custom_end_at.should eql( @time ) event.end_at.should eql( @time ) end context "generating database queries" do it "should rely on the overridden fields" do yesterday = DateTime.now - 1.day tomorrow = DateTime.now + 1.day event = CustomEvent.create(:custom_start_at => yesterday, :custom_end_at => tomorrow) CustomEvent.events_for_date_range((Date.today - 1.week ), (Date.today + 1.week)).should eql( [ event ] ) end end end describe "Class methods" do describe ".create_event_strips" do context "given I tell it to create strips for this week" do it "returns an array with 8 spaces" do comparison = [[nil, nil, nil, nil, nil, nil, nil, nil]] Event.create_event_strips(Date.today - 3, Date.today + 4, []).should == comparison end end end describe ".event_strips_for_week" do before(:each) do Event.destroy_all @mon = DateTime.civil(87,12,03) @thu = @mon + 3 @sun = @thu + 3 @mon.wday.should == 1 @thu.wday.should == 4 @sun.wday.should == 0 @first = Event.create(:start_at => @mon, :end_at => @mon) @second = Event.create(:start_at => @thu, :end_at => @thu) @third = Event.create(:start_at => @sun, :end_at => @sun) Date.stub(:today).and_return(@thu) Date.today.should == @thu end it "accepts a parameterless call" do lambda { Event.event_strips_for_week }.should_not raise_error end context "given there's three events, one on Mon, one on Thu, one in Sun and the first day of the week is Mon" do it "returns an array with the three events in it" do comparison = [[@first, nil, nil, @second, nil, nil, @third, nil]] Event.event_strips_for_week.should == comparison end end end end end <file_sep>#coding: UTF-8 require 'spec_helper' describe "Hiperlocal" do before do @ebrasilia = create(:event, :city => City.find_by_subdomain('brasilia'), :fid => 1, :tag_list => "tagsilia") @erio = create(:event, :city => City.find_by_subdomain('rio'), :fid => 2, :tag_list => "tagrio") @events = JSON('[ { "eid": 1, "name": "gama", "creator": 1, "privacy": "OPEN", "location": "No mundo inteiro", "venue": { "street": "", "city": "", "state": "", "country": "" }, "start_time": 1327622400, "end_time": 1327622400 }, { "eid": 2, "name": "botafogo", "creator": 100001678599737, "privacy": "OPEN", "location": "Ceará", "venue": { "street": "", "city": "", "state": "", "country": "" }, "start_time": 1328002200, "end_time": 1328013000 } ]') Koala::Facebook::API.any_instance.stubs(:fql_query).returns(@events) end it "Defaults city to Brasília" do visit '/' page.should have_content "Brasília" end context "brasilia.fubuia.com.br", :subdomain => 'brasilia' do specify "should point to Brasília" do visit '/' page.should have_content "Brasília" end specify "shouldn`t show event from Rio" do visit '/' page.should have_content "gama" page.should_not have_content "botafogo" end specify "shouldn`t show tags in Rio event" do visit '/' page.should have_content "tagsilia" page.should_not have_content "tagrio" end end context "rio.fubuia.com.br", :subdomain => 'rio' do specify "should point to Rio" do visit '/' page.should have_content "Rio de Janeiro" end specify "shouldn`t show event from Brasília" do visit '/' page.should have_content "botafogo" page.should_not have_content "gama" end specify "shouldn`t show tags in Brasilia event" do visit '/' page.should have_content "tagrio" page.should_not have_content "tagsilia" end end end <file_sep># encoding: utf-8 class ApplicationController < ActionController::Base http_basic_authenticate_with name:'buzaga', password:'<PASSWORD>', only:'filter_me_out' protect_from_forgery before_filter :set_app_data helper_method :current_user_session, :current_user class NotLoggedIn < Exception; end class MissingTokenException < Exception; end class UnexpectedException < Exception; end rescue_from MissingTokenException do |e| redirect_to root_url, :flash => {:error => "Missing AccessToken"} end rescue_from NotLoggedIn do |e| redirect_to root_url, :flash => {:error => t('errors.messages.not_logged_in')} end def filter_me_out render :file => "filter_me_out.html", layout:false end protected def set_app_data #set locale I18n.locale = 'pt-BR' #subdomain stuff @app_data = Facebook::CONFIG.merge("callback_url" => "#{request.scheme}://#{request.host}/") if request.subdomain.present? && request.subdomain != 'www' @city = City.find_by_subdomain(request.subdomain) || City.find_by_subdomain('brasilia') else @city ||= City.find_by_subdomain('brasilia') end end def app_access_token #"115184478532515|hHi14dQEY9-V<PASSWORD>zDbkg" #TODO: extract this shit into a constant "495058763843807|3HXV1gMmTu1lbHsYXEUSs9IzVeI" end private def require_login! raise NotLoggedIn unless current_user end def current_user_session return @current_user_session if defined? @current_user_session @current_user_session = Session.find end def current_user return @current_user if defined? @current_user @current_user = current_user_session && current_user_session.user end end <file_sep>Tagging = ActsAsTaggableOn::Tagging <file_sep>Tag = ActsAsTaggableOn::Tag <file_sep>require 'spec_helper' describe "Authorizations" do before do Koala::Facebook::API.any_instance.stubs(:fql_query).returns({}) @event = create(:event, :id => 1, :fid => 1) end it "start import requires login" do visit start_events_import_path page.should have_content i18n('errors.messages.not_logged_in') end specify "import event requires login" do visit import_event_path(1) page.should have_content i18n('errors.messages.not_logged_in') end end <file_sep>Fubuia::Application.routes.draw do devise_for :admin_users, ActiveAdmin::Devise.config get '/cofcof/filter_me' => 'application#filter_me_out' post '/f_e_s', :to => "events#f_e_u" get '/f_e_s', :to => "events#f_e_s" get '/facebook_subscription', :to => "events#f_e_u" post '/facebook/subscription', :to => "events#f_e_u" match '/test', :to => "events#gmailtest" post '/events/:id/create' => 'events#create', :as => :create_event match '/events/import/:eid' => 'events#import', :as => :import_event match '/events/start_import' => 'events#start_import', :as => :start_events_import resources :events, :except => [:index, :create] match 'auth/failure', to: redirect('/') match '/logout' => 'authentication#destroy', :as => :logout match 'auth/:provider/callback', to: "authentication#create", :as => :login, :defaults => {provider:"facebook"} root :to => "calendar#index" ActiveAdmin.routes(self) end <file_sep>ActiveAdmin.register User do index do column :id column :email column :active column :oauth_expires_at column "Ecount" do |user| user.events.count end end end <file_sep>#coding: UTF-8 require 'spec_helper' describe "Events" do before do @event = create(:event, :fid => 12345678, :active => true, :start_at => Date.today, :end_at => Date.today) @event2 = create(:event, :fid => 666, :active => false, :start_at => Date.today, :end_at => Date.today) @facebook_events = [{"name"=>"Evento 1", "eid"=>12345678}, {"name" => "Evento 2", "eid" => 666}] Koala::Facebook::API.any_instance.stubs(:fql_query).returns(@facebook_events) end describe "show" do before do @event_db = create(:event, :fid => 12345, :tag_list => "rock, 0800 beer" ) @multiquery = multiquery() Koala::Facebook::API.any_instance.stubs(:fql_multiquery).returns(@multiquery) @event = @multiquery["event"][0] @creator = @multiquery["creator"][0] end it "should display the event info from facebook" do visit event_path(@event_db) page.should have_content "<NAME>" #creator page.should have_content "No mundo inteiro" #location page.should have_content "Fim do Mundo - Eu vou!" #name page.should have_content "rock" #tags page.should have_content "0800" #tags page.should have_content "beer" #tags page.should have_content "OpenBar até o último cliente" #description page.find('img', :src => "http://profile.ak.fbcdn.net/hprofile-ak-snc4/50236_105417699523664_1798087_n.jpg").should_not be_nil end end describe "new" do it "requires log in" do visit new_event_path page.should have_content page.should have_content i18n('errors.messages.not_logged_in') end context "user logged in" do before do visit '/' page.find_link('Login')["href"].should =~ /first.log.in/ end context "first visit" do pending end it "displays user's events from facebook" do visit new_event_path p end end context "clicking on 'start' link" do context "user logged in" do before do connections_hash = [{"name"=>"<NAME> - Eu vou!", "id"=>"105417699523664"}, {"name"=>"CAMPANHA: CID, DOE SEU SALÁRIO!", "id"=>"226420880736785"}, {"name"=>"LONDON CALLING Summer Edition**show com JOHNNY FLIRT e CASSINO SUPERNOVA", "id"=>"317163524988819"}, {"name"=>"teste", "id"=>"372742442742194"}, {"name"=>"Festa na Cobe do China", "id"=>"228651767221196"}] fql_hash = events_query() today_mock = DateTime.civil(2012, 1, 26) Time.stubs(:now).returns(today_mock) Date.stubs(:today).returns(today_mock.to_date) Koala::Facebook::API.any_instance.stubs(:get_connections).with('me', 'events').returns(connections_hash) Koala::Facebook::API.any_instance.stubs(:fql_query).returns(fql_hash) #<NAME> - Eu Vou! <- created by me, open, future #LONDON CALLING <- created by me, open, future #CID, DOE SEU SALÁRIO! <- not created by me, open, future #teste <- created by me, secret, future #Festa na Cobe do China <- not created by me, secret, past visit login_path visit new_event_path end it "should retrieve user-created events from facebook" do click_on 'start' page.should have_content "Fim do Mundo - Eu vou!" page.should have_content "LONDON CALLING" end it "should retrieve events user has RSVP'd" do end specify "events should be public only" do pending "?" click_on 'start' page.should have_no_content "teste" end specify "events should be future only" do pending "?" click_on 'start' page.should have_no_content "Festa na Cobe do China" end specify "there should be an import button" do click_on 'start' page.should have_selector '.import' end context "selecting an event" do before do click_on 'start' @multiquery = multiquery() Koala::Facebook::API.any_instance.stubs(:fql_multiquery).returns(@multiquery) @event = @multiquery["event"][0] @creator = @multiquery["creator"][0] page.first('.import').click end it "should display event data from facebook" do page.should have_content "Fim do Mundo - Eu vou!" page.should have_content "No mundo inteiro" page.should have_content I18n.l Time.zone.parse(@event["start_time"]) #TODO #page.should have_content Time.zone.parse(@event["end_time"]).to_s(:short) page.should have_content "Breno Salgado" end it "should prompt user to input tags" do page.should have_field "event-tags" end context "saving" do before do Koala::Facebook::API.any_instance.stubs(:fql_query).returns([@event]) end specify "clicking on 'salvar' should save event and redirect to event page" do click_on 'salvar' current_path.should match '/events/[1-9]*' end specify "newly saved event should appear on calendar" do click_on 'salvar' visit '/' page.should have_content "Fim do Mundo - Eu vou!" end end end end end end end <file_sep># -*- coding: utf-8 -*- module CalendarHelper def month_link(month_date) link_to(I18n.localize(month_date, :format => "%B"), {:month => month_date.month, :year => month_date.year}) end def proximo_dia_link #link_to ">>", {:shift => @shift + 1}, :title => "Ver próximos" link_to({:shift => @shift + 1}, id:"right-arrow", class:"nav-links", remote:true) do image_tag "/assets/right-arrow.png", :style => "position: absolute; z-index: 999; right: 0%; top: 50%; height: 30px; opacity: 0.5; margin-right: -10px;" end end def dia_anterior_link #link_to "<<", {:shift => @shift - 1}, :title => "Ver anteriores" link_to({:shift => @shift - 1}, id:"left-arrow", class:"nav-links", remote:true) do image_tag "/assets/left-arrow.png", :style => "position: absolute; z-index: 999; left: 0%; top: 50%; height: 30px; opacity: 0.5; margin-left: -10px;" end end # custom options for this calendar def event_calendar_opts { :shift => @shift, :first_day_of_week => @first_day_of_week, :height => 114, :year => @year, :month => @month, :event_strips => @event_strips, :previous_month_text => dia_anterior_link, :next_month_text => proximo_dia_link, :month_name_text => @shift.to_i == 0 ? "<span style='color:white;text-shadow:0 1px 0 black;'>Hoje &darr;</span>" : "" #:previous_month_text => "<< " + month_link(@shown_month.prev_month), #:next_month_text => month_link(@shown_month.next_month) + " >>" } } end def event_calendar # args is an argument hash containing :event, :day, and :options calendar event_calendar_opts do |args| event = args[:event] #TODO: fix messy html in here, use helper r = %(<a class="e-sesamo" itemprop="url" href="/#!/events/#{event.to_param}" title="#{h(event.name)}">) r << %(<span itemprop="summary"> #{h(event.name)} </span>) r << %(</a>) r << %(<meta itemprop="startDate" content="#{event.start_at.iso8601}"/>) # Microformats! r end end private def link_to_hashbang(*args, &block) link = link_to(*args, &block) "#!#{link}" end end <file_sep># coding: utf-8 class AuthenticationController < ApplicationController def create @user = User.from_omniauth(env["omniauth.auth"]) if @user.save && Session.create(@user) cookies.permanent[:revisitor] = 1 if params[:state] == "first_log_in" redirect_to start_events_import_path, :flash => {:success => "Muito bem vindo! Abaixo estão seus eventos no Facebook, se para importá-lo p/ o site clique em 'importar'." } else redirect_to root_url, :flash => {:success => t('messages.login_success') } end else raise UnexpectedException end end def destroy current_user_session.destroy unless current_user_session.blank? session[:fuser] = nil redirect_to root_url, :flash => {:notice => t('messages.logout_success') } end end <file_sep>//= jquery //= jquery_ujs //= jquery.ui.core //= jquery.ui.widget //= jquery.ui.datepicker //= require active_admin/application
44bc04ffae3923a841b25cde0fe400985055e61a
[ "JavaScript", "Ruby" ]
51
Ruby
salgadobreno/Fubuia
b47c149beb9f5410adf9da82af0f1a183519b5a6
1f7873d29170899c5771dd6a10a43815651afcef
refs/heads/master
<repo_name>kingkris/b16<file_sep>/11-php/connect.php <?php $dbname = 'b16'; $dbuser = 'root'; $dbpass = '<PASSWORD>'; $dbhost = 'localhost'; $link = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname); if (!$link) { echo "Error: Unable to connect to MySQL." . PHP_EOL; echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL; echo "Debugging error: " . mysqli_connect_error() . PHP_EOL; exit; } ?><file_sep>/11-php/index.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Hello, World!</title> <style> .small{color: #D61E63 } .lead{font-size: 18px; color: #59A904 } .wrapper{max-width:700px;margin: 30px auto;padding: 30px;background-color: #F6F5F5;} .dabba{background-color: #fff;padding: 10px;text-align: center;border:solid 1px #CCC;border-radius: 8px} </style> </head> <body> <?php echo '<p>Hello, World! <small class="small">From PHP</small></p>'; // An error below as the text is wrapped in double quotes which includes double quotes as part of the content // echo "<p>Hello, World! <small class="small">From PHP</small></p>"; echo '<p>'; echo 'Some content'; echo ' will come here'; echo '<p>'; $fname = 'KriShne'; $lname = 'Gowda'; $initials = 'NL'; $box = 'dabba'; echo "<p>$fname $lname $initials</p>"; //string n Varibales in double quotes echo '<p class="lead">$fname $lname $initials</p>'; //string n Varibales in single quotes echo '<p>'; echo $fname, $lname, $initials; //Using comma to separet varaibles echo '</p>'; echo '<p>'; echo $fname; echo $lname; echo $initials; echo '</p>'; /*String Concatination*/ echo '<p class="lead">' . $fname . ', ' . $lname . ' ' . $initials . '</p>'; ?> <div class="wrapper"> <h2>my list</h2> <div class="<?php echo $box ?>"> this is a <?php echo $box ?> </div> </div> <?php $markup = '<ol>'; for ($i=0; $i < 10; $i++) { $markup .= '<li>List Item ' . $i . '</li>'; } $markup .= '</ol>'; $x = 100; $y = 200; ?> <div class="wrapper"> <h2>my list</h2> <div class="<?php echo $box ?>"> <?php echo $markup; echo "<p>$x + $y is " . ($x + $y) . "</p>"; echo "<p>$x * $y is " . ($x * $y) . "</p>"; $Y = $x + $y + 400; echo "<p>($x + $y + 400) is $Y</p>"; ?> </div> </div> </body> </html><file_sep>/11-php/03-loops.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Hello, World!</title> <style> .small{color: #D61E63 } .lead{font-size: 18px; color: #59A904 } .wrapper{max-width:700px;margin: 30px auto;padding: 30px;background-color: #F6F5F5;} .dabba{background-color: #fff;padding: 10px;text-align: center;border:solid 1px #CCC;border-radius: 8px} *{ box-sizing: border-box; } .photos{ max-width: 980px; margin: 30px; } @media (min-width: 980px) { .photos{margin-left: auto;margin-right: auto;} } .photos:after{ content: ""; display: block; clear: both; } .photo{ padding: 10px; } .photo img{ border:solid 1px #CCC; background-color: #EAEAEA; padding: 10px; width: 100%; height: auto; display: block; } @media (min-width: 560px) { .photo{ width: 50%; float: left; } } @media (min-width: 768px) { .photo{ width: 33.333%; } } @media (min-width: 980px) { .photo{ width: 25%; } } </style> </head> <body> <h1>For Loop</h1> <div class="photos"> <div class="photo"> <img src="https://api.fnkr.net/testimg/350x200/D15900/FFF/?text=Photo1"> </div> <div class="photo"> <img src="https://api.fnkr.net/testimg/350x200/D15900/FFF/?text=Photo2"> </div> <div class="photo"> <img src="https://api.fnkr.net/testimg/350x200/D15900/FFF/?text=Photo3"> </div> <div class="photo"> <img src="https://api.fnkr.net/testimg/350x200/D15900/FFF/?text=Photo4"> </div> <div class="photo"> <img src="https://api.fnkr.net/testimg/350x200/D15900/FFF/?text=Photo5"> </div> <div class="photo"> <img src="https://api.fnkr.net/testimg/350x200/D15900/FFF/?text=Photo6"> </div> <div class="photo"> <img src="https://api.fnkr.net/testimg/350x200/D15900/FFF/?text=Photo7"> </div> <div class="photo"> <img src="https://api.fnkr.net/testimg/350x200/D15900/FFF/?text=Photo8"> </div> <div class="photo"> <img src="https://api.fnkr.net/testimg/350x200/D15900/FFF/?text=Photo9"> </div> <div class="photo"> <img src="https://api.fnkr.net/testimg/350x200/D15900/FFF/?text=Photo10"> </div> <div class="photo"> <img src="https://api.fnkr.net/testimg/350x200/D15900/FFF/?text=Photo11"> </div> <div class="photo"> <img src="https://api.fnkr.net/testimg/350x200/D15900/FFF/?text=Photo12"> </div> </div> <hr> <div class="photos"> <?php for ($i=1; $i <= 12 ; $i++) { echo '<div class="photo">'; echo '<img src="https://api.fnkr.net/testimg/350x200/D15900/FFF/?text=Photo'. $i .'">'; echo '</div>'; } ?> </div> <hr> <div class="photos"> <?php for ($i=1; $i <= 12 ; $i++) { ?> <div class="photo"> <img src="https://api.fnkr.net/testimg/350x200/D15900/FFF/?text=Photo<?php echo $i ?>"> </div> <?php } ?> </div> <h2>Alternate Syntax</h2> <hr> <div class="photos"> <?php for ($i=1; $i <= 12 ; $i++): ?> <div class="photo"> <img src="https://api.fnkr.net/testimg/350x200/D15900/FFF/?text=Photo<?php echo $i ?>"> </div> <?php endfor; ?> </div> <?php for ($i=0; $i < 10; $i++) { echo "<div>"; for ($j=0; $j < $i; $j++) { echo " * "; } echo "</div>"; } ?> <hr> <hr> <hr> <hr> <h1>While Loop</h1> <ol> <?php $i = rand(0, 11); while ( $i<= 10) { echo "<li>$i</li>"; $i++; } ?> </ol> </body> </html><file_sep>/11-php/04-switch.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Hello, World!</title> <style> .small{color: #D61E63 } .lead{font-size: 18px; color: #59A904 } .wrapper{max-width:700px;margin: 30px auto;padding: 30px;background-color: #F6F5F5;} .dabba{background-color: #fff;padding: 10px;text-align: center;border:solid 1px #CCC;border-radius: 8px} *{ box-sizing: border-box; } .photos{ max-width: 980px; margin: 30px; } @media (min-width: 980px) { .photos{margin-left: auto;margin-right: auto;} } .photos:after{ content: ""; display: block; clear: both; } .photo{ padding: 10px; } .photo img{ border:solid 1px #CCC; background-color: #EAEAEA; padding: 10px; width: 100%; height: auto; display: block; } @media (min-width: 560px) { .photo{ width: 50%; float: left; } } @media (min-width: 768px) { .photo{ width: 33.333%; } } @media (min-width: 980px) { .photo{ width: 25%; } } </style> </head> <body> <?php $day = "Sunday"; ?> <h1>Switch Case</h1> <div class="dabba"> <h1>Daily Schedule of <?php echo $day ?></h1> <?php switch ($day) { case 'Monday': echo "<p>Login and start the weekly mail,</p>"; echo "<p>Attend the weekly status meeting</p>"; echo "<p>Run the Weekly chart</p>"; break; case 'Tuesday': case 'Wednesday': case 'Thursday': echo "<p>Attend the daily status meeting</p>"; break; case 'Friday': echo "<p>Report the weekly status</p>"; echo "<p>Send the weekly mail and logout</p>"; echo "<p>Stop the Weekly chart</p>"; break; default: echo "<p>No Work just Enjoy</p>"; break; } switch ($day) : case 'Monday': echo "<p>Login and start the weekly mail,</p>"; echo "<p>Attend the weekly status meeting</p>"; echo "<p>Run the Weekly chart</p>"; break; case 'Tuesday': case 'Wednesday': case 'Thursday': echo "<p>Attend the daily status meeting</p>"; break; case 'Friday': echo "<p>Report the weekly status</p>"; echo "<p>Send the weekly mail and logout</p>"; echo "<p>Stop the Weekly chart</p>"; break; default: echo "<p>No Work just Enjoy</p>"; break; endswitch; ?> </div> </body> </html><file_sep>/01-intro/editing-tags.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Intro to editing tags</title> </head> <body> <!-- /** TODO: - First todo item - Second todo item */ --> <h1>Editing Tags</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Doloremque neque, aliquid. Error, quaerat eos nisi ab fugit vitae molestiae odio recusandae asperiores. Excepturi, velit necessitatibus impedit nihil. Veniam, recusandae, quam!</p> <p>this is a p tag</p> <p>this is a p tag</p> <!-- <p>this is a p tag</p> --> <p>this is a p tag</p> <p>Hey all, Namaste, thanks for your time. I am a <strong>full stack web designer</strong>, based out of <em>bengaluru</em>. You can reach out to me for any of your web design works, I write perfect <abbr title="Hyper Text Markup Language">html</abbr> &amp; CSS.</p> <p>By the way am the 1<sup>st</sup> in the group. H<sub>2</sub>O</p> <p>I am ardent follower of <NAME>, and as he says <q cite="">You must be the change you wish to see in the world.</q></p> <blockquote cite="http://example.com/facts"> <p>If you're going to try, go all the way. Otherwise, don't even start. This could mean losing girlfriends, wives, relatives and maybe even your mind. It could mean not eating for three or four days. It could mean freezing on a park bench. It could mean jail. It could mean derision. It could mean mockery--isolation. Isolation is the gift. All the others are a test of your endurance, of how much you really want to do it. And, you'll do it, despite rejection and the worst odds. And it will be better than anything else you can imagine. If you're going to try, go all the way. There is no other feeling like that. You will be alone with the gods, and the nights will flame with fire. You will ride life straight to perfect laughter. It's the only good fight there is.</p> <cite><NAME></cite> </blockquote> <!--============================================================ = whatever piece of code you are writing = =============================================================--> <!--==== End of whatever piece of code you are writing ====--> <hr> <address> <strong>KriS' School of Web</strong>,<br> #493/3, 2<sup>nd</sup> floor, Old Airport Road,<br> Kodihally, Bengaluru - 560008 </address> strong, em, abbr, sup, sub, small, time – inline elements hr, br, Address, blockquote attribute cite, q, cite, pre <!-- Comments --> Special Characters <footer> &copy; &trade; &amp; &gt; &lt; &lsquo; - all rights reserved. </footer> </body> </html><file_sep>/02-css/specificity.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Specificity Demo</title> <style> body{ margin:0; color: grey; } h1 {color: green; } .site-header h1 {color: blue; } .title {color: red; } #page-title {color: violet; } #page-title {color: yellow; } h3 + ul {color: red;} .nav-bar{ background-color: #B008AA; border-bottom: solid 10px #1D3DB6; } .menu{ list-style-type: none; padding-left: 0; margin: 0; } .menu:after{ display: block; clear: both; content: "" } .menu > li{ float: left; width: 20%; text-align: center; position: relative; } .menu > li.has-submenu:after{ content: ""; width: 6px; height: 6px; position: absolute; top: 12px; right: 10px; border-right: solid 1px #FFF; border-bottom: solid 1px #FFF; transform: rotate(45deg); } .menu > li > a{ text-transform: uppercase; color: #FFF; text-decoration: none; display: block; line-height: 34px; } .menu > li > a:hover, .menu > li:hover > a{ background-color: #1D3DB6; } .menu li .submenu{ position: absolute; background-color: #1D3DB6; width: 160px; left: 0;right: 0; top: 34px; list-style: none; padding: 5px; margin: 0 auto; display: none; } .menu li:hover .submenu{ display: block; } .submenu li{ text-align: left; } .submenu li a{ display: block; line-height: 28px; color: #FFF; text-transform: uppercase; font-size: 13px; padding: 0 10px; text-decoration: none; border-bottom: solid 1px #6578BE; } .submenu li a:hover{ color: #1D3DB6; background-color: #fff; } .spacer{ min-height: 300px; border-left: dotted 1px grey; margin-left: 30px; } </style> </head> <body> <header class="site-header"> <h1>This is Header 1</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit fugiat quia voluptas omnis enim aliquam est minus, in vero libero rerum, provident nemo consectetur voluptate suscipit officiis fuga, magnam nobis.</p> </header> <div class="content"> <h1>This is header 1</h1> <h1 class="title">This is header 1</h1> <h1 class="title" id="page-title">This is header 1</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Pariatur dolorem harum eveniet, rem molestias maxime delectus repudiandae quos et mollitia quasi sed omnis saepe ratione non totam modi, iure perspiciatis.</p> <h3>Adjacent selector</h3> <ul> <li>list itemsadasd 01</li> <li>list itemsadasd 02</li> <li>list itemsadasd 03</li> <li>list itemsadasd 04</li> <li>list itemsadasd 05</li> </ul> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eius possimus totam perferendis, quia laboriosam dolores enim excepturi omnis harum repudiandae saepe temporibus iure nobis iusto delectus, recusandae, consequatur culpa non.</p> <ul> <li>list itemsadasd 01</li> <li>list itemsadasd 02</li> <li>list itemsadasd 03</li> <li>list itemsadasd 04</li> <li>list itemsadasd 05</li> </ul> <h3>Direct Child Selector</h3> <nav class="nav-bar"> <ul class="menu"> <li><a href="#">Link 1</a></li> <li><a href="#">Link 2</a></li> <li class="has-submenu"><a href="#">Link 3</a> <ul class="submenu"> <li><a href="#">sublink3_1</a></li> <li><a href="#">sublink3_2</a></li> <li><a href="#">sublink3_3</a></li> <li><a href="#">sublink3_4</a></li> <li><a href="#">sublink3_5</a></li> </ul> </li> <li><a href="#">Link 4</a></li> <li><a href="#">Link 5</a></li> </ul> </nav> </div> <div class="spacer"></div> </body> </html><file_sep>/11-php/feedback.php <?php include_once 'connect.php'; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Hello, World!</title> <style> html{ font-family: 'Open Sans', sans-serif; font-weight: 300; color:#444; font-size:16px; line-height: 1.4; } h1 { font-size:56px; font-weight:400; font-family: 'Slabo 27px', serif; text-decoration: none; color:#C46F00; } *{ box-sizing: border-box; } body{ margin:0; } .bg-grey{ background-color: #D4D4D4; padding: 20px; } .bg-lightblue{ background-color: #ADB2FF; padding: 20px; } .form-wrap form{ width:600px; margin:20px auto; } .form-row{ background-color: #fff; margin-bottom: 10px; padding:10px } .form-row label{ width:150px; display: inline-block; text-align: right; font-size: 13px; color: #666; } .txt-area{ width:300px; resize: horizontal; } .bg-title{ background-color: #9500F4; padding:10px; text-align: center; margin:0 0 20px; color:#FFF; position:sticky; top:10px; z-index:2; } .form-sub-row{} .form-row .form-sub-row label{ text-align: left; cursor: pointer; } .form-sub-row input:checked ~ label{ color:red; font-weight: bold; } .form-sub-row input[type="checkbox"]:checked ~ label{ color:green; } .form-sub-row-horizantal{ display: inline-block; } .input-bgi{ background-image: url('../img/bullet-01.png'); background-repeat: no-repeat; background-position: 5px 3px; border: solid 1px #AEAEAE; border-radius:4px; padding:4px 10px 4px 30px; } .input-bg{ border: solid 1px #AEAEAE; border-radius:4px; padding:4px 10px 4px 30px; position: relative; } .input-bg:hover{ border-color: #A9FF3A; } .input-bg:focus{ border-color: #569800; } .form-element{ display: inline-block; position: relative; } .form-element:before{ position: absolute; left:10px; top:3px; content: "@"; width:20px; height:20px; color:#444; z-index:1; text-align: center; line-height: 20px; } .input-box{ border:solid 1px #CCC; border-radius: 4px; padding: 4px 6px; color: #666; width: 200px } .input-box:hover{ border-color:#88A37E; box-shadow: 0 0 1px 0 #4FFF0F; } .input-box:focus{ border-color:#4FFF0F; box-shadow: 0 0 4px 0 #4FFF0F; } .input-box.error{ border-color:#FF0F47; box-shadow: 0 0 4px 0 #FF0F47; } .tac{ text-align: center; } .spacer{ min-height: 500px; margin-left: 40px; border-left: dotted 1px #FBA0A0; } .tbl2{ width: 90%; margin:20px auto; border: solid 1px #CCC; border-collapse: collapse; empty-cells: } .tbl2 caption{ background-color: #D9D9D9; font-size: 20px; line-height: 40px; text-transform: uppercase; } .tbl2 th{ background-color: #BCBCBC; font-size:16px; padding: 6px 2px; border: solid 1px #d9d9d9; } .tbl2 td{ border: solid 1px #BCBCBC; padding:5px; font-size:14px; } .tbl2 tr:nth-child(odd){ background-color: #F6E8FF; } .tbl2 tr:nth-child(even){ background-color: #E8E8FF; } .tbl2 tr:hover{ background-color: #D4FDCF; cursor: pointer; } .tbl2-sl {width:60px; } .tbl2-name {width:220px;} .tbl2-email {width:150px; } .tbl2-mobile {width:120px; } </style> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400|Slabo+27px" rel="stylesheet"> </head> <body> <div class="form-wrap bg-grey"> <h2 class="bg-title">Feedback</h2> <?php //$query = "SELECT * FROM table_name"; $query = "SELECT * FROM feedback"; mysqli_query($link, $query) or die('Error querying database.'); $result = mysqli_query($link, $query); // $row = mysqli_fetch_array($result); ?> <table class="tbl2"> <caption>My Friends</caption> <thead> <tr> <th class="tbl2-sl">Sl #</th> <th class="tbl2-name">Name</th> <th class="tbl2-email">Email</th> <th class="tbl2-mobile">Mobile</th> <th class="tbl2-message">Message</th> </tr> </thead> <tbody> <?php while ($row = mysqli_fetch_array($result)) { echo '<tr>'; echo '<td>' . ' - ' . '</td>'; echo '<td>' . $row['name'] . '</td>'; echo '<td>' . $row['email'] . '</td>'; echo '<td>' . $row['mobile'] . '</td>'; echo '<td>' . $row['message'] . '</td>'; echo '</tr>'; } ?> </tbody> </table> <p><a href="07-forms.php">Want to give your feedback!</a></p> </div> </body> </html><file_sep>/11-php/close.php <?php $dbname = 'b16'; mysqli_close($dbname); ?><file_sep>/09-bs-basics/04-cards.html <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="css/bootstrap.css"> </head> <body> <div class="container bg-bdr"> <h1 class="text-center bg-primary">Working with cards</h1> <div class="row"> <div class="col"> <div class="card"> <img src="https://api.fnkr.net/testimg/350x200/A314B8/FFF/?text=img+placeholder" class="card-img-top" alt="Card image cap"> <div class="card-body"> <h4 class="card-title">Card title</h4> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div><!-- eo card --> </div><!-- eo col --> <div class="col"> <div class="card"> <img src="https://api.fnkr.net/testimg/350x200/A314B8/FFF/?text=img+placeholder" class="card-img-top" alt="Card image cap"> <div class="card-body"> <h4 class="card-title">Card title</h4> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div><!-- eo card --> </div><!-- eo col --> <div class="col"> <div class="card"> <img src="https://api.fnkr.net/testimg/350x200/A314B8/FFF/?text=img+placeholder" class="card-img-top" alt="Card image cap"> <div class="card-body"> <h4 class="card-title">Card title</h4> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div><!-- eo card --> </div><!-- eo col --> </div><!-- /.row --> </div><!-- eo container --> <hr> <div class="container bg-bdr"> <hr> <div class="card"> <header class="card-header"> Quote </header> <div class="card-body"> <blockquote class="blockquote mb-0"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.</p> <footer class="blockquote-footer">Someone famous in <cite title="Source Title">Source Title</cite></footer> </blockquote> </div> </div><!-- eo card --> <hr> <div class="card w-25 d-inline-flex"> <header class="card-header"> Quote </header> <div class="card-body"> <blockquote class="blockquote mb-0"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.</p> <footer class="blockquote-footer">Someone famous in <cite title="Source Title">Source Title</cite></footer> </blockquote> </div> </div><!-- eo card --> <div class="card w-50 d-inline-flex"> <header class="card-header"> Quote </header> <div class="card-body"> <blockquote class="blockquote mb-0"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.</p> <footer class="blockquote-footer">Someone famous in <cite title="Source Title">Source Title</cite></footer> </blockquote> </div> </div><!-- eo card --> <hr> </div><!-- eo container --> <div class="container bg-bdr"> <hr> <div class="card-group"> <div class="card text-white"> <img src="https://api.fnkr.net/testimg/560x420/528357/81ae86/?text=Quote" class="card-img" alt="Card image cap"> <div class="card-body card-img-overlay"> <h4 class="card-title">Card title</h4> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div><!-- eo card --> <div class="card text-white"> <img src="https://api.fnkr.net/testimg/560x420/528357/81ae86/?text=Quote" class="card-img" alt="Card image cap"> <div class="card-body card-img-overlay"> <h4 class="card-title">Card title</h4> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div><!-- eo card --> </div><!-- eo card-group --> <hr> <hr> <div class="card-deck"> <div class="card text-white"> <img src="https://api.fnkr.net/testimg/560x420/528357/81ae86/?text=Quote" class="card-img" alt="Card image cap"> <div class="card-body card-img-overlay"> <h4 class="card-title">Card title</h4> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div><!-- eo card --> <div class="col"> <div class="card text-white"> <img src="https://api.fnkr.net/testimg/560x420/528357/81ae86/?text=Quote" class="card-img" alt="Card image cap"> <div class="card-body card-img-overlay"> <h4 class="card-title">Card title</h4> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div><!-- eo card --> </div><!-- eo card-deck --> <hr> </div><!-- eo container --> <style> .bg-bdr{ background-color: #EADFFF; border:solid 1px red; } .bg-white{background-color: #fff; } .bg-blue{background-color: #BCADFF; } .bg-green{background-color: #C0FFC6; } .bg-red{background-color: #FFB3B3; } .bg-orange{background-color: #FFDCA9; } </style> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> </body> </html><file_sep>/12-js-jquery/js/main.js x = prompt('What is your name?'); elem = document.getElementById('tagline'); elem.innerHTML = x; <file_sep>/11-php/quickcontact.php <?php if($_POST['email'] != '') { /********************* added server side scripting *******************/ $continue = "thankyou.html"; $auto_redirect = 0; $redirect_url = "thankyou.html"; $required_fields_check = 1; $required_fields = array('name','email','phone','comment'); $show_ip = 1; $banned_ips_check = 0; $banned_ips = array(); $banned_ip_message = "Your IP address is banned. The form was not sent."; setcookie('formtoemailpro'); $require_cookie = 0; $strip_html_tags = 1; $check_referrer = 1; $check_comments = 1; $comment_check_words = array('http://','https://','www.','@','.com','.biz'); $gobbledegook_check = 1; // Initialise variables $errors = array(); if($_SERVER['REQUEST_METHOD'] == "POST") { $form_input = $_POST; } elseif($_SERVER['REQUEST_METHOD'] == "GET") { $form_input = $_GET; } else{ exit; } // Remove leading whitespace from all values. $useremail=$form_input['email']; function recursive_array_check(&$element_value){ if(!is_array($element_value)) { $element_value = ltrim($element_value); } else { foreach($element_value as $key => $value){$element_value[$key] = recursive_array_check($value);} } return $element_value; } recursive_array_check($form_input); // Test for cookie. if($require_cookie){ if(!isset($_COOKIE['formtoemailpro'])){$errors[] = "You must enable cookies to use the form";} } // Check referrer. if($check_referrer){ if(!(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) && stristr($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST']))){$errors[] = "You must enable referrer logging to use the form";} } // Check for required fields. If none, don't allow blank form to be sent. if($required_fields_check){ foreach($required_fields as $value){if(!isset($form_input[$value]) || empty($form_input[$value])){$errors[] = "Please go back and complete the $value field";}} } else{ // Check for a blank form. function recursive_array_check_blank($element_value){ global $set; if(!is_array($element_value)) { if(!empty($element_value)){ $set = 1;}} else { foreach($element_value as $value){if($set){break;} recursive_array_check_blank($value);} } } recursive_array_check_blank($form_input); if(!$set){$errors[] = "You cannot send a blank form";} } // Check for banned IPs. if($banned_ips_check) { foreach($banned_ips as $value) { if($value == $_SERVER[REMOTE_ADDR]){$errors[] = $banned_ip_message; break;} } } // Check all fields for gobbledegook. if($gobbledegook_check) { if($set){$set = "";} $gobbledegook_alphabet = array('\'a1','\'a2','\'a4','\'a6','\'a7','\'a8','\'aa','\'ab','\'ac','\'ae','\'af','\'b0','\'b1','\'b2','\'b3','\'b5','\'b6','\'b7','\'b8','\'b9','\'ba','\'bb','\'bc','\'bd','\'be','\'bf','\'c0','\'c1','\'c2','\'c3','\'c4','\'c5','\'c6','\'c7','\'c8','\'c9','\'ca','\'cb','\'cc','\'cd','\'ce','\'cf','\'d0','\'d1','\'d2','\'d3','\'d4','\'d5','\'d6','\'d7','\'d8','\'d9','\'da','\'db','\'dc','\'dd','\'de','\'df','\'e0','\'e1','\'e2','\'e3','\'e4','\'e5','\'e6','\'e7','\'e8','\'e9','\'ea','\'eb','\'ec','\'ed','\'ee','\'ef','\'f0','\'f1','\'f3','\'f5','\'f6','\'f7','\'f8','\'fa','\'fb','\'fc','\'fd','\'fe'); function recursive_array_check_gobbledegook($element_value,$inkey = "") { global $set; global $gobbledegook_alphabet; global $return_value; global $return_key; if(!is_array($element_value)) { foreach($gobbledegook_alphabet as $value){if(stristr($element_value,$value)){$set = 1; $return_value = $value; $return_key = $inkey; break;}} }else{ foreach($element_value as $key => $value){if($set){break;} recursive_array_check_gobbledegook($value,$key);} } } recursive_array_check_gobbledegook($form_input); if($set){if(is_numeric($return_key)){$errors[] = "You have entered an invalid character ($return_value)";}else{$errors[] = "You have entered an invalid character ($return_value) in the \"$return_key\" field";}} } // Strip HTML tags from all fields. if($strip_html_tags) { function recursive_array_check2(&$element_value) { if(!is_array($element_value)){$element_value = strip_tags($element_value);} else { foreach($element_value as $key => $value){$element_value[$key] = recursive_array_check2($value);} } return $element_value; } recursive_array_check2($form_input); } // Validate name field. if(isset($form_input['name']) && !empty($form_input['name'])) { if(preg_match("`[\r\n]`",$form_input['name'])){$errors[] = "You have submitted an invalid new line character";} if(preg_match("/[^a-z' -]/i",stripslashes($form_input['name']))){$errors[] = "You have submitted an invalid character in the name field";} } // Validate email field. if(isset($form_input['email']) && !empty($form_input['email'])) { if(preg_match("`[\r\n]`",$form_input['email'])){$errors[] = "You have submitted an invalid new line character";} //if(!preg_match('/^([a-z][a-z0-9_.-\/\%]*@[^\s\"\)\?<>]+\.[a-z]\{2,6\})$/i',$form_input['Email'])) {$errors[] = "Email address is invalid";} } // Display any errors and exit if errors exist. if(count($errors)){ session_start(); foreach($errors as $value){$error_values .= $value."<br>";} $_SESSION['errvalue'] = $error_values; $_SESSION['previous_page'] = $_SERVER['HTTP_REFERER']; header("location: message.php"); exit; } // Build message. function build_message($request_input) {if(!isset($message_output)) {$message_output = "";}if(!is_array($request_input)) {$message_output = $request_input;}else{foreach($request_input as $key => $value){if(!is_numeric($key)){$message_output .= "\n\n".$key.": ".build_message($value);}else{$message_output .= "\n\n".build_message($value);}}}return $message_output;} $message = build_message($form_input); // Show sender's IP address. if($show_ip){$message .= "\n\nSender's IP address: $_SERVER[REMOTE_ADDR]";} // Strip slashes. $message = stripslashes($message); // Send email. $formfrom=$_POST['email']; $headers = "From: " . $formfrom . "\n" . "Return-Path: " . $formfrom . "\n" . "Reply-To: " . $formfrom . "\n"; $thanksto=$form_input['email']; //mail($my_email,$subject,$message,$headers); /********************** End server side scripting******************************************/ $name = $_POST['name']; $email = $_POST['email']; $mobile = $_POST['phone']; $comment = $_POST['comment']; $hidform = $_POST['hidform']; /********************** End server side scripting******************************************/ // message for different page $msg = "[dzineden.com] Enquiry"; $to_admin .= '<EMAIL>' . ', '; $text_to_user = "Dear ".$name.", <br><br>Thank you for contacting dzineden.com<br>Our team will get in touch with you to provide required information<br><br>Best regards<br><strong>Team dzineden.com</strong><br><br><br><span style='font-size:12px;color:#444'>[This is an auto generated message, please do not reply to this e-mail. Incase of any feedback / suggestions / queries, please post your query here at <EMAIL>]</span>"; $text_to_admin = "Dear Admin,<br>Below is the details sent by ".$name; $text_to_admin .= "<br>-------------------------------------------------<br>"; $text_to_admin .= "<br>Name: ".$name." <br>Email: ".$email." <br>Phone: ".$phone."<br>Comment: ".$comment." <br><br>Sender's IP address:".$_SERVER[REMOTE_ADDR]; $text_to_admin .= "<br>-------------------------------------------------<br>"; /*************************************************/ // mail to user $to_user = $email; // subject $user_subject = '[dzineDen] - Your Enquiry'; $user_headers = 'MIME-Version: 1.0' . "\r\n"; $user_headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Additional headers $user_headers .= 'From: <EMAIL>' . "\r\n"; // Mail to user mail($to_user, $user_subject, $text_to_user, $user_headers); /*************************************************/ /*************************************************/ // subject $admin_headers = 'MIME-Version: 1.0' . "\r\n"; $admin_headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Additional headers $admin_headers .= 'From: '.$email.'' . "\r\n"; // Mail to admin mail($to_admin,$admin_subject,$text_to_admin,$admin_headers); //mail($to_admin,$admin_subject,$text_to_admin,$headers); /*************************************************/ header("Location: thankyou.html"); } ?><file_sep>/12-js-jquery/js/variables.js var x = 5; i = 10; j = 15; // 2a = 10; // a2 = 10; function printVar () { /* console.log('x :', x); console.log('i :', i); console.log('j :', j); console.log('------------------------------'); */ var x; var i = 3000; j = 2000; console.log('x :', x); console.log('i :', i); console.log('j :', j); console.log('------------------------------'); } printVar(); console.log('x :', x); console.log('i :', i); console.log('j :', j); console.log('j :' + j); <file_sep>/README.md # b16 learn webdesign in style, here you'll find all the practice files done in the class <file_sep>/11-php/07-form-thankyou.php <?php include_once 'connect.php'; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Hello, World!</title> <style> html{ font-family: 'Open Sans', sans-serif; font-weight: 300; color:#444; font-size:16px; line-height: 1.4; } h1 { font-size:56px; font-weight:400; font-family: 'Slabo 27px', serif; text-decoration: none; color:#C46F00; } *{ box-sizing: border-box; } body{ margin:0; } .bg-grey{ background-color: #D4D4D4; padding: 20px; } .bg-lightblue{ background-color: #ADB2FF; padding: 20px; } .form-wrap form{ width:600px; margin:20px auto; } .form-row{ background-color: #fff; margin-bottom: 10px; padding:10px } .form-row label{ width:150px; display: inline-block; text-align: right; font-size: 13px; color: #666; } .txt-area{ width:300px; resize: horizontal; } .bg-title{ background-color: #9500F4; padding:10px; text-align: center; margin:0 0 20px; color:#FFF; position:sticky; top:10px; z-index:2; } .form-sub-row{} .form-row .form-sub-row label{ text-align: left; cursor: pointer; } .form-sub-row input:checked ~ label{ color:red; font-weight: bold; } .form-sub-row input[type="checkbox"]:checked ~ label{ color:green; } .form-sub-row-horizantal{ display: inline-block; } .input-bgi{ background-image: url('../img/bullet-01.png'); background-repeat: no-repeat; background-position: 5px 3px; border: solid 1px #AEAEAE; border-radius:4px; padding:4px 10px 4px 30px; } .input-bg{ border: solid 1px #AEAEAE; border-radius:4px; padding:4px 10px 4px 30px; position: relative; } .input-bg:hover{ border-color: #A9FF3A; } .input-bg:focus{ border-color: #569800; } .form-element{ display: inline-block; position: relative; } .form-element:before{ position: absolute; left:10px; top:3px; content: "@"; width:20px; height:20px; color:#444; z-index:1; text-align: center; line-height: 20px; } .input-box{ border:solid 1px #CCC; border-radius: 4px; padding: 4px 6px; color: #666; width: 200px } .input-box:hover{ border-color:#88A37E; box-shadow: 0 0 1px 0 #4FFF0F; } .input-box:focus{ border-color:#4FFF0F; box-shadow: 0 0 4px 0 #4FFF0F; } .input-box.error{ border-color:#FF0F47; box-shadow: 0 0 4px 0 #FF0F47; } .tac{ text-align: center; } .spacer{ min-height: 500px; margin-left: 40px; border-left: dotted 1px #FBA0A0; } </style> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400|Slabo+27px" rel="stylesheet"> </head> <body> <?php if ($_SERVER["REQUEST_METHOD"]=='POST') { $postMethod = $_POST; }else{ $postMethod = $_GET; } /* echo 'Hello ' . htmlspecialchars($postMethod["Name"]) . '!'; // echo "<pre>"; echo var_dump($postMethod); echo "</pre>"; */ ?> <div class="form-wrap bg-grey"> <h2 class="bg-title">Thank You</h2> <p>Hey <b><?php echo htmlspecialchars($postMethod["Name"]) ?></b> Thanks for getting in touch. We'll Process your request and get back to you soon</p> <p>The details you eneterde as follows</p> <!-- <p>Name: <i><?php echo htmlspecialchars($postMethod["Name"]) ?></i></p> <p>Email: <i><?php echo htmlspecialchars($postMethod["Email"]) ?></i></p> <p>Mobile: <i><?php echo htmlspecialchars($postMethod["Mobile"]) ?></i></p> --> <?php foreach ($postMethod as $key => $value): ?> <p><?php echo $key . ': <i>' . $value . '</i>'; ?> </p> <?php endforeach ?> <?php $to = '<EMAIL>'; $from = $postMethod["Email"]; $subject = '[testform] - mail from enquiry'; $name = $postMethod['Name']; $email = $postMethod['Email']; $mobile = $postMethod['Mobile']; $message = $postMethod['Message']; $sql = "INSERT INTO feedback (name, email, mobile, message) VALUES ('$name', '$email', $mobile, '$message')"; if ($link->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $link->error; } $headers = 'MIME-Version: 1.0' . "\r\n" . 'Content-type: text/html; charset=iso-8859-1' . "\r\n". 'From: <EMAIL>' . "\r\n" . 'Reply-To: ' . $from . "\r\n" . 'X-Mailer: PHP/' . phpversion(). "\r\n" ; $message = '<div style="background-color:#F7F7F7;padding:30px">' . '<div style="max-width:500px;padding:10px;border:solid 1px #CCC;background-color:#FFF;font-size:14px;color:#444;font-family:sans-serif;margin:10px auto;">'. '<p style="font-size:18px">Hey Admin, <i>'. $name . '</i> left you a message</p>'. '<p>Details are as below</p>'. '<p>Name: <b>' .$name . '</b></p>'. '<p>Email: <b>' .$email . '</b></p>'. '<p>Mobile: <b>' .$mobile . '</b></p>'. '<p>Message: <b>' .$message . '</b></p>'. '</div>'. '</div>'; // mail($to, $subject, $message, $headers); ?> <p><a href="feedback.php">View the list of feedback</a></p> </div> </body> </html><file_sep>/11-php/03-while-loop.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Hello, World!</title> <style> .small{color: #D61E63 } .lead{font-size: 18px; color: #59A904 } .wrapper{max-width:700px;margin: 30px auto;padding: 30px;background-color: #F6F5F5;} .dabba{background-color: #fff;padding: 10px;text-align: center;border:solid 1px #CCC;border-radius: 8px} *{ box-sizing: border-box; } .photos{ max-width: 980px; margin: 30px; } @media (min-width: 980px) { .photos{margin-left: auto;margin-right: auto;} } .photos:after{ content: ""; display: block; clear: both; } .photo{ padding: 10px; } .photo img{ border:solid 1px #CCC; background-color: #EAEAEA; padding: 10px; width: 100%; height: auto; display: block; } @media (min-width: 560px) { .photo{ width: 50%; float: left; } } @media (min-width: 768px) { .photo{ width: 33.333%; } } @media (min-width: 980px) { .photo{ width: 25%; } } </style> </head> <body> <h1>While Loop</h1> <?php $random = rand(0, 11); $i = $random; echo "<p>The number generated is $random</p>"; echo "<ol>"; while ( $i< 10) { echo "<li>$i</li>"; $i++; } echo "</ol>"; ?> <h1>Do While Loop</h1> <?php echo "<p>The number generated is $random</p>"; $i = $random; echo "<ol>"; do{ echo "<li>$i</li>"; $i++; }while($i< 10); echo "</ol>"; ?> </body> </html><file_sep>/11-php/06-functions.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Hello, World!</title> <style> .small{color: #D61E63 } .lead{font-size: 18px; color: #59A904 } .wrapper{max-width:700px;margin: 30px auto;padding: 30px;background-color: #F6F5F5;} .dabba{background-color: #fff;padding: 10px;text-align: center;border:solid 1px #CCC;border-radius: 8px} *{ box-sizing: border-box; } .photos{ max-width: 980px; margin: 30px; } @media (min-width: 980px) { .photos{margin-left: auto;margin-right: auto;} } .photos:after{ content: ""; display: block; clear: both; } .photo{ padding: 10px; } .photo img{ border:solid 1px #CCC; background-color: #EAEAEA; padding: 10px; width: 100%; height: auto; display: block; } @media (min-width: 560px) { .photo{ width: 50%; float: left; } } @media (min-width: 768px) { .photo{ width: 33.333%; } } @media (min-width: 980px) { .photo{ width: 25%; } } .dashboard{ background-color: #FFC4D2; border: solid 1px #CCC; text-align: left; padding: 20px; } .dashboard span, .dashboard i{ background-color: #FFF; border: solid 1px #CCC; padding: 8px; border-radius: 4px; font-size: 20px; display: inline-block; } .dashboard span{color: #933309 } .dashboard i{color: #0C4704 } </style> </head> <body> <div class="photos"> <?php $students = array( 'Name' => 'Raju', 'Class' => '8a', 'Dob' => '30-june-1999', 'Result' => 'Pass', 'Marks' => array( 'Kannada' => 93, 'English' => 70, 'Maths' => "45", 'Science' => 45, 'Social' => 67, 'Biology' => 88 ) ); $friend = array( 'Name' => 'Rahul', 'Class' => '8a', 'Dob' => '30-june-1999', 'Result' => 'Pass', 'Marks' => array( 'Kannada' => 93, 'English' => 70, 'Maths' => "45", 'Science' => 45, 'Social' => 67, 'Biology' => 88 ) ); function VarDump($var) { echo "<pre>"; echo "the value is"; var_dump($var); echo "</pre>"; } VarDump($students); echo $students['Marks']['Kannada']; function printStudentDetails($student) { echo "<ul>"; foreach ($student as $details => $value) { echo "<li>"; if ($details == 'Marks') { echo "$details - "; echo "<ul>"; foreach ($value as $subject => $value) { echo "<li>$subject : <b>$value</b></li>"; } echo "</ul>"; } else{ echo "$details - $value"; } echo "</li>"; } echo "</ul>"; unset($student); } function printFriendDetails() { global $friend; echo "<hr><p>printed from printFriendDetails functions</p>"; echo "<ul>"; foreach ($friend as $details => $value) { echo "<li>"; if ($details == 'Marks') { echo "$details - "; echo "<ul>"; foreach ($value as $subject => $value) { echo "<li>$subject : <b>$value</b></li>"; } echo "</ul>"; } else{ echo "$details - $value"; } echo "</li>"; } echo "</ul>"; } printStudentDetails($students); printStudentDetails($friend); printFriendDetails(); function addNumbers($num1, $num2) { $x = $num1 + $num2; return $x; } ?> <hr> <div class="dabba"> <?php printStudentDetails($students) ?> <?php $x = 4000; $y = 1345; ?> <p class="dashboard"> <span><?php echo $x ?></span> <span><?php echo $y ?></span> <i><?php echo addNumbers($x, $y) ?></i> </p> </div> </div> </body> </html><file_sep>/11-php/site/daily-tips.php <?php include 'header.php'; include 'site-header.php'; ?> <div class="banner"> <picture> <source media="(max-width: 767px)" srcset="https://api.fnkr.net/testimg/500x200/00CED1/FFF/?text=Mobile"> <source media="(min-width: 1400px)" srcset="https://api.fnkr.net/testimg/1400x200/00CED1/FFF/?text=Large+Desktop"> <source media="(min-width: 980px)" srcset="https://api.fnkr.net/testimg/1200x200/0C007D/FFF/?text=Desktop"> <source media="(min-width: 768px)" srcset="https://api.fnkr.net/testimg/800x200/016231/FFF/?text=Tab"> <img src="https://api.fnkr.net/testimg/1200x200/0C007D/FFF/?text=Desktop" alt="Save water Save earth"> </picture> </div> <div class="container"> <h2>Daily Tips</h2> </div> <?php include 'site-footer.php'; include 'footer.php'; ?> <file_sep>/11-php/05-array-1.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Hello, World!</title> <style> .small{color: #D61E63 } .lead{font-size: 18px; color: #59A904 } .wrapper{max-width:700px;margin: 30px auto;padding: 30px;background-color: #F6F5F5;} .dabba{background-color: #fff;padding: 10px;text-align: center;border:solid 1px #CCC;border-radius: 8px} *{ box-sizing: border-box; } .photos{ max-width: 980px; margin: 30px; } @media (min-width: 980px) { .photos{margin-left: auto;margin-right: auto;} } .photos:after{ content: ""; display: block; clear: both; } .photo{ padding: 10px; } .photo img{ border:solid 1px #CCC; background-color: #EAEAEA; padding: 10px; width: 100%; height: auto; display: block; } @media (min-width: 560px) { .photo{ width: 50%; float: left; } } @media (min-width: 768px) { .photo{ width: 33.333%; } } @media (min-width: 980px) { .photo{ width: 25%; } } </style> </head> <body> <?php $days = array('Monday', 'Tuesday', 'Wednseday', 'Thursday', 'Friday', 'Saturday', 'Sunday'); $marks = array( 'Kannada' => 60, 'English' => 30, 'Maths' => "Absent", 'Science' => 45, 'Social' => 67, 'Biology' => 88 ); ?> <div class="photos"> <?php echo "<ul>"; foreach ($marks as $subject => $score) : echo "<li>$subject : <b> $score</b></li>"; endforeach; echo "</ul>"; echo "<p>", $marks['English'], "</p>"; ?> </div> <hr> <div class="photos"> <?php $student = array( 'Name' => 'Raju', 'Class' => '8a', 'Dob' => '30-june-1999', 'Result' => 'Pass', 'Marks' => array( 'Kannada' => 93, 'English' => 70, 'Maths' => "45", 'Science' => 45, 'Social' => 67, 'Biology' => 88 ) ); echo "<pre>"; var_dump($student); echo "</pre>"; echo $student['Marks']['Kannada']; echo "<ul>"; foreach ($student as $details => $value) { echo "<li>"; if ($details == 'Marks') { echo "$details - "; echo "<ul>"; foreach ($value as $subject => $value) { echo "<li>$subject : <b>$value</b></li>"; } echo "</ul>"; } else{ echo "$details - $value"; } echo "</li>"; } echo "</ul>"; unset($student); ?> </div> <h2>Friend list</h2> <?php $name = "<NAME>"; echo strlen($name); // will return the length of the string echo '<p>', substr($name, 0, 4), '</p>'; //returning the first 4 characters echo strtoupper($name); echo '<p>' . substr($name, 4, 4) . '</p>'; //returning the first 4 characters ?> </body> </html><file_sep>/11-php/site/header.php <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>Developed by dzineden</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="author" content="<NAME>"> <link rel="apple-touch-icon" href="apple-touch-icon.png"> <link rel="shortcut icon" href="favicon.ico"> <!-- Place favicon.ico in the root directory --> <link rel="stylesheet" href="css/normalize.min.css"> <link rel="stylesheet" href="css/main.css"> <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,500" rel="stylesheet"> </head> <body> <!--[if lte IE 9]> <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience and security.</p> <![endif]--> <!-- Add your site or application content here --> <?php include 'site-header.php'; ?><file_sep>/08-psd-to-html-sass/mamtaweb.in.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Welcome to my website</title> </head> <body> <h1>Happy Independence day to you all... </h1> <h2>Be Indepenedent and feel more secure</h2> </body> </html><file_sep>/11-php/site/index.php <?php include 'header.php'; include_once 'site-header.php'; ?> <div class="banner"> <picture> <source media="(max-width: 767px)" srcset="img/banner-mobile.jpg"> <source media="(min-width: 1400px)" srcset="img/banner-xl.jpg"> <source media="(min-width: 980px)" srcset="img/banner-l.jpg"> <source media="(min-width: 768px)" srcset="img/banner-tab.jpg"> <img src="img/banner-l.jpg" alt="Save water Save earth"> </picture> <div> Discover the wold of awsome <span>free PSD templates</span> </div> </div> <?php include 'site-footer.php'; include 'footer.php'; ?> <file_sep>/11-php/02-conditions.php <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Hello, World!</title> <style> .small{color: #D61E63 } .lead{font-size: 18px; color: #59A904 } .wrapper{max-width:700px;margin: 30px auto;padding: 30px;background-color: #F6F5F5;} .dabba{background-color: #fff;padding: 10px;text-align: center;border:solid 1px #CCC;border-radius: 8px} </style> </head> <body> <?php $page = "homae"; if ($page == "home") { echo "<h1>Yes home page</h1>"; } else{ echo "<h1>Not a home page</h1>"; } $time = 8; $faculty = ""; $class ="Started"; if($time>=9 && $faculty){ echo "<p>Let them inside office</p>"; if ($class=="Started") { echo "<p>Let them attend class</p>"; } }else if($faculty){ echo "<p>Let them Discuss doubts</p>"; } ?> <h2>Alternate Syntax</h2> <?php if (true) { echo "<p>Do something</p>"; echo "<hr>"; echo "<p>Alternate syntaxt is as given below</p>"; } if (true): echo "<hr>"; echo "<p>Do something</p>"; echo "<p>Alternate syntaxt is as given below</p>"; endif; ?> </body> </html>
69df1ea47ad8de58cb4a0c2893aa4ff611063a61
[ "JavaScript", "Markdown", "HTML", "PHP" ]
22
PHP
kingkris/b16
42170db6e9fc6b2cbe94fa9fb15aedd198fb07b0
ee6b73f4c895195b651e631f7988d175cbd83e2c
refs/heads/main
<file_sep>import torch.nn as nn from tool.utils import Util class SpatialBlock(nn.Module): def __init__(self, num_layers, kernel_size, in_channels, out_channels, dropout_rate): super(SpatialBlock, self).__init__() self.padding = kernel_size // 2 self.dropout_rate = dropout_rate self.conv_layers = nn.ModuleList() self.dropout_layers = nn.ModuleList() kernel_size = Util.generate_list_from(kernel_size) #factorized kernel spatial_kernel_size = [1, kernel_size[1], kernel_size[2]] spatial_padding_value = kernel_size[1] // 2 spatial_padding = [0, spatial_padding_value, spatial_padding_value] intermed_channels = out_channels for i in range(num_layers): intermed_channels*=2 if i == (num_layers-1): intermed_channels = out_channels self.conv_layers.append( nn.Sequential( nn.Conv3d(in_channels, intermed_channels, kernel_size=spatial_kernel_size, padding=spatial_padding, bias=False), nn.BatchNorm3d(intermed_channels), nn.LeakyReLU(inplace=True) ) ) self.dropout_layers.append(nn.Dropout(dropout_rate)) in_channels = intermed_channels def learning_with_dropout(self, x): for conv, drop in zip(self.conv_layers, self.dropout_layers): x = drop(conv(x)) return x def learning_without_dropout(self, x): for conv in self.conv_layers: x = conv(x) return x def forward(self, input_): if self.dropout_rate > 0.: output = self.learning_with_dropout(input_) else: output = self.learning_without_dropout(input_) return output<file_sep>import torch import torch.nn as nn from tool.utils import Util class TemporalReversedBlock(nn.Module): def __init__(self, input_size, num_layers, kernel_size, in_channels, out_channels, dropout_rate, step): super(TemporalReversedBlock, self).__init__() self.dropout_rate = dropout_rate self.conv_layers = nn.ModuleList() self.dropout_layers = nn.ModuleList() self.input_length = input_size[2] self.step = step kernel_size = Util.generate_list_from(kernel_size) #factorized kernel temporal_kernel_size = [kernel_size[0], 1, 1] intermed_channels = out_channels for i in range(num_layers): intermed_channels*=2 if i == (num_layers-1): intermed_channels = out_channels self.conv_layers.append( RNet(in_channels, intermed_channels, kernel_size=temporal_kernel_size, bias=False) ) self.dropout_layers.append(nn.Dropout(dropout_rate)) in_channels = intermed_channels def learning_with_dropout(self, x): for conv, drop in zip(self.conv_layers, self.dropout_layers): x = drop(conv(x)) return x def learning_without_dropout(self, x): for conv in self.conv_layers: x = conv(x) return x def forward(self, input_): input_ = torch.flip(input_,[2]) if self.dropout_rate > 0.: output = self.learning_with_dropout(input_) else: output = self.learning_without_dropout(input_) output = torch.flip(output,[2]) return output class TemporalReversedBlock_NoChannelIncrease(nn.Module): def __init__(self, input_size, num_layers, kernel_size, in_channels, out_channels, dropout_rate, step): super(TemporalReversedBlock_NoChannelIncrease, self).__init__() self.dropout_rate = dropout_rate self.conv_layers = nn.ModuleList() self.lrelu_layers = nn.ModuleList() self.batch_layers = nn.ModuleList() self.dropout_layers = nn.ModuleList() self.input_length = input_size[2] self.step = step kernel_size = Util.generate_list_from(kernel_size) #factorized kernel temporal_kernel_size = [kernel_size[0], 1, 1] for i in range(num_layers): self.conv_layers.append( RNet(in_channels, out_channels, kernel_size=temporal_kernel_size, bias=False) ) self.dropout_layers.append(nn.Dropout(dropout_rate)) in_channels = out_channels def learning_with_dropout(self, x): for conv, drop in zip(self.conv_layers, self.dropout_layers): x = drop(conv(x)) return x def learning_without_dropout(self, x): for conv in self.conv_layers: x = conv(x) return x def forward(self, input_): input_ = torch.flip(input_,[2]) if self.dropout_rate > 0.: output = self.learning_with_dropout(input_) else: output = self.learning_without_dropout(input_) output = torch.flip(output,[2]) return output class RNet(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, bias): super(RNet, self).__init__() self.temporal_kernel_value = kernel_size[0] self.conv = nn.Sequential( nn.Conv3d(in_channels, out_channels, kernel_size=kernel_size, bias=bias), nn.BatchNorm3d(out_channels), nn.LeakyReLU(inplace=True) ) self.conv_k2 = nn.Sequential( nn.Conv3d(in_channels, out_channels, kernel_size=[2,1,1], bias=bias), nn.BatchNorm3d(out_channels), nn.LeakyReLU(inplace=True) ) self.pad_k2 = nn.ReplicationPad3d((0, 0, 0, 0, 0, 1)) def forward(self, x): if self.temporal_kernel_value == 2: return self.conv_k2(x) output_conv = self.conv(x) output_conv_k2 = self.conv_k2(x[:,:,-self.temporal_kernel_value:,:,:]) output_conv_k2 = self.pad_k2(output_conv_k2) output_conv_part_1 = output_conv[:,:,:-1,:,:] output_conv_part_2 = output_conv[:,:,-1:,:,:] output_conv_part_2 = output_conv_part_2 - output_conv_k2 output = torch.cat([output_conv_part_1,output_conv_part_2], dim=2) return output class TemporalCausalBlock(nn.Module): def __init__(self, input_size, num_layers, kernel_size, in_channels, out_channels, dropout_rate, step): super(TemporalCausalBlock, self).__init__() self.dropout_rate = dropout_rate self.conv_layers = nn.ModuleList() self.lrelu_layers = nn.ModuleList() self.batch_layers = nn.ModuleList() self.dropout_layers = nn.ModuleList() self.input_length = input_size[2] self.step = step kernel_size = Util.generate_list_from(kernel_size) #factorized kernel temporal_kernel_size = [kernel_size[0], 1, 1] self.temporal_padding_value = kernel_size[0] - 1 temporal_padding = [self.temporal_padding_value, 0, 0] intermed_channels = out_channels for i in range(num_layers): intermed_channels*=2 if i == (num_layers-1): intermed_channels = out_channels self.conv_layers.append( nn.Conv3d(in_channels, intermed_channels, kernel_size=temporal_kernel_size, padding=temporal_padding, bias=False) ) self.lrelu_layers.append(nn.LeakyReLU()) self.batch_layers.append(nn.BatchNorm3d(intermed_channels)) self.dropout_layers.append(nn.Dropout(dropout_rate)) in_channels = intermed_channels def learning_with_dropout(self, x): for conv, lrelu, batch, drop in zip(self.conv_layers, self.lrelu_layers, self.batch_layers, self.dropout_layers): x = conv(x)[:,:,:-self.temporal_padding_value,:,:] x = drop(lrelu(batch(x))) return x def learning_without_dropout(self, x): for conv, lrelu, batch in zip(self.conv_layers, self.lrelu_layers, self.batch_layers): x = conv(x)[:,:,:-self.temporal_padding_value,:,:] x = lrelu(batch(x)) return x def forward(self, input_): if self.dropout_rate > 0.: output = self.learning_with_dropout(input_) else: output = self.learning_without_dropout(input_) return output class TemporalCausalBlock_NoChannelIncrease(nn.Module): def __init__(self, input_size, num_layers, kernel_size, in_channels, out_channels, dropout_rate, step): super(TemporalCausalBlock_NoChannelIncrease, self).__init__() self.dropout_rate = dropout_rate self.conv_layers = nn.ModuleList() self.lrelu_layers = nn.ModuleList() self.batch_layers = nn.ModuleList() self.dropout_layers = nn.ModuleList() self.input_length = input_size[2] self.step = step kernel_size = Util.generate_list_from(kernel_size) #factorized kernel temporal_kernel_size = [kernel_size[0], 1, 1] self.temporal_padding_value = kernel_size[0] - 1 temporal_padding = [self.temporal_padding_value, 0, 0] for i in range(num_layers): self.conv_layers.append( nn.Conv3d(in_channels, out_channels, kernel_size=temporal_kernel_size, padding=temporal_padding, bias=False) ) self.lrelu_layers.append(nn.LeakyReLU()) self.batch_layers.append(nn.BatchNorm3d(out_channels)) self.dropout_layers.append(nn.Dropout(dropout_rate)) in_channels = out_channels def learning_with_dropout(self, x): for conv, lrelu, batch, drop in zip(self.conv_layers, self.lrelu_layers, self.batch_layers, self.dropout_layers): x = conv(x)[:,:,:-self.temporal_padding_value,:,:] x = drop(lrelu(batch(x))) return x def learning_without_dropout(self, x): for conv, lrelu, batch in zip(self.conv_layers, self.lrelu_layers, self.batch_layers): x = conv(x)[:,:,:-self.temporal_padding_value,:,:] x = lrelu(batch(x)) return x def forward(self, input_): if self.dropout_rate > 0.: output = self.learning_with_dropout(input_) else: output = self.learning_without_dropout(input_) return output class TemporalBlock(nn.Module): def __init__(self, input_size, num_layers, kernel_size, in_channels, out_channels, dropout_rate, step): super(TemporalBlock, self).__init__() self.dropout_rate = dropout_rate self.conv_layers = nn.ModuleList() self.dropout_layers = nn.ModuleList() self.input_length = input_size[2] self.step = step kernel_size = Util.generate_list_from(kernel_size) #factorized kernel temporal_kernel_size = [kernel_size[0], 1, 1] self.temporal_padding_value = kernel_size[0] // 2 temporal_padding = [self.temporal_padding_value, 0, 0] intermed_channels = out_channels for i in range(num_layers): intermed_channels*=2 if i == (num_layers-1): intermed_channels = out_channels self.conv_layers.append( nn.Sequential( nn.Conv3d(in_channels, intermed_channels, kernel_size=temporal_kernel_size, padding=temporal_padding, bias=False), nn.BatchNorm3d(intermed_channels), nn.LeakyReLU(inplace=True) ) ) self.dropout_layers.append(nn.Dropout(dropout_rate)) in_channels = intermed_channels def learning_with_dropout(self, x): for conv, drop in zip(self.conv_layers, self.dropout_layers): x = drop(conv(x)) return x def learning_without_dropout(self, x): for conv in self.conv_layers: x = conv(x) return x def forward(self, input_): if self.dropout_rate > 0.: output = self.learning_with_dropout(input_) else: output = self.learning_without_dropout(input_) return output <file_sep>import torch.nn as nn import math from tool.utils import Util class Conv2Plus1D(nn.Module): def __init__(self, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step=5): super(Conv2Plus1D, self).__init__() self.conv2plus1_layers = nn.ModuleList() initial_in_channels = input_size[1] in_channels = initial_in_channels out_channels = hidden_dim for i in range(num_layers): self.conv2plus1_layers.append( nn.Sequential( Conv2Plus1Block(kernel_size, in_channels, out_channels, dropout_rate, bias=False), nn.BatchNorm3d(out_channels), nn.LeakyReLU(inplace=True) ) ) in_channels = out_channels padding = kernel_size // 2 self.out_conv = nn.Conv3d(in_channels=out_channels, out_channels=initial_in_channels, kernel_size=kernel_size, padding=padding) def forward(self, x): for conv2plus1 in self.conv2plus1_layers: x = conv2plus1(x) return self.out_conv(x) class Conv2Plus1Block(nn.Module): def __init__(self, kernel_size, in_channels, out_channels, dropout_rate, bias): super(Conv2Plus1Block, self).__init__() kernel_size = Util.generate_list_from(kernel_size) #factorized kernel spatial_kernel_size = [1, kernel_size[1], kernel_size[2]] temporal_kernel_size = [kernel_size[0], 1, 1] spatial_padding_value = kernel_size[1] // 2 temporal_padding_value = kernel_size[0] // 2 spatial_padding = [0, spatial_padding_value, spatial_padding_value] temporal_padding = [temporal_padding_value, 0, 0] intermed_channels = int(math.floor((kernel_size[0] * kernel_size[1] * kernel_size[2] * in_channels * out_channels)/ \ (kernel_size[1] * kernel_size[2] * in_channels + kernel_size[0] * out_channels))) self.spatial_conv = nn.Sequential( nn.Conv3d(in_channels, intermed_channels, spatial_kernel_size, padding=spatial_padding, bias=bias), nn.BatchNorm3d(intermed_channels), nn.LeakyReLU(inplace=True) ) self.temporal_conv = nn.Conv3d(intermed_channels, out_channels, temporal_kernel_size, padding=temporal_padding, bias=bias) def forward(self, x): x = self.spatial_conv(x) return self.temporal_conv(x) """ class R2Plus1(nn.Module): def __init__(self, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step=5): super(R2Plus1, self).__init__() self.r2plus1_layers = nn.ModuleList() self.lrelu_layers = nn.ModuleList() self.batch_layers = nn.ModuleList() initial_in_channels = input_size[1] in_channels = initial_in_channels out_channels = hidden_dim for i in range(num_layers): self.r2plus1_layers.append( R2Plus1Block(kernel_size, in_channels, out_channels, dropout_rate) ) self.batch_layers.append(nn.BatchNorm3d(out_channels)) self.lrelu_layers.append(nn.LeakyReLU()) in_channels = out_channels padding = kernel_size // 2 self.out_conv = nn.Conv3d(in_channels=out_channels, out_channels=initial_in_channels, kernel_size=kernel_size, padding=padding) def forward(self, x): for r2plus1, lrelu, batch in zip(self.r2plus1_layers, self.lrelu_layers, self.batch_layers): x = lrelu(batch(r2plus1(x))) return self.out_conv(x) class R2Plus1CausalBlock(nn.Module): def __init__(self, kernel_size, in_channels, out_channels, dropout_rate): super(R2Plus1CausalBlock, self).__init__() kernel_size = Util.generate_list_from(kernel_size) #factorized kernel spatial_kernel_size = [1, kernel_size[1], kernel_size[2]] temporal_kernel_size = [kernel_size[0], 1, 1] spatial_padding_value = kernel_size[1] // 2 self.temporal_padding_value = kernel_size[0] - 1 spatial_padding = [0, spatial_padding_value, spatial_padding_value] temporal_padding = [self.temporal_padding_value, 0, 0] # number of parameters in the (2+1)D block is approximately equal to that implementing full 3D convolution. intermed_channels = int(math.floor((kernel_size[0] * kernel_size[1] * kernel_size[2] * in_channels * out_channels)/ \ (kernel_size[1] * kernel_size[2] * in_channels + kernel_size[0] * out_channels))) self.spatial_conv = nn.Sequential( nn.Conv3d(in_channels, intermed_channels, spatial_kernel_size, padding=spatial_padding, bias=False), nn.BatchNorm3d(intermed_channels), nn.LeakyReLU(inplace=True) ) self.temporal_conv = nn.Conv3d(intermed_channels, out_channels, temporal_kernel_size, padding=temporal_padding, bias=False) def forward(self, x): x = self.spatial_conv(x) x = self.temporal_conv(x)[:,:,:-self.temporal_padding_value,:,:] return x class R2Plus1Block(nn.Module): def __init__(self, kernel_size, in_channels, out_channels, dropout_rate): super(R2Plus1Block, self).__init__() kernel_size = Util.generate_list_from(kernel_size) #factorized kernel spatial_kernel_size = [1, kernel_size[1], kernel_size[2]] temporal_kernel_size = [kernel_size[0], 1, 1] spatial_padding_value = kernel_size[1] // 2 temporal_padding_value = kernel_size[0] // 2 spatial_padding = [0, spatial_padding_value, spatial_padding_value] temporal_padding = [temporal_padding_value, 0, 0] # number of parameters in the (2+1)D block is approximately equal to that implementing full 3D convolution. intermed_channels = int(math.floor((kernel_size[0] * kernel_size[1] * kernel_size[2] * in_channels * out_channels)/ \ (kernel_size[1] * kernel_size[2] * in_channels + kernel_size[0] * out_channels))) self.spatial_conv = nn.Sequential( nn.Conv3d(in_channels, intermed_channels, spatial_kernel_size, padding=spatial_padding, bias=False), nn.BatchNorm3d(intermed_channels), nn.LeakyReLU(inplace=True) ) self.temporal_conv = nn.Conv3d(intermed_channels, out_channels, temporal_kernel_size, padding=temporal_padding, bias=False) def forward(self, x): x = self.spatial_conv(x) x = self.temporal_conv(x) return x """ <file_sep>import torch.nn as nn import math from tool.utils import Util class Conv3D(nn.Module): def __init__(self, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step=5): super(Conv3D, self).__init__() self.conv3D_layers = nn.ModuleList() initial_in_channels = input_size[1] in_channels = initial_in_channels out_channels = hidden_dim for i in range(num_layers): self.conv3D_layers.append( nn.Sequential( Conv3DBlock(kernel_size, in_channels, out_channels, dropout_rate, bias=False), nn.BatchNorm3d(out_channels), nn.LeakyReLU(inplace=True) ) ) in_channels = out_channels padding = kernel_size // 2 self.conv_final = nn.Conv3d(in_channels=hidden_dim, out_channels=initial_in_channels, kernel_size=kernel_size, padding=padding) def forward(self, x): for conv3D in self.conv3D_layers: x = conv3D(x) return self.conv_final(x) class Conv3DBlock(nn.Module): def __init__(self, kernel_size, in_channels, out_channels, dropout_rate, bias): super(Conv3DBlock, self).__init__() kernel_size = Util.generate_list_from(kernel_size) spatial_padding_value = kernel_size[1] // 2 temporal_padding_value = kernel_size[0] // 2 padding = [temporal_padding_value, spatial_padding_value, spatial_padding_value] self.conv = nn.Conv3d(in_channels, out_channels, kernel_size, padding=padding, bias=bias) def forward(self, x): return self.conv(x) """ class C3D(nn.Module): def __init__(self, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step=5): super(C3D, self).__init__() self.c3d_layers = nn.ModuleList() self.lrelu_layers = nn.ModuleList() self.batch_layers = nn.ModuleList() initial_in_channels = input_size[1] in_channels = initial_in_channels out_channels = hidden_dim for i in range(num_layers): self.c3d_layers.append( C3DBlock(kernel_size, in_channels, out_channels, dropout_rate) ) self.batch_layers.append(nn.BatchNorm3d(out_channels)) self.lrelu_layers.append(nn.LeakyReLU()) in_channels = out_channels padding = kernel_size // 2 self.conv_final = nn.Conv3d(in_channels=hidden_dim, out_channels=initial_in_channels, kernel_size=kernel_size, padding=padding) def forward(self, x): for c3d, lrelu, batch in zip(self.c3d_layers, self.lrelu_layers, self.batch_layers): x = lrelu(batch(c3d(x))) return self.conv_final(x) """ <file_sep>#---------------------------------------------------------------- # my implementation based on https://github.com/eracah/hur-detect #---------------------------------------------------------------- import torch import torch.nn as nn from tool.utils import Util class Endocer_Decoder3D(nn.Module): def __init__(self, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step=5): super(Endocer_Decoder3D, self).__init__() self.down_block = nn.ModuleList() self.up_block = nn.ModuleList() self.input_size = input_size initial_in_channels = input_size[1] in_channels = initial_in_channels out_channels = hidden_dim for i in range(num_layers): self.down_block.append( DownsampleBlock(kernel_size, in_channels, out_channels) ) in_channels = out_channels out_channels = out_channels * 2 out_channels = out_channels // 2 self.batch = nn.BatchNorm3d(out_channels) for i in range(num_layers): in_channels = out_channels out_channels = int(out_channels /2) self.up_block.append( UpsampleBlock(kernel_size, in_channels, out_channels) ) padding = kernel_size // 2 self.out_conv = nn.Conv3d(in_channels=out_channels, out_channels=initial_in_channels, kernel_size=kernel_size, padding=padding) def crop(self, tensor, target_size): _, _, _, tensor_height, tensor_width = tensor.size() diff_y = (tensor_height - target_size[0]) // 2 diff_x = (tensor_width - target_size[1]) // 2 return tensor[:, :, :, diff_y : (diff_y + target_size[0]), diff_x : (diff_x + target_size[1])] def forward(self, x): for down in self.down_block: x = down(x) x = self.batch(x) for up in self.up_block: x = up(x) out = self.out_conv(x) if out.shape[3:] != self.input_size[3:]: out = self.crop(out, self.input_size[3:]) return out class DownsampleBlock(nn.Module): def __init__(self, kernel_size, in_channels, out_channels): super().__init__() kernel_size = Util.generate_list_from(kernel_size) temporal_value = kernel_size[0] // 2 spatial_value = kernel_size[1] // 2 padding = [temporal_value, spatial_value, spatial_value] stride = [1, spatial_value, spatial_value] self.down_block = nn.Sequential( nn.Conv3d(in_channels, out_channels, kernel_size=kernel_size, padding=padding, stride=stride), nn.LeakyReLU(inplace=True) ) def forward(self, x): out = self.down_block(x) return out class UpsampleBlock(nn.Module): def __init__(self, kernel_size, in_channels, out_channels): super().__init__() kernel_size = Util.generate_list_from(kernel_size) spatial_value = kernel_size[1] // 2 kernel_size = [1, spatial_value, spatial_value] stride = [1, spatial_value, spatial_value] self.conv = nn.Sequential( nn.ConvTranspose3d(in_channels, out_channels, kernel_size=kernel_size, stride=stride), nn.LeakyReLU(inplace=True) ) def forward(self, x): out = self.conv(x) return out <file_sep>#------------------------------------------------------------------------- # implementation based on https://github.com/AlexMa011/ConvLSTM_pytorch #------------------------------------------------------------------------- import torch.nn as nn import torch class STConvLSTM(nn.Module): def __init__(self, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step=5): super(STConvLSTM, self).__init__() input_dim = input_size[1] output_dim = input_dim self.convlstm = ConvLSTM(input_size, input_dim, hidden_dim, (kernel_size,kernel_size), num_layers, dropout_rate, step, device) self.conv_layer = nn.Conv3d(in_channels=hidden_dim, out_channels=output_dim, kernel_size=1, padding=0) def forward(self, input_): output = self.convlstm(input_) return self.conv_layer(output) class ConvLSTM(nn.Module): def __init__(self, input_size, input_dim, hidden_dim, kernel_size, num_layers, dropout_rate, step, device, batch_first=True, bias=True): super(ConvLSTM, self).__init__() self._check_kernel_size_consistency(kernel_size) # Make sure that both `kernel_size` and `hidden_dim` are lists having len == num_layers kernel_size = self._extend_for_multilayer(kernel_size, num_layers) hidden_dim = self._extend_for_multilayer(hidden_dim, num_layers) if not len(kernel_size) == len(hidden_dim) == num_layers: raise ValueError('Inconsistent list length.') self.device = device self.input_length = input_size[2] self.height = input_size[3] self.width = input_size[4] self.input_dim = input_dim self.hidden_dim = hidden_dim self.kernel_size = kernel_size self.num_layers = num_layers self.batch_first = batch_first self.bias = bias self.step = step cell_list, conv_list = [],[] for i in range(0, self.num_layers): cur_input_dim = self.input_dim if i == 0 else self.hidden_dim[i-1] cell_list.append(ConvLSTMCell(input_size=(self.height, self.width), input_dim=cur_input_dim, hidden_dim=self.hidden_dim[i], kernel_size=self.kernel_size[i], bias=self.bias, dropout_rate=dropout_rate, device=self.device )) conv_list.append(nn.Conv2d(self.hidden_dim[num_layers-1], cur_input_dim, kernel_size=1, stride=1, padding=0, bias=False)) self.cell_list = nn.ModuleList(cell_list) self.conv_list = nn.ModuleList(conv_list) def forward(self, input_tensor, hidden_state=None): if not self.batch_first: # (c, b, t, h, w) -> (b, c, t, h, w) input_tensor.permute(1, 0, 2, 3, 4) batch = input_tensor.shape[0] if hidden_state is not None: raise NotImplementedError() else: hidden_state = self._init_hidden(batch_size=batch) cur_layer_input = input_tensor for layer_idx in range(self.num_layers): h, c = hidden_state[layer_idx] output_inner = [] for t in range(self.step): if t < self.input_length: net = cur_layer_input[:, :, t, :, :] else: net = x_gen h, c = self.cell_list[layer_idx](input_tensor=net, cur_state=[h, c]) output_inner.append(h) x_gen = self.conv_list[layer_idx](h) layer_output = torch.stack(output_inner, dim=2) cur_layer_input = layer_output return layer_output def _init_hidden(self, batch_size): init_states = [] for i in range(self.num_layers): init_states.append(self.cell_list[i].init_hidden(batch_size)) return init_states @staticmethod def _check_kernel_size_consistency(kernel_size): if not (isinstance(kernel_size, tuple) or (isinstance(kernel_size, list) and all([isinstance(elem, tuple) for elem in kernel_size]))): raise ValueError('`kernel_size` must be tuple or list of tuples') @staticmethod def _extend_for_multilayer(param, num_layers): if not isinstance(param, list): param = [param] * num_layers return param class ConvLSTMCell(nn.Module): def __init__(self, input_size, input_dim, hidden_dim, kernel_size, bias, dropout_rate, device): super(ConvLSTMCell, self).__init__() self.height, self.width = input_size self.input_dim = input_dim self.hidden_dim = hidden_dim self.device = device self.kernel_size = kernel_size self.padding = kernel_size[0] // 2, kernel_size[1] // 2 self.bias = bias self.conv = nn.Sequential( nn.Conv2d(in_channels=self.input_dim + self.hidden_dim, out_channels=4 * self.hidden_dim, kernel_size=self.kernel_size, padding=self.padding, bias=self.bias), nn.Dropout2d(dropout_rate) ) def forward(self, input_tensor, cur_state): h_cur, c_cur = cur_state combined = torch.cat([input_tensor, h_cur], dim=1) # concatenate along channel axis combined_conv = self.conv(combined) cc_i, cc_f, cc_o, cc_g = torch.split(combined_conv, self.hidden_dim, dim=1) i = torch.sigmoid(cc_i) f = torch.sigmoid(cc_f) o = torch.sigmoid(cc_o) g = torch.tanh(cc_g) c_next = f * c_cur + i * g h_next = o * torch.tanh(c_next) return h_next, c_next def init_hidden(self, batch_size): h = torch.zeros(batch_size, self.hidden_dim, self.height, self.width).to(self.device) c = h return (h, c)<file_sep>import torch import torch.nn as nn from .temporal_block import TemporalReversedBlock, TemporalCausalBlock from .spatial_block import SpatialBlock from .generator_block import TemporalGeneratorBlock class STConvS2S_R(nn.Module): def __init__(self, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step=5): super(STConvS2S_R, self).__init__() self.stconvs2s_r = Model(TemporalReversedBlock, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step) def forward(self, x): return self.stconvs2s_r(x) class STConvS2S_C(nn.Module): def __init__(self, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step=5): super(STConvS2S_C, self).__init__() initial_in_channels = input_size[1] input_length = input_size[2] self.stconvs2s_c = Model(TemporalCausalBlock, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step) def forward(self, x): return self.stconvs2s_c(x) class Model(nn.Module): def __init__(self, TemporalBlockInstance, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step=5): super(Model, self).__init__() initial_in_channels = input_size[1] input_length = input_size[2] temporal_block = TemporalBlockInstance(input_size, num_layers, kernel_size, in_channels=initial_in_channels, out_channels=hidden_dim, dropout_rate=dropout_rate, step=step) spatial_block = SpatialBlock(num_layers, kernel_size, in_channels=hidden_dim, out_channels=hidden_dim, dropout_rate=dropout_rate) if step > input_length: generator_block = TemporalGeneratorBlock(input_size, kernel_size, in_channels=hidden_dim, out_channels=hidden_dim, dropout_rate=dropout_rate, step=step) self.conv = nn.Sequential(temporal_block, spatial_block, generator_block) else: self.conv = nn.Sequential(temporal_block, spatial_block) padding = kernel_size // 2 self.conv_final = nn.Conv3d(in_channels=hidden_dim, out_channels=initial_in_channels, kernel_size=kernel_size, padding=padding) def forward(self, x): x = self.conv(x) return self.conv_final(x) <file_sep>import numpy as np import pandas as pd import smtplib import os import time as tm from datetime import datetime from configparser import ConfigParser from pathlib import Path import matplotlib import matplotlib.pyplot as plt matplotlib.use('Agg') #non-interactive backends for png files from matplotlib.ticker import MaxNLocator import torch class Util: def __init__(self, model_descr, dataset_type='notebooks', version=0, prefix=''): current_time = datetime.now() self.model_descr = model_descr self.start_time = current_time.strftime('%d/%m/%Y %H:%M:%S') self.start_time_timestamp = tm.time() self.version = str(version) prefix = prefix.lower() + '_' if prefix.strip() else '' self.base_filename = prefix + self.version + '_' + current_time.strftime('%Y%m%d-%H%M%S') self.project_dir = str(Path(__file__).absolute().parent.parent) self.output_dir = os.path.join(self.project_dir, 'output', dataset_type) def plot(self, data, columns_name, x_label, y_label, title, enable=True, inline=False): if (enable): df = pd.DataFrame(data).T df.columns = columns_name df.index += 1 plot = df.plot(linewidth=2, figsize=(15,8), color=['darkgreen', 'orange'], grid=True); train = columns_name[0] val = columns_name[1] # find position of lowest validation loss idx_min_loss = df[val].idxmin() plot.axvline(idx_min_loss, linestyle='--', color='r',label='Best epoch'); plot.legend(); plot.set_xlim(0, len(df.index)+1); plot.xaxis.set_major_locator(MaxNLocator(integer=True)) plot.set_xlabel(x_label, fontsize=12); plot.set_ylabel(y_label, fontsize=12); plot.set_title(title, fontsize=16); if (not inline): plot_dir = self.__create_dir('plots') filename = os.path.join(plot_dir, self.base_filename + '.png') plot.figure.savefig(filename, bbox_inches='tight'); def send_email(self, model_info, enable=True): if (enable): config = ConfigParser() config.read(os.path.join(self.project_dir, 'config/mail_config.ini')) server = config.get('mailer','server') port = config.get('mailer','port') login = config.get('mailer','login') password = config.get('mailer', 'password') to = config.get('mailer', 'receiver') subject = 'Experiment execution [' + self.model_descr + ']' text = 'This is an email message to inform you that the python script has completed.' message = text + '\n' + str(self.get_time_info()) + '\n' + str(model_info) smtp = smtplib.SMTP_SSL(server, port) smtp.login(login, password) body = '\r\n'.join(['To: %s' % to, 'From: %s' % login, 'Subject: %s' % subject, '', message]) try: smtp.sendmail(login, [to], body) print ('email sent') except Exception: print ('error sending the email') smtp.quit() def save_loss(self, train_losses, val_losses, enable=True): if (enable): losses_dir = self.__create_dir('losses') train_dir, val_dir = self.__create_train_val_dir_in(losses_dir) train_filename = os.path.join(train_dir, self.base_filename + '.txt') val_filename = os.path.join(val_dir, self.base_filename + '.txt') np.savetxt(train_filename, train_losses, delimiter=",", fmt='%g') np.savetxt(val_filename, val_losses, delimiter=",", fmt='%g') def save_examples(self, inputs, target, output, step): input_seq_length = inputs.shape[2] row = step // input_seq_length fig_input, ax_input = plt.subplots(nrows=1, ncols=input_seq_length) fig_ground_truth, ax_ground_truth = plt.subplots(nrows=row, ncols=input_seq_length) fig_prediction, ax_prediction = plt.subplots(nrows=row, ncols=input_seq_length) count = 0 for i in range(row): for j in range(input_seq_length): if step == 5: ax_input[j] = self.__create_image_plot(inputs, ax_input, i, j, count+j, step) ax_ground_truth[j] = self.__create_image_plot(target, ax_ground_truth, i,j ,count+j, step) ax_prediction[j] = self.__create_image_plot(output, ax_prediction, i,j ,count+j, step) else: if i == 0: ax_input[j] = self.__create_image_plot(inputs, ax_input, i, j, count+j, step, ax_input=True) ax_ground_truth[i][j] = self.__create_image_plot(target, ax_ground_truth, i,j ,count+j, step) ax_prediction[i][j] = self.__create_image_plot(output, ax_prediction, i,j ,count+j, step) count+=5 examples_dir = self.__create_dir('examples') self.__save_image_plot(fig_input, examples_dir, 'input', step, fig_input=True) self.__save_image_plot(fig_ground_truth, examples_dir, 'ground_truth', step) self.__save_image_plot(fig_prediction, examples_dir, 'prediction', step) def get_checkpoint_filename(self): check_dir = self.__create_dir('checkpoints') filename = os.path.join(check_dir, self.base_filename + '.pth.tar') return filename def to_readable_time(self, timestamp): hours = int(timestamp / (60 * 60)) minutes = int((timestamp % (60 * 60)) / 60) seconds = timestamp % 60. return f'{hours}:{minutes:>02}:{seconds:>05.2f}' def get_time_info(self): end_time = datetime.now().strftime('%d/%m/%Y %H:%M:%S') end_time_timestamp = tm.time() elapsed_time = end_time_timestamp - self.start_time_timestamp elapsed_time = self.to_readable_time(elapsed_time) time_info = {'model': self.model_descr, 'version': self.version, 'start_time': self.start_time, 'end_time': end_time, 'elapsed_time': elapsed_time} return time_info def get_mask_land(self): """ Original chirps dataset has no ocean data, so this mask is required to ensure that only land data is considered """ filename = os.path.join(self.project_dir, 'data', 'chirps_mask_land.npy') mask_land = np.load(filename) mask_land = torch.from_numpy(mask_land).float() return mask_land @staticmethod def generate_list_from(integer, size=3): if isinstance(integer,int): return [integer] * size return integer def __create_train_val_dir_in(self, dir_path): train_dir = os.path.join(dir_path, 'train') os.makedirs(train_dir, exist_ok=True) val_dir = os.path.join(dir_path, 'val') os.makedirs(val_dir, exist_ok=True) return train_dir, val_dir def __create_dir(self, dir_name): new_dir = os.path.join(self.output_dir, dir_name, self.model_descr) os.makedirs(new_dir, exist_ok=True) return new_dir def __create_image_plot(self, tensor, ax, i, j, index, step, ax_input=False): cmap = 'YlGnBu' if self.base_filename.startswith('chirps') else 'viridis' tensor_numpy = tensor[0,:,index,:,:].squeeze().cpu().numpy() if step == 5 or ax_input: ax[j].imshow(np.flipud(tensor_numpy), cmap=cmap) ax[j].get_xaxis().set_visible(False) ax[j].get_yaxis().set_visible(False) else: ax[i][j].imshow(np.flipud(tensor_numpy), cmap=cmap) ax[i][j].get_xaxis().set_visible(False) ax[i][j].get_yaxis().set_visible(False) return ax def __save_image_plot(self, figure, folder, name, step, fig_input=False): y = 0.7 if (step == 5 or fig_input) else 0.9 figure.suptitle(name, y=y) filename = os.path.join(folder, name + '_' + self.base_filename + '.png') figure.savefig(filename, dpi=300)<file_sep>#-------------------------------------------------------------------- # implementation based on https://github.com/thuml/predrnn-pytorch #-------------------------------------------------------------------- import torch import torch.nn as nn from tool.utils import Util class PredRNN(nn.Module): def __init__(self, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step=5): super(PredRNN, self).__init__() self.frame_channel = input_size[1] self.num_layers = num_layers self.num_hidden = Util.generate_list_from(hidden_dim,num_layers) self.device = device cell_list = [] self.input_length = input_size[2] self.step = step width = input_size[4] in_channel = self.frame_channel for i in range(self.num_layers): in_channel = self.frame_channel if i == 0 else self.num_hidden[i-1] cell_list.append( SpatioTemporalLSTMCell(in_channel, self.num_hidden[i], width, kernel_size, 1, dropout_rate) ) self.cell_list = nn.ModuleList(cell_list) self.conv_last = nn.Conv2d(self.num_hidden[num_layers-1], self.frame_channel, kernel_size=1, stride=1, padding=0, bias=False) def forward(self, frames): # [batch, channel, length, height, width] -> [batch, length, channel, height, width] frames = frames.permute(0, 2, 1, 3, 4).contiguous() batch = frames.shape[0] height = frames.shape[3] width = frames.shape[4] mask_true = torch.zeros((batch, self.step - self.input_length, frames.shape[2], height, width)).to(self.device) next_frames = [] h_t = [] c_t = [] for i in range(self.num_layers): zeros = torch.zeros([batch, self.num_hidden[i], height, width]).to(self.device) h_t.append(zeros) c_t.append(zeros) memory = torch.zeros([batch, self.num_hidden[0], height, width]).to(self.device) for t in range(self.step): if t < self.input_length: net = frames[:,t] else: net = (1 - mask_true[:, t - self.input_length]) * x_gen h_t[0], c_t[0], memory = self.cell_list[0](net, h_t[0], c_t[0], memory) for i in range(1, self.num_layers): h_t[i], c_t[i], memory = self.cell_list[i](h_t[i - 1], h_t[i], c_t[i], memory) x_gen = self.conv_last(h_t[self.num_layers-1]) next_frames.append(x_gen) # [length, batch, channel, height, width] -> [batch, channel, length, height, width] next_frames = torch.stack(next_frames, dim=0).permute(1, 2, 0, 3, 4).contiguous() return next_frames class SpatioTemporalLSTMCell(nn.Module): def __init__(self, in_channel, num_hidden, width, filter_size, stride, dropout_rate): super(SpatioTemporalLSTMCell, self).__init__() self.num_hidden = num_hidden self.padding = filter_size // 2 self._forget_bias = 1.0 self.conv_x = nn.Sequential( nn.Conv2d(in_channel, num_hidden * 7, kernel_size=filter_size, stride=stride, padding=self.padding), nn.LayerNorm([num_hidden * 7, width, width]), nn.Dropout2d(dropout_rate) ) self.conv_h = nn.Sequential( nn.Conv2d(num_hidden, num_hidden * 4, kernel_size=filter_size, stride=stride, padding=self.padding), nn.LayerNorm([num_hidden * 4, width, width]), nn.Dropout2d(dropout_rate) ) self.conv_m = nn.Sequential( nn.Conv2d(num_hidden, num_hidden * 3, kernel_size=filter_size, stride=stride, padding=self.padding), nn.LayerNorm([num_hidden * 3, width, width]), nn.Dropout2d(dropout_rate) ) self.conv_o = nn.Sequential( nn.Conv2d(num_hidden * 2, num_hidden, kernel_size=filter_size, stride=stride, padding=self.padding), nn.LayerNorm([num_hidden, width, width]), nn.Dropout2d(dropout_rate) ) self.conv_last = nn.Conv2d(num_hidden * 2, num_hidden, kernel_size=1, stride=1, padding=0) def forward(self, x_t, h_t, c_t, m_t): x_concat = self.conv_x(x_t) h_concat = self.conv_h(h_t) m_concat = self.conv_m(m_t) i_x, f_x, g_x, i_x_prime, f_x_prime, g_x_prime, o_x = torch.split(x_concat, self.num_hidden, dim=1) i_h, f_h, g_h, o_h = torch.split(h_concat, self.num_hidden, dim=1) i_m, f_m, g_m = torch.split(m_concat, self.num_hidden, dim=1) i_t = torch.sigmoid(i_x + i_h) f_t = torch.sigmoid(f_x + f_h + self._forget_bias) g_t = torch.tanh(g_x + g_h) c_new = f_t * c_t + i_t * g_t i_t_prime = torch.sigmoid(i_x_prime + i_m) f_t_prime = torch.sigmoid(f_x_prime + f_m + self._forget_bias) g_t_prime = torch.tanh(g_x_prime + g_m) m_new = f_t_prime * m_t + i_t_prime * g_t_prime mem = torch.cat((c_new, m_new), 1) o_t = torch.sigmoid(o_x + o_h + self.conv_o(mem)) h_new = o_t * torch.tanh(self.conv_last(mem)) return h_new, c_new, m_new<file_sep>import math import torch import torch.nn as nn from tool.utils import Util class TemporalGeneratorBlock(nn.Module): def __init__(self, input_size, kernel_size, in_channels, out_channels, dropout_rate, step): super(TemporalGeneratorBlock, self).__init__() self.step = step self.input_length = input_size[2] self.tconv_layers = nn.ModuleList() self.conv_layers = nn.ModuleList() kernel_size = Util.generate_list_from(kernel_size) #factorized kernel spatial_kernel_size = [1, kernel_size[1], kernel_size[2]] spatial_padding_value = kernel_size[1] // 2 spatial_padding = [0, spatial_padding_value, spatial_padding_value] num_layers = math.ceil((self.step - self.input_length)/(2 * self.input_length)) intermed_channels = out_channels for i in range(num_layers): intermed_channels*=2 if i == (num_layers-1): intermed_channels = out_channels self.tconv_layers.append( nn.Sequential( nn.ConvTranspose3d(in_channels, intermed_channels, [4,1,1], stride=[2,1,1], padding=[1,0,0], bias=False), nn.BatchNorm3d(intermed_channels), nn.LeakyReLU(inplace=True) ) ) in_channels = intermed_channels num_layers = self.step // self.input_length intermed_channels*=2 for i in range(num_layers): self.conv_layers.append( nn.Sequential( nn.Conv3d(in_channels, intermed_channels, kernel_size=spatial_kernel_size, padding=spatial_padding, bias=False), nn.BatchNorm3d(intermed_channels), nn.LeakyReLU(inplace=True) ) ) in_channels = intermed_channels intermed_channels = out_channels def crop(self, tensor, target_depth): diff_z = (tensor.shape[2] - target_depth) // 2 return tensor[:, :, diff_z : (diff_z + target_depth), :,:] def forward(self, input_): x = input_.clone() for tconv in self.tconv_layers: x = tconv(x) output = torch.cat([input_, x], dim=2) if output.shape[2] > self.step: output = self.crop(output, self.step) for conv in self.conv_layers: output = conv(output) return output """ class TemporalGeneratorBlock(nn.Module): def __init__(self, input_size, kernel_size, in_channels, out_channels, dropout_rate, step): super(TemporalGeneratorBlock, self).__init__() self.step = step self.input_length = input_size[2] self.tconv_layers = nn.ModuleList() num_layers = math.ceil((self.step - self.input_length)/(2 * self.input_length)) intermed_channels = out_channels for i in range(num_layers): intermed_channels*=2 if i == (num_layers-1): intermed_channels = out_channels self.tconv_layers.append( nn.Sequential( nn.ConvTranspose3d(in_channels, intermed_channels, [4,1,1], stride=[2,1,1], padding=[1,0,0], bias=False), nn.BatchNorm3d(intermed_channels), nn.LeakyReLU(inplace=True) ) ) in_channels = intermed_channels #num_layers = self.step // self.input_length #self.conv = SpatialBlock(num_layers, kernel_size, intermed_channels, out_channels, dropout_rate) self.conv = nn.Sequential( nn.Conv3d(in_channels, out_channels, kernel_size=[1, kernel_size, kernel_size], padding=[0, kernel_size // 2, kernel_size // 2], bias=False), nn.BatchNorm3d(out_channels), nn.LeakyReLU(inplace=True), nn.Conv3d(out_channels, out_channels*2, kernel_size=[1, kernel_size, kernel_size], padding=[0, kernel_size // 2, kernel_size // 2], bias=False), nn.BatchNorm3d(out_channels*2), nn.LeakyReLU(inplace=True), nn.Conv3d(out_channels*2, out_channels, kernel_size=[1, kernel_size, kernel_size], padding=[0, kernel_size // 2, kernel_size // 2], bias=False), nn.BatchNorm3d(out_channels), nn.LeakyReLU(inplace=True) ) melhor por enquanto - 6.2590 e 2.8054 self.conv = nn.Sequential( nn.Conv3d(in_channels, out_channels*2, kernel_size=[1, kernel_size, kernel_size], padding=[0, kernel_size // 2, kernel_size // 2], bias=False), nn.BatchNorm3d(out_channels*2), nn.LeakyReLU(inplace=True), nn.Conv3d(out_channels*2, out_channels, kernel_size=[1, kernel_size, kernel_size], padding=[0, kernel_size // 2, kernel_size // 2], bias=False), nn.BatchNorm3d(out_channels), nn.LeakyReLU(inplace=True), nn.Conv3d(out_channels, out_channels, kernel_size=[1, kernel_size, kernel_size], padding=[0, kernel_size // 2, kernel_size // 2], bias=False), nn.BatchNorm3d(out_channels), nn.LeakyReLU(inplace=True) ) self.conv = nn.Sequential( nn.Conv3d(in_channels, out_channels*2, kernel_size=[1, kernel_size, kernel_size], padding=[0, kernel_size // 2, kernel_size // 2], bias=False), nn.BatchNorm3d(out_channels*2), nn.LeakyReLU(inplace=True), nn.Conv3d(out_channels*2, out_channels*2, kernel_size=[1, kernel_size, kernel_size], padding=[0, kernel_size // 2, kernel_size // 2], bias=False), nn.BatchNorm3d(out_channels*2), nn.LeakyReLU(inplace=True), nn.Conv3d(out_channels*2, out_channels, kernel_size=[1, kernel_size, kernel_size], padding=[0, kernel_size // 2, kernel_size // 2], bias=False), nn.BatchNorm3d(out_channels), nn.LeakyReLU(inplace=True) ) def crop(self, tensor, target_depth): diff_z = (tensor.shape[2] - target_depth) // 2 return tensor[:, :, diff_z : (diff_z + target_depth), :,:] def forward(self, input_): x = input_.clone() for tconv in self.tconv_layers: x = tconv(x) output = torch.cat([input_, x], dim=2) if output.shape[2] > self.step: output = self.crop(output, self.step) return self.conv(output) """<file_sep>#----------------------------------------------------------- # my implementation based on https://github.com/Yunbo426/MIM #----------------------------------------------------------- import torch import torch.nn as nn from tool.utils import Util class MIM(nn.Module): def __init__(self, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step=5): super(MIM, self).__init__() self.filter_size = kernel_size self.num_hidden_out = input_size[1] self.input_length = input_size[2] self.step = step self.num_layers = num_layers self.num_hidden = Util.generate_list_from(hidden_dim,num_layers) self.device = device self.stlstm_layer = nn.ModuleList() self.stlstm_layer_diff = nn.ModuleList() num_hidden_in = self.num_hidden_out for i in range(self.num_layers): if i < 1: self.stlstm_layer.append( SpatioTemporalLSTMCell(self.filter_size, num_hidden_in, self.num_hidden[i], input_size, device, dropout_rate) ) else: self.stlstm_layer.append( MIMBlock(self.filter_size, self.num_hidden[i], input_size, device, dropout_rate) ) for i in range(self.num_layers - 1): self.stlstm_layer_diff.append( MIMS(self.filter_size, self.num_hidden[i+1], input_size, device, dropout_rate) ) self.conv_last = nn.Conv2d(self.num_hidden[num_layers - 1], self.num_hidden_out, kernel_size=1, stride=1, padding=0, bias=False) def forward(self, frames): #[batch, channel, length, height, width] -> [batch, length, channel, height, width] frames = frames.permute(0, 2, 1, 3, 4).contiguous() batch = frames.shape[0] height = frames.shape[3] width = frames.shape[4] schedual_sampling_bool = torch.zeros((batch, self.step - self.input_length, frames.shape[2], height, width)).to(self.device) convlstm_c = None next_frames = [] hidden_state, cell_state = [],[] hidden_state_diff, cell_state_diff = [],[] for i in range(self.num_layers): zeros = torch.zeros([batch, self.num_hidden[i], height, width]).to(self.device) hidden_state.append(zeros) cell_state.append(zeros) if i < (self.num_layers - 1): hidden_state_diff.append(zeros) cell_state_diff.append(zeros) st_memory = torch.zeros([batch, self.num_hidden[0], height, width]).to(self.device) for time_step in range(self.step): if time_step < self.input_length: x_gen = frames[:,time_step] else: x_gen = (1 - schedual_sampling_bool[:,time_step - self.input_length]) * x_gen preh = hidden_state[0] hidden_state[0], cell_state[0], st_memory = self.stlstm_layer[0](x_gen, hidden_state[0], cell_state[0], st_memory) for i in range(1, self.num_layers): if time_step > 0: if i == 1: hidden_state_diff[i - 1], cell_state_diff[i - 1] = self.stlstm_layer_diff[i - 1]( hidden_state[i - 1] - preh, hidden_state_diff[i - 1], cell_state_diff[i - 1]) else: hidden_state_diff[i - 1], cell_state_diff[i - 1] = self.stlstm_layer_diff[i - 1]( hidden_state_diff[i - 2], hidden_state_diff[i - 1], cell_state_diff[i - 1]) else: self.stlstm_layer_diff[i - 1](torch.zeros_like(hidden_state[i - 1]), None, None) preh = hidden_state[i] hidden_state[i], cell_state[i], st_memory, convlstm_c = self.stlstm_layer[i]( hidden_state[i - 1], hidden_state_diff[i - 1], hidden_state[i], cell_state[i], st_memory, convlstm_c) x_gen = self.conv_last(hidden_state[self.num_layers-1]) next_frames.append(x_gen) # [length, batch, channel, height, width] -> [batch, channel, length, height, width] next_frames = torch.stack(next_frames, dim=0).permute(1, 2, 0, 3, 4).contiguous() return next_frames class MIMBlock(nn.Module): def __init__(self, filter_size, num_hidden, input_size, device, dropout_rate, bias=False): super(MIMBlock, self).__init__() self.num_hidden = num_hidden self.width = input_size[4] self.device = device self._forget_bias = 1.0 pad = filter_size // 2 self.t_cc = nn.Sequential( nn.Conv2d(num_hidden, num_hidden * 3, kernel_size=filter_size, stride=1, padding=pad, bias=bias), nn.LayerNorm([num_hidden * 3, self.width, self.width]), nn.Dropout2d(dropout_rate) ) self.s_cc = nn.Sequential( nn.Conv2d(num_hidden, num_hidden * 4, kernel_size=filter_size, stride=1, padding=pad, bias=bias), nn.LayerNorm([num_hidden * 4, self.width, self.width]), nn.Dropout2d(dropout_rate) ) self.x_cc = nn.Sequential( nn.Conv2d(num_hidden, num_hidden * 4, kernel_size=filter_size, stride=1, padding=pad, bias=bias), nn.LayerNorm([num_hidden * 4, self.width, self.width]), nn.Dropout2d(dropout_rate) ) self.mims = MIMS(filter_size, num_hidden, input_size, device, dropout_rate) self.last = nn.Conv2d(num_hidden * 2, 1, 1, 1, 0) def init_state(self, shape): return torch.zeros([shape[0], self.num_hidden, shape[2], shape[3]]).to(self.device) def forward(self, x, diff_h, h, c, m, convlstm_c): if h is None: h = self.init_state(x.shape) if c is None: c = self.init_state(x.shape) if m is None: m = self.init_state(x.shape) if diff_h is None: diff_h = torch.zeros_like(h) i_s, g_s, f_s, o_s = torch.split(self.s_cc(m), self.num_hidden, dim=1) i_t, g_t, o_t = torch.split(self.t_cc(h), self.num_hidden, dim=1) i_x, g_x, f_x, o_x = torch.split(self.x_cc(x), self.num_hidden, dim=1) i = torch.sigmoid(i_x + i_t) i_ = torch.sigmoid(i_x + i_s) g = torch.tanh(g_x + g_t) g_ = torch.tanh(g_x + g_s) f_ = torch.sigmoid(f_x + f_s + self._forget_bias) o = torch.sigmoid(o_x + o_t + o_s) new_m = f_ * m + i_ * g_ c, new_convlstm_c = self.mims(diff_h, c, convlstm_c) new_c = c + i * g cell = self.last(torch.cat([new_c, new_m], 1)) new_h = o * torch.tanh(cell) return new_h, new_c, new_m, new_convlstm_c class MIMS(nn.Module): def __init__(self, filter_size, num_hidden, input_size, device, dropout_rate, bias=False): super(MIMS, self).__init__() self.num_hidden = num_hidden self.width = input_size[4] self.device = device self._forget_bias = 1.0 pad = filter_size // 2 self.conv_h = nn.Sequential( nn.Conv2d(num_hidden, num_hidden * 4, kernel_size=filter_size, stride=1, padding=pad, bias=bias), nn.LayerNorm([num_hidden * 4, self.width, self.width]), nn.Dropout2d(dropout_rate) ) self.conv_x = nn.Sequential( nn.Conv2d(num_hidden, num_hidden * 4, kernel_size=filter_size, stride=1, padding=pad, bias=bias), nn.LayerNorm([num_hidden * 4, self.width, self.width]), nn.Dropout2d(dropout_rate) ) self.ct_weight = nn.init.normal_(nn.Parameter(torch.Tensor(torch.zeros(num_hidden*2, self.width, self.width))), 0.0, 1.0) self.oc_weight = nn.init.normal_(nn.Parameter(torch.Tensor(torch.zeros(num_hidden, self.width, self.width))), 0.0, 1.0) def init_state(self, shape): out = torch.zeros([shape[0], self.num_hidden, shape[2], shape[3]]).to(self.device) return out def forward(self, x, h_t, c_t): if h_t is None: h_t = self.init_state(x.shape) if c_t is None: c_t = self.init_state(x.shape) out = self.conv_h(h_t) i_h, g_h, f_h, o_h = torch.split(out, self.num_hidden, dim=1) ct_activation = torch.matmul(c_t.repeat([1,2,1,1]), self.ct_weight) i_c, f_c = torch.split(ct_activation, self.num_hidden, dim=1) i_ = i_h + i_c f_ = f_h + f_c g_ = g_h o_ = o_h if x is not None: outx = self.conv_x(x) i_x, g_x, f_x, o_x = torch.split(outx, self.num_hidden, dim=1) i_ += i_x f_ += f_x g_ += g_x o_ += o_x i_ = torch.sigmoid(i_) f_ = torch.sigmoid(f_ + self._forget_bias) c_new = f_ * c_t + i_ * torch.tanh(g_) o_c = torch.matmul(c_new, self.oc_weight) h_new = torch.sigmoid(o_ + o_c) * torch.tanh(c_new) return h_new, c_new class SpatioTemporalLSTMCell(nn.Module): def __init__(self, filter_size, num_hidden_in, num_hidden, input_size, device, dropout_rate, bias=False): super(SpatioTemporalLSTMCell, self).__init__() self.filter_size = filter_size self.num_hidden_in = num_hidden_in self.num_hidden = num_hidden self.width = input_size[4] self.device = device self._forget_bias = 1.0 pad = filter_size // 2 self.t_cc = nn.Sequential( nn.Conv2d(num_hidden, num_hidden * 4, kernel_size=filter_size, stride=1, padding=pad, bias=bias), nn.LayerNorm([num_hidden * 4, self.width, self.width]), nn.Dropout2d(dropout_rate) ) self.s_cc = nn.Sequential( nn.Conv2d(num_hidden, num_hidden * 4, kernel_size=filter_size, stride=1, padding=pad, bias=bias), nn.LayerNorm([num_hidden * 4, self.width, self.width]), nn.Dropout2d(dropout_rate) ) self.x_cc = nn.Sequential( nn.Conv2d(num_hidden_in, num_hidden * 4, kernel_size=filter_size, stride=1, padding=pad, bias=bias), nn.LayerNorm([num_hidden * 4, self.width, self.width]), nn.Dropout2d(dropout_rate) ) self.last = nn.Conv2d(num_hidden * 2, 1, 1, 1, 0) def init_state(self, shape): return torch.zeros([shape[0], self.num_hidden, shape[2], shape[3]]).to(self.device) def forward(self, x, h, c, m): if h is None: h = self.init_state(x.shape) if c is None: c = self.init_state(x.shape) if m is None: m = self.init_state(x.shape) i_s, g_s, f_s, o_s = torch.split(self.s_cc(m), self.num_hidden, dim=1) i_t, g_t, f_t, o_t = torch.split(self.t_cc(h), self.num_hidden, dim=1) i_x, g_x, f_x, o_x = torch.split(self.x_cc(x), self.num_hidden, dim=1) i = torch.sigmoid(i_x + i_t) i_ = torch.sigmoid(i_x + i_s) g = torch.sigmoid(g_x + g_t) g_ = torch.sigmoid(g_x + g_s) f = torch.sigmoid(f_x + f_t + self._forget_bias) f_ = torch.sigmoid(f_x + f_s + self._forget_bias) o = torch.sigmoid(o_x + o_t + o_s) new_m = f_ * m + i_ * g_ new_c = f * c + i * g cell = self.last(torch.cat([new_c, new_m], 1)) new_h = o * torch.tanh(cell) return new_h, new_c, new_m<file_sep>import torch import torch.nn as nn from .temporal_block import * from .spatial_block import * class AblationSTConvS2S_R_Inverted(nn.Module): def __init__(self, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step=5): super(AblationSTConvS2S_R_Inverted, self).__init__() self.stconvs2s_r = ModelInverted(TemporalReversedBlock, SpatialBlock, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step) def forward(self, x): return self.stconvs2s_r(x) class AblationSTConvS2S_C_Inverted(nn.Module): def __init__(self, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step=5): super(AblationSTConvS2S_C_Inverted, self).__init__() self.stconvs2s_c = ModelInverted(TemporalCausalBlock, SpatialBlock, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step) def forward(self, x): return self.stconvs2s_c(x) class AblationSTConvS2S_R_NoChannelIncrease(nn.Module): def __init__(self, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step=5): super(AblationSTConvS2S_R_NoChannelIncrease, self).__init__() self.stconvs2s_r = Model(TemporalReversedBlock_NoChannelIncrease, SpatialBlock_NoChannelIncrease, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step) def forward(self, x): return self.stconvs2s_r(x) class AblationSTConvS2S_C_NoChannelIncrease(nn.Module): def __init__(self, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step): super(AblationSTConvS2S_C_NoChannelIncrease, self).__init__() initial_in_channels = input_size[1] input_length = input_size[2] self.stconvs2s_c = Model(TemporalCausalBlock_NoChannelIncrease, SpatialBlock_NoChannelIncrease, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step) def forward(self, x): return self.stconvs2s_c(x) class AblationSTConvS2S_NoCausalConstraint(nn.Module): def __init__(self, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step): super(AblationSTConvS2S_NoCausalConstraint, self).__init__() initial_in_channels = input_size[1] input_length = input_size[2] self.stconvs2s = Model(TemporalBlock, SpatialBlock, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step) def forward(self, x): return self.stconvs2s(x) class AblationSTConvS2S_NoTemporal(nn.Module): def __init__(self, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step): super(AblationSTConvS2S_NoTemporal, self).__init__() initial_in_channels = input_size[1] input_length = input_size[2] self.conv = SpatialBlock(num_layers, kernel_size, in_channels=initial_in_channels, out_channels=hidden_dim, dropout_rate=dropout_rate) padding = kernel_size // 2 self.conv_final = nn.Conv3d(in_channels=hidden_dim, out_channels=initial_in_channels, kernel_size=kernel_size, padding=padding) def forward(self, x): x = self.conv(x) return self.conv_final(x) class AblationSTConvS2S_R_NotFactorized(nn.Module): def __init__(self, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step=5): super(AblationSTConvS2S_R_NotFactorized, self).__init__() self.conv3D_layers = nn.ModuleList() initial_in_channels = input_size[1] in_channels = initial_in_channels out_channels = hidden_dim kernel_size = Util.generate_list_from(kernel_size) spatial_padding_value = kernel_size[1] // 2 temporal_padding_value = kernel_size[0] // 2 padding = [temporal_padding_value, spatial_padding_value, spatial_padding_value] for i in range(num_layers): self.conv3D_layers.append( RNetNotFactorized(in_channels, out_channels, kernel_size, bias=False) ) in_channels = out_channels self.conv_final = nn.Conv3d(in_channels=hidden_dim, out_channels=initial_in_channels, kernel_size=kernel_size, padding=padding) def forward(self, x): x = torch.flip(x,[2]) for conv in self.conv3D_layers: x = conv(x) output = torch.flip(x,[2]) return self.conv_final(output) class AblationSTConvS2S_C_NotFactorized(nn.Module): def __init__(self, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step): super(AblationSTConvS2S_C_NotFactorized, self).__init__() self.conv3D_layers = nn.ModuleList() initial_in_channels = input_size[1] in_channels = initial_in_channels out_channels = hidden_dim for i in range(num_layers): self.conv3D_layers.append( nn.Sequential( Conv3DCausalBlock(kernel_size, in_channels, out_channels, dropout_rate, bias=False), nn.BatchNorm3d(out_channels), nn.LeakyReLU(inplace=True) ) ) in_channels = out_channels padding = kernel_size // 2 self.conv_final = nn.Conv3d(in_channels=hidden_dim, out_channels=initial_in_channels, kernel_size=kernel_size, padding=padding) def forward(self, x): for conv in self.conv3D_layers: x = conv(x) return self.conv_final(x) class Model(nn.Module): def __init__(self, TemporalBlockInstance, SpatialBlockInstance, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step=5): super(Model, self).__init__() initial_in_channels = input_size[1] input_length = input_size[2] temporal_block = TemporalBlockInstance(input_size, num_layers, kernel_size, in_channels=initial_in_channels, out_channels=hidden_dim, dropout_rate=dropout_rate, step=step) spatial_block = SpatialBlockInstance(num_layers, kernel_size, in_channels=hidden_dim, out_channels=hidden_dim, dropout_rate=dropout_rate) self.conv = nn.Sequential(temporal_block, spatial_block) padding = kernel_size // 2 self.conv_final = nn.Conv3d(in_channels=hidden_dim, out_channels=initial_in_channels, kernel_size=kernel_size, padding=padding) def forward(self, x): x = self.conv(x) return self.conv_final(x) class ModelInverted(nn.Module): def __init__(self, TemporalBlockInstance, SpatialBlockInstance, input_size, num_layers, hidden_dim, kernel_size, device, dropout_rate, step=5): super(ModelInverted, self).__init__() initial_in_channels = input_size[1] input_length = input_size[2] spatial_block = SpatialBlockInstance(num_layers, kernel_size, in_channels=initial_in_channels, out_channels=hidden_dim, dropout_rate=dropout_rate) temporal_block = TemporalBlockInstance(input_size, num_layers, kernel_size, in_channels=hidden_dim, out_channels=hidden_dim, dropout_rate=dropout_rate, step=step) self.conv = nn.Sequential(spatial_block, temporal_block) padding = kernel_size // 2 self.conv_final = nn.Conv3d(in_channels=hidden_dim, out_channels=initial_in_channels, kernel_size=kernel_size, padding=padding) def forward(self, x): x = self.conv(x) return self.conv_final(x) class Conv3DCausalBlock(nn.Module): def __init__(self, kernel_size, in_channels, out_channels, dropout_rate, bias): super(Conv3DCausalBlock, self).__init__() kernel_size = Util.generate_list_from(kernel_size) spatial_padding_value = kernel_size[1] // 2 self.temporal_padding_value = kernel_size[0] - 1 padding = [self.temporal_padding_value, spatial_padding_value, spatial_padding_value] self.conv = nn.Conv3d(in_channels, out_channels, kernel_size, padding=padding, bias=bias) def forward(self, x): return self.conv(x)[:,:,:-self.temporal_padding_value,:,:] class RNetNotFactorized(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, bias): super(RNetNotFactorized, self).__init__() self.temporal_kernel_value = kernel_size[0] spatial_padding_value = kernel_size[1] // 2 padding = [0, spatial_padding_value, spatial_padding_value] self.conv = nn.Sequential( nn.Conv3d(in_channels, out_channels, kernel_size=kernel_size, padding=padding, bias=bias), nn.BatchNorm3d(out_channels), nn.LeakyReLU(inplace=True) ) self.conv_k2 = nn.Sequential( nn.Conv3d(in_channels, out_channels, kernel_size=[2,1,1], bias=bias), nn.BatchNorm3d(out_channels), nn.LeakyReLU(inplace=True) ) self.pad_k2 = nn.ReplicationPad3d((0, 0, 0, 0, 0, 1)) def forward(self, x): if self.temporal_kernel_value == 2: return self.conv_k2(x) output_conv = self.conv(x) output_conv_k2 = self.conv_k2(x[:,:,-self.temporal_kernel_value:,:,:]) output_conv_k2 = self.pad_k2(output_conv_k2) output_conv_part_1 = output_conv[:,:,:-1,:,:] output_conv_part_2 = output_conv[:,:,-1:,:,:] output_conv_part_2 = output_conv_part_2 - output_conv_k2 output = torch.cat([output_conv_part_1,output_conv_part_2], dim=2) return output
258eedd8f3b2bf0d78961c6d73e340cdb2d9bc00
[ "Python" ]
12
Python
jvguinelli/workshop_cor
c666befc09851994c55c2dc94edeb24b389747df
40e2009ef05cd9eb47f5006c323bb8a2115bc833
refs/heads/master
<file_sep>package com.kryvokin.onlineshop.controller; import com.kryvokin.onlineshop.model.User; import com.kryvokin.onlineshop.service.UserService; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @Controller public class UserPhotoController { private UserService userService; public UserPhotoController(UserService userService) { this.userService = userService; } @GetMapping("/user/download/photo") public String getEditUserView() { return "user/settings"; } @PostMapping("/user/download/photo") public String editUser(@CookieValue(value = "userEmail") String userEmail, @RequestParam("photo") MultipartFile multipartFile) throws IOException { User user = userService.getUserByEmail(userEmail); user.setPhoto(multipartFile.getBytes()); userService.save(user); return "user/main"; } @GetMapping("/user/photo") public void displayPhoto(@CookieValue(value = "userEmail") String userEmail, HttpServletResponse httpServletResponse) throws IOException { byte[] userPhoto = userService.getUserByEmail(userEmail).getPhoto(); if (userPhoto.length > 0) { InputStream photo = new ByteArrayInputStream(userPhoto); httpServletResponse.setContentType(MediaType.IMAGE_JPEG_VALUE); IOUtils.copy(photo, httpServletResponse.getOutputStream()); } } } <file_sep>package com.kryvokin.onlineshop.filter; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.filter.CommonsRequestLoggingFilter; import javax.servlet.http.HttpServletRequest; @Component public class LoggingFilter extends CommonsRequestLoggingFilter { @Value("${isRequestLoggingEnabled}") private boolean isRequestLoggingEnabled; private Logger logger = LogManager.getRootLogger(); private static final Marker REQUEST_MARKER = MarkerManager.getMarker("REQUEST"); @Override protected void beforeRequest(HttpServletRequest request, String message) { logger.info(REQUEST_MARKER,message); } @Override protected boolean shouldLog(HttpServletRequest request) { return isRequestLoggingEnabled; } } <file_sep>-- MySQL Script generated by MySQL Workbench -- Fri Jul 10 15:59:05 2020 -- Model: New Model Version: 1.0 -- MySQL Workbench Forward Engineering SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'; -- ----------------------------------------------------- -- Schema online_shop -- ----------------------------------------------------- DROP SCHEMA IF EXISTS `online_shop` ; -- ----------------------------------------------------- -- Schema online_shop -- ----------------------------------------------------- CREATE SCHEMA IF NOT EXISTS `online_shop` DEFAULT CHARACTER SET utf8 ; USE `online_shop` ; -- ----------------------------------------------------- -- Table `online_shop`.`users` -- ----------------------------------------------------- DROP TABLE IF EXISTS `online_shop`.`users` ; CREATE TABLE IF NOT EXISTS `online_shop`.`users` ( `id` INT NOT NULL AUTO_INCREMENT, `email` VARCHAR(45) NOT NULL, `password` VARCHAR(60) NOT NULL, `photo` BLOB NULL, PRIMARY KEY (`id`), UNIQUE INDEX `email_UNIQUE` (`email` ASC) VISIBLE) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `online_shop`.`orders` -- ----------------------------------------------------- DROP TABLE IF EXISTS `online_shop`.`orders` ; CREATE TABLE IF NOT EXISTS `online_shop`.`orders` ( `id` INT NOT NULL AUTO_INCREMENT, `price` DOUBLE NOT NULL, `status` VARCHAR(45) NOT NULL DEFAULT 'NEW', `users_id` INT NULL, PRIMARY KEY (`id`), INDEX `fk_orders_users1_idx` (`users_id` ASC) VISIBLE, CONSTRAINT `fk_orders_users1` FOREIGN KEY (`users_id`) REFERENCES `online_shop`.`users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `online_shop`.`item` -- ----------------------------------------------------- DROP TABLE IF EXISTS `online_shop`.`item` ; CREATE TABLE IF NOT EXISTS `online_shop`.`item` ( `id` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(45) NOT NULL, `price` DOUBLE NOT NULL, `total_amount` INT NOT NULL, `sold_amount` INT NOT NULL DEFAULT 0, PRIMARY KEY (`id`)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `online_shop`.`roles` -- ----------------------------------------------------- DROP TABLE IF EXISTS `online_shop`.`roles` ; CREATE TABLE IF NOT EXISTS `online_shop`.`roles` ( `name` VARCHAR(45) NOT NULL, PRIMARY KEY (`name`)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `online_shop`.`users_has_roles` -- ----------------------------------------------------- DROP TABLE IF EXISTS `online_shop`.`users_has_roles` ; CREATE TABLE IF NOT EXISTS `online_shop`.`users_has_roles` ( `users_id` INT NOT NULL, `roles_name` VARCHAR(45) NOT NULL, PRIMARY KEY (`users_id`, `roles_name`), INDEX `fk_users_has_roles_roles1_idx` (`roles_name` ASC) VISIBLE, INDEX `fk_users_has_roles_users1_idx` (`users_id` ASC) VISIBLE, CONSTRAINT `fk_users_has_roles_users1` FOREIGN KEY (`users_id`) REFERENCES `online_shop`.`users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_users_has_roles_roles1` FOREIGN KEY (`roles_name`) REFERENCES `online_shop`.`roles` (`name`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `online_shop`.`orders_has_item` -- ----------------------------------------------------- DROP TABLE IF EXISTS `online_shop`.`orders_has_item` ; CREATE TABLE IF NOT EXISTS `online_shop`.`orders_has_item` ( `orders_id` INT NOT NULL, `item_id` INT NOT NULL, `amount` INT NOT NULL, INDEX `fk_orders_has_item_item1_idx` (`item_id` ASC) VISIBLE, INDEX `fk_orders_has_item_orders1_idx` (`orders_id` ASC) VISIBLE, PRIMARY KEY (`orders_id`, `item_id`), CONSTRAINT `fk_orders_has_item_orders1` FOREIGN KEY (`orders_id`) REFERENCES `online_shop`.`orders` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_orders_has_item_item1` FOREIGN KEY (`item_id`) REFERENCES `online_shop`.`item` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; <file_sep>shop.datasource.driver=com.mysql.cj.jdbc.Driver shop.datasource.jdbcUrl=jdbc:mysql://localhost:3306/online_shop shop.datasource.username=root shop.datasource.password=<PASSWORD> spring.servlet.multipart.enabled=true logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG isRequestLoggingEnabled=true<file_sep>package com.kryvokin.onlineshop.model; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class RoleEditorTest { private RoleEditor roleEditor = new RoleEditor(); private Role role = new Role(); @Test void packageTest(){ assertEquals(roleEditor.getClass().getPackage(), role.getClass().getPackage()); } @Test void nameTest(){ assertEquals(RoleEditor.class.getSimpleName(),Role.class.getSimpleName().concat("Editor")); } }<file_sep>package com.kryvokin.onlineshop.model; import java.beans.PropertyEditorSupport; public class RoleEditor extends PropertyEditorSupport { @Override public void setAsText(String text) throws IllegalArgumentException { Role role = new Role(); role.setName(text); setValue(role); } } <file_sep>message.logout=Выйти message.user.email=Email : message.user.password=<PASSWORD>: message.submit=Отправить message.sign.in=Зайти message.register=Зарегистрироватся message.invalid.login.waring=Неправильный пароль или email message.register.error=Пользователь с %s email уже существет message.remember.me=Запомнить меня message.user.greeting=Привет пользователь! message.download.photo=Загрузить фото message.name=Имя message.price=Цена message.add=Добавить message.amount=Количество message.back=Назад message.create.order=Оформить заказ message.catalog=Каталог<file_sep>package com.kryvokin.onlineshop.model; public enum OrderStatus { NEW("NEW"), CANCELLED("CANCELLED"), CLOSED("CLOSED"), IN_PROGRESS("IN PROGRESS"); private String name; OrderStatus(String name) { this.name = name; } } <file_sep>package com.kryvokin.onlineshop.controller; import com.kryvokin.onlineshop.model.Local; import com.kryvokin.onlineshop.service.UserService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class HomeController { private UserService userService; public HomeController(UserService userService) { this.userService = userService; } @GetMapping(value = {"/", "/main"}) public String doHome(Model model){ model.addAttribute("local", Local.values()); return "main"; } @GetMapping("/user/main") public String doUserHome(Model model){ return "user/main"; } @GetMapping("/admin/main") public String doAdminHome(Model model){ return "admin/main"; } } <file_sep>package com.kryvokin.onlineshop.model.compositekey; import lombok.Builder; import javax.persistence.Column; import javax.persistence.Embeddable; import java.io.Serializable; import java.util.Objects; @Embeddable @Builder public class OrderHasItemKey implements Serializable { @Column(name = "orders_id") private int orderId; @Column(name = "item_id") private int itemId; public OrderHasItemKey() { } public OrderHasItemKey(int orderId, int itemId) { this.orderId = orderId; this.itemId = itemId; } public int getOrderId() { return orderId; } public void setOrderId(int orderId) { this.orderId = orderId; } public int getItemId() { return itemId; } public void setItemId(int itemId) { this.itemId = itemId; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof OrderHasItemKey)) return false; OrderHasItemKey that = (OrderHasItemKey) o; return orderId == that.orderId && itemId == that.itemId; } @Override public int hashCode() { return Objects.hash(orderId, itemId); } } <file_sep>package com.kryvokin.onlineshop.config; import com.kryvokin.onlineshop.model.Cart; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.client.RestTemplate; import org.springframework.web.context.WebApplicationContext; @Configuration public class AppConfig { @Bean public PasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } @Bean public RestTemplate restTemplate() { return new RestTemplate(); } @Bean @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) public Cart cart() { return new Cart(); } } <file_sep>message.logout=Logout message.user.email=User email : message.user.password=<PASSWORD>: message.submit=Submit message.sign.in=Sign in message.register=Register message.invalid.login.waring=Invalid username or password. message.register.error=User with %s email already exists message.remember.me=Remember me message.user.greeting=Hello user! message.download.photo=Download photo message.name=Name message.price=Price message.add=Add message.amount=Amount message.back=Back message.create.order=Submit an order message.catalog=Catalog <file_sep>package com.kryvokin.onlineshop.service; import com.kryvokin.onlineshop.model.Product; import com.kryvokin.onlineshop.repository.ProductRepository; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class ProductService { private ProductRepository productRepository; public ProductService(ProductRepository productRepository) { this.productRepository = productRepository; } public Page<Product> findAll(int pageSize, int currentPage){ Pageable page = PageRequest.of(currentPage, pageSize); return productRepository.findAll(page); } public Optional<Product> findById(int id){ return productRepository.findById(id); } public Product save(Product product){ return productRepository.save(product); } } <file_sep>package com.kryvokin.onlineshop.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import java.util.List; import java.util.Objects; @Entity @Table(name = "item") public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; private double price; @Column(name = "total_amount") private int totalAmount; @Column(name = "sold_amount") private int soldAmount; @OneToMany(mappedBy = "item") private List<OrderHasItem> orders; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getTotalAmount() { return totalAmount; } public void setTotalAmount(int totalAmount) { this.totalAmount = totalAmount; } public int getSoldAmount() { return soldAmount; } public void setSoldAmount(int soldAmount) { this.soldAmount = soldAmount; } public List<OrderHasItem> getOrders() { return orders; } public void setOrders(List<OrderHasItem> orders) { this.orders = orders; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Product)) return false; Product product = (Product) o; return id == product.id && Double.compare(product.price, price) == 0 && totalAmount == product.totalAmount && soldAmount == product.soldAmount && name.equals(product.name); } @Override public int hashCode() { return Objects.hash(id, name, price, totalAmount, soldAmount); } } <file_sep>package com.kryvokin.onlineshop.model; import com.kryvokin.onlineshop.model.compositekey.OrderHasItemKey; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.NoArgsConstructor; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.MapsId; import javax.persistence.Table; @Entity @Table(name = "orders_has_item") @Builder @NoArgsConstructor @AllArgsConstructor public class OrderHasItem { @EmbeddedId private OrderHasItemKey id; @ManyToOne @MapsId("orders_id") @JoinColumn(name = "orders_id") private Order order; @ManyToOne @MapsId("item_id") @JoinColumn(name = "item_id") private Product item; private int amount; public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } public Product getItem() { return item; } public void setItem(Product item) { this.item = item; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } } <file_sep>package com.kryvokin.onlineshop.model; import java.util.HashMap; import java.util.Map; public class Cart { private Map<Product, Integer> cart = new HashMap<>(); public Map<Product, Integer> getCart() { return cart; } } <file_sep>package com.kryvokin.onlineshop.model; public enum Local { RU, EN } <file_sep>package com.kryvokin.onlineshop.repository; import com.kryvokin.onlineshop.model.User; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends PagingAndSortingRepository<User, Integer> { User getUserByEmail(String email); }
39e2bcfe97752d27b22c6261c92a0ad7028285ce
[ "Java", "SQL", "INI" ]
18
Java
mariakryvokin/springboot_mvc
5995eee1d9365c63aafd46601f61c8d4d578b7bd
13377818b1565662d9d0f09d6f99537cea124606
refs/heads/master
<repo_name>sivitry/web2csv<file_sep>/web2csv2bow.py # coding: utf-8 # In[129]: import collections, re import json, csv documents = [] with open("VivianChen_PaperList.csv") as f: for line in f: documents.append(line.split(",")[1]) document = "\'"+document+"\'" bagsofwords = [ collections.Counter(re.findall(r'\w+', txt)) for txt in documents] sumbags = sum(bagsofwords, collections.Counter()) #print(bagsofwords) #rint(sumbags) #print(list(sumbags)) print(sumbags.items()) csvfp = open("output.csv", "w") csvwriter = csv.writer(csvfp) csvwriter.writerows(sumbags.items()) csvfp.close() <file_sep>/README.md # web2csv extract data from html and download as csv file Because escape characters problem, please download raw file, https://github.com/sivitry/web2csv/raw/master/README.md // extract data from html and download as csv file // 2017/08/12 sivitry [example url] https://scholar.google.com/citations?user=jQLg-_UAAAAJ&hl=en [Target XPath] '//*[@id="gsc_a_b"]/tr[55]/td[1]/a' '//*[@id="gsc_a_b"]/tr[56]/td[1]/a' //*[@id="gsc_a_b"]/tr[1] [XPath Pattern] '//*[@id="gsc_a_b"]/tr/td[1]/a' [Chrome Debug] // get all paper node x = $x('//*[@id="gsc_a_b"]/tr') // extract paper name and concate // PaperTitle: x[a].getElementsByTagName('a')[0].innerText.replace(/\,/g,"_") // Year: x[a].getElementsByTagName('td')[2].getElementsByTagName('span')[0].innerText // ConfName: x[a].getElementsByTagName('div')[1].innerText.replace(/\,/g, "_") // CitedBy: x[a].getElementsByTagName('a')[1].innerText s = ""; s = s+"#, PaperTitle, Year, ConfName, CitedBy \n" for(a in x) s = s + (parseInt(a)+1) +"," +x[a].getElementsByTagName('a')[0].innerText.replace(/\,/g,"_") +"," +x[a].getElementsByTagName('td')[2].getElementsByTagName('span')[0].innerText +"," +x[a].getElementsByTagName('div')[1].innerText.replace(/\,/g, "_") +"," +x[a].getElementsByTagName('a')[1].innerText +"," +"\n"; // prepare http header and data to be download csvContent = "data:text/csv;charset=utf-8,"; csvContent = csvContent+s; // encodeURI and execute download action var encodedUri = encodeURI(csvContent); var link = document.createElement("a"); link.setAttribute("href", encodedUri); link.setAttribute("download", "my_data.csv"); document.body.appendChild(link); link.click();
80bc9a3b4200b4c12c24e9d1e2deb0baace517df
[ "Markdown", "Python" ]
2
Python
sivitry/web2csv
4de2961cf625ac17b85fb0abcf0a56e0c7070328
5723f4ad5fefc6dc119afa13edbb611b3973fcd3
refs/heads/master
<repo_name>Jrenner07/TP_appli_mobile_interfaces<file_sep>/TP_Interfaces_simples/app/src/main/java/julienco/tp_interfaces_simples/act_Menu.java package julienco.tp_interfaces_simples; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class act_Menu extends AppCompatActivity { final String Nom = "user_Nom"; final String Prenom = "user_Prenom"; final String DateDeNaissance = "user_DateDeNaissance"; final String Email = "user_Email"; final String Adresse = "user_Adresse"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_act__menu); Button ButtonAccueil = (Button)findViewById(R.id.button2_accueil); Button ButtonSport = (Button)findViewById(R.id.button_sport); final TextView Tnom = (TextView)findViewById(R.id.Text_NomPreview); final TextView Tprenom = (TextView)findViewById(R.id.Text_PrenomPreview); final TextView Tdatedenaissance = (TextView)findViewById(R.id.Text_DateDeNaissancePreview); final TextView Temail = (TextView)findViewById(R.id.Text_EmailPreview); final TextView Tadresse = (TextView)findViewById(R.id.Text_AdressePreview); Intent monIntent = getIntent(); Tnom.setText(monIntent.getStringExtra(Nom)); Tprenom.setText(monIntent.getStringExtra(Prenom)); Tdatedenaissance.setText(monIntent.getStringExtra(DateDeNaissance)); Temail.setText(monIntent.getStringExtra(Email)); Tadresse.setText(monIntent.getStringExtra(Adresse)); ButtonAccueil.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent menuIntent = new Intent(act_Menu.this, MainActivity.class); startActivity(menuIntent); } }); } } <file_sep>/TP_Interfaces_simples/app/src/main/java/julienco/tp_interfaces_simples/act_authentification.java package julienco.tp_interfaces_simples; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import org.w3c.dom.Text; public class act_authentification extends AppCompatActivity { final String Nom = "user_Nom"; final String Prenom = "user_Prenom"; final String DateDeNaissance = "user_DateDeNaissance"; final String Email = "user_Email"; final String Adresse = "user_Adresse"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_act_authentification); Button MyButton = (Button)findViewById(R.id.button_Valide); final TextView Tnom = (TextView)findViewById(R.id.Text_Nom); final TextView Tprenom = (TextView)findViewById(R.id.Text_Prenom); final TextView TdateDeNaissance = (TextView)findViewById(R.id.Text_DateDeNaissance); final TextView Temail = (TextView)findViewById(R.id.Text_Email); final TextView Tadresse = (TextView)findViewById(R.id.Text_Adresse); MyButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent monIntent = new Intent(act_authentification.this, act_Menu.class); monIntent.putExtra(Nom, Tnom.getText().toString()); monIntent.putExtra(Prenom, Tprenom.getText().toString()); monIntent.putExtra(DateDeNaissance, TdateDeNaissance.getText().toString()); monIntent.putExtra(Email, Temail.getText().toString()); monIntent.putExtra(Adresse, Tadresse.getText().toString()); startActivity(monIntent); } }); } }
0baee7b693e51de36428b0ba93031282101610be
[ "Java" ]
2
Java
Jrenner07/TP_appli_mobile_interfaces
0edbf564a6abcece5aa2d547e721078861bf68fe
69213612d29b33eecaa31bebcf2e3cd16bfd6e82
refs/heads/master
<file_sep>using System; namespace SalesWebMVC.Services.Exceptions { public class IntegrityExceptiom : ApplicationException { public IntegrityExceptiom(string message) : base(message) { } } }
79996bcc566d2a080d94b9e8c08b5fd847c49c6e
[ "C#" ]
1
C#
raziisz/workshop-asp-net-core-mvc
55544a3d10d28a4733c420fc875c07c02292f351
d99306b8e0fc3cee0837bb6e87f591fe343c6b36
refs/heads/master
<file_sep>import {List} from './list' export class Board { name: string; lists: List[]; }<file_sep>import { Component } from '@angular/core'; import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms' import { NavController } from 'ionic-angular'; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { creatingBoard = false; newBoard = { name: '' }; newBoardForm = this.fb.group({ 'name': ['', Validators.compose([Validators.required, Validators.minLength(2)])] }) constructor(public navCtrl: NavController, public fb: FormBuilder) { } createNewBoard(event) { if(this.newBoardForm.valid) { console.log(this.newBoardForm.value) console.log("create board") } else { console.log("you suck") } } } <file_sep>import {Task} from './task'; export class List { name: string; tasks: Task[]; }
53fd73042c799885772ff83b4c51badac9e2dea4
[ "TypeScript" ]
3
TypeScript
spencerhenze/IonicKanban
913ce30f78deb230fd05e6a3a720f0d702575a72
8d3cf6b7b975b7584239e46ac629d36a1adae1d8
refs/heads/master
<file_sep>import movies from '../../data/movies'; export function get(request, response, next) { const { slug } = request.params; const movie = movies.find(movie => movie.slug === slug); if (movie) { response.writeHead(200, { 'Content-Type': 'application/json' }); response.end(JSON.stringify(movie)); } else { response.writeHead(404, { 'Content-Type': 'application/json' }); response.end(JSON.stringify({ message: 'Movie not found', })); } } <file_sep>export default [ { title: 'Narcos', slug: 'narcos', image: 'https://m.media-amazon.com/images/M/MV5BNmFjODU3YzgtMGUwNC00ZGI3LWFkZjQtMjkxZDc3NmQ1MzcyXkEyXkFqcGdeQXVyNjUwNzk3NDc@._V1_UX182_CR0,0,182,268_AL_.jpg', score: 8.8, description: 'A chronicled look at the criminal exploits of Colombian drug lord Pablo Escobar, as well as the many other drug kingpins who plagued the country through the years.', creators: '<NAME>, <NAME>, <NAME>', stars: '<NAME>, <NAME>, <NAME>' }, { title: 'One Last Deal', slug: 'one-last-deal', image: 'https://m.media-amazon.com/images/M/MV5BMjlhNjBlNGYtNzVlMC00MzJiLTg3MjAtZmEyOTBhY2VkMDA1XkEyXkFqcGdeQXVyMDA2ODM5NQ@@._V1_UY268_CR3,0,182,268_AL_.jpg', score: 7.4, description: 'An elderly art dealer investigates the history behind an unsigned painting that promises to bring his suffering career to a successful end.', creators: '<NAME>, <NAME>', stars: 'Heikki Nousiainen, Pirjo Lonka, <NAME>' }, { title: 'True Detective', slug: 'true-detective', image: 'https://m.media-amazon.com/images/M/MV5BMTUwMGM2ZmYtZGEyZC00OWQyLWI2Y2QtMTdjYzMxZGJmNjhjXkEyXkFqcGdeQXVyNjU2ODM5MjU@._V1_UX182_CR0,0,182,268_AL_.jpg', score: 9.0, description: 'Seasonal anthology series in which police investigations unearth the personal and professional secrets of those involved, both within and outside the law.', creators: '<NAME>', stars: '<NAME>, <NAME>, <NAME>' }, { title: 'The OA', slug: 'the-oa', image: 'https://m.media-amazon.com/images/M/MV5BMTY5OTkwNDkzOF5BMl5BanBnXkFtZTgwMDEyNzI1NzM@._V1_UX182_CR0,0,182,268_AL_.jpg', score: 7.8, description: 'Having gone missing seven years ago, the previously blind Prairie returns home, now in her twenties with her sight restored. While many believe she is a miracle, others worry that she could be dangerous.', creators: '<NAME>, <NAME>', stars: '<NAME>, <NAME>, <NAME>' }, { title: 'Sense8', slug: 'sense8', image: 'https://m.media-amazon.com/images/M/MV5BMjA4MTEyMzcwMl5BMl5BanBnXkFtZTgwMTIwODczNTM@._V1_UX182_CR0,0,182,268_AL_.jpg', score: 8.3, description: 'A group of people around the world are suddenly linked mentally, and must find a way to survive being hunted by those who see them as a threat to the world\'s order.', creators: '<NAME>, <NAME>, <NAME>', stars: 'Bae Doona, <NAME>, <NAME>' }, { title: 'Westworld', slug: 'westworld', image: 'https://m.media-amazon.com/images/M/<KEY>qcGdeQXVyMDM2NDM2MQ@@._V1_UX182_CR0,0,182,268_AL_.jpg', score: 8.6, description: 'Set at the intersection of the near future and the reimagined past, explore a world in which every human appetite can be indulged without consequence.', creators: '<NAME>, <NAME>', stars: '<NAME>, <NAME>, <NAME>' }, ];<file_sep><h1 align="center"> <img src="imdb-sapper.png" alt="Small IMDB clone made with Sapper" /> </h1> <h4 align="center">You can read the written tutorial about the implementation on <strong><a href="https://www.webtips.dev/how-to-build-an-imdb-clone-using-sapper">webtips.dev</a></strong> 🎥</h4>
2698e62ade7ba2e228122c10a15cbcb89a0df3f6
[ "JavaScript", "Markdown" ]
3
JavaScript
flowforfrank/imdb-sapper
db91cb307dc0eee21e7e4ba5b399c072df3dfc43
5440714781fd543dba687296b80fbdfec81b907b
refs/heads/master
<file_sep>"use strict"; var express = require('express'); var app = express(); var server = require('http').Server(app); var io = require('socket.io')(server); // Listen on port 3000 server.listen(3000); // Request for static template app.get('/', function (req, res) { res.sendFile(`${__dirname}/view.html`); }); // Temporary User management ***************************** var users = { assignName(socket){ let rand = Math.random().toString(36).substring(7); users[socket.id] = `User${rand}`; } }; // Socket ********************************************* io.on('connection', function (socket) { // Give users arbitrary name on connection users.assignName(socket); // Emit username to client socket.emit('connected', { name: `${users[socket.id]}` }); socket.on('newMessage', function (data) { // broadcast the received message to all the other clients socket.broadcast.emit('appendMsg', { name: users[socket.id], message: data } ); }); socket.on('nameChange', function(name){ users[socket.id] = name; }) });
344b41f7cea16e7aa378ffeb182a7eaf2c5e7aa7
[ "JavaScript" ]
1
JavaScript
Jareechang/Node-chat-system
1e424e3c15d92e00e0ddd6285fe448be8bf91f4a
fd128621380a82e0ed088a9b793a81fcdd37c5f8
refs/heads/master
<file_sep>from .util import * from .priors import * Areas = namedtuple('Areas', "coordinates geoms") ############################### # Make an Exclusion Calculator class ExclusionCalculator(object): """The ExclusionCalculator object makes land eligibility (LE) analyses easy and quick. Once initialized to a particular region, the ExclusionCalculator object can be used to incorporate any geospatial dataset (so long as it is interpretable by GDAL) into the LE analysis. Note: ----- By default, ExclusionCalculator is always initialized at 100x100 meter resolution in the EPSG3035 projection system. This is well-suited to LE analyses in Europe, however if another region is being investigated or else if another resolution or projection system is desired for any other reason, this can be incorporated as well during the initialization stage. If you need to find a new projection system for your analyses, the following website is helpful: http://spatialreference.org/ref/epsg/ Initialization: --------------- * ExclusionCalculator can be initialized by passing a specific vector file describing the investigation region: >>> ec = ExclusionCalculator(<path>) * A particular srs and resolution can be used: >>> ec = ExclusionCalculator(<path>, pixelRes=0.001, srs='latlon') * In fact, the ExclusionCalculator initialization is simply a call to geokit.RegionMask.load, so see that for more information. This also means that any geokit.RegoinMask object can be used to initialize the ExclusionCalculator >>> rm = geokit.RegionMask.load(<path>, pad=..., srs=..., pixelRes=..., ...) >>> ec = ExclusionCalculator(rm) Usage: ------ * The ExclusionCalculator object contains a member name "availability", which contains the most up to date result of the LE analysis - Just after initialization, the the availability matrix is filled with 100's, meaning that all locations are available - After excluding locations based off various geospatial datasets, cells in the availability matrix are changed to a value between 0 and 100, where 0 means completely unavailable, 100 means fully available, and intermediate values indicate a pixel which is only partly excluded. * Exclusions can be applied by using one of the 'excludeVectorType', 'excludeRasterType', or 'excludePrior' methods - The correct method to use depends on the format of the datasource used for exclusions * After all exclusions have been applied... - The 'draw' method can be used to visualize the result - The 'save' method will save the result to a raster file on disc - The 'availability' member can be used to extract the availability matrix as a NumPy matrix for further usage """ typicalExclusions = { "access_distance": (5000, None ), "agriculture_proximity": (None, 50 ), "agriculture_arable_proximity": (None, 50 ), "agriculture_pasture_proximity": (None, 50 ), "agriculture_permanent_crop_proximity": (None, 50 ), "agriculture_heterogeneous_proximity": (None, 50 ), "airfield_proximity": (None, 3000 ), "airport_proximity": (None, 5000 ), "connection_distance": (10000, None ), "dni_threshold": (None, 3.0 ), "elevation_threshold": (1800, None ), "ghi_threshold": (None, 3.0 ), "industrial_proximity": (None, 300 ), "lake_proximity": (None, 400 ), "mining_proximity": (None, 100 ), "ocean_proximity": (None, 1000 ), "power_line_proximity": (None, 200 ), "protected_biosphere_proximity": (None, 300 ), "protected_bird_proximity": (None, 1500 ), "protected_habitat_proximity": (None, 1500 ), "protected_landscape_proximity": (None, 500 ), "protected_natural_monument_proximity": (None, 1000 ), "protected_park_proximity": (None, 1000 ), "protected_reserve_proximity": (None, 500 ), "protected_wilderness_proximity": (None, 1000 ), "camping_proximity": (None, 1000), "touristic_proximity": (None, 800), "leisure_proximity": (None, 1000), "railway_proximity": (None, 150 ), "river_proximity": (None, 200 ), "roads_proximity": (None, 150 ), "roads_main_proximity": (None, 200 ), "roads_secondary_proximity": (None, 100 ), "sand_proximity": (None, 1000 ), "settlement_proximity": (None, 500 ), "settlement_urban_proximity": (None, 1000 ), "slope_threshold": (10, None ), "slope_north_facing_threshold": (3, None ), "wetland_proximity": (None, 1000 ), "waterbody_proximity": (None, 300 ), "windspeed_100m_threshold": (None, 4.5 ), "windspeed_50m_threshold": (None, 4.5 ), "woodland_proximity": (None, 300 ), "woodland_coniferous_proximity": (None, 300 ), "woodland_deciduous_proximity": (None, 300 ), "woodland_mixed_proximity": (None, 300 )} def __init__(s, region, srs=3035, pixelRes=100, where=None, padExtent=0, **kwargs): """Initialize the ExclusionCalculator Parameters: ----------- region : str, geokit.RegionMask The regional definition for the land eligibility analysis * If given as a string, must be a path to a vector file * If given as a RegionMask, it is taken directly despite other arguments srs : Anything acceptable to geokit.srs.loadSRS() The srs context of the generated RegionMask object * The default srs EPSG3035 is only valid for a European context * If an integer is given, it is treated as an EPSG identifier - Look here for options: http://spatialreference.org/ref/epsg/ * Only effective if 'region' is a path to a vector pixelRes : float or tuple The generated RegionMask's native pixel size(s) * If float : A pixel size to apply to both the X and Y dimension * If (float float) : An X-dimension and Y-dimension pixel size * Only effective if 'region' is a path to a vector where : str, int; optional If string -> An SQL-like where statement to apply to the source If int -> The feature's ID within the vector dataset * Feature attribute name do not need quotes * String values should be wrapped in 'single quotes' * Only effective if 'region' is a path to a vector Example: If the source vector has a string attribute called "ISO" and a integer attribute called "POP", you could use.... where = "ISO='DEU' AND POP>1000" padExtent : float; optional An amount by which to pad the extent before generating the RegionMask * Only effective if 'region' is a path to a vector kwargs: * Keyword arguments are passed on to a call to geokit.RegionMask.load * Only take effect when the 'region' argument is a string """ # load the region s.region = gk.RegionMask.load(region, srs=srs, pixelRes=pixelRes, where=where, padExtent=padExtent, **kwargs) s.srs = s.region.srs s.maskPixels = s.region.mask.sum() # Make the total availability matrix s._availability = np.array(s.region.mask, dtype=np.uint8)*100 #s._availability[~s.region.mask] = 255 # Make a list of item coords s.itemCoords=None s._itemCoords=None s._areas=None def save(s, output, threshold=None, **kwargs): """Save the current availability matrix to a raster file Output will be a byte-valued raster with the following convention: 0 -> unavailable 1..99 -> Semi-available 100 -> fully eligibile 255 -> "no data" (out of region) Parameters: ----------- output : str The path of the output raster file * Must end in ".tif" threshold : float; optional The acceptable threshold indicating an available pixel * Use this to process the availability matrix before saving it (will save a little bit of space) kwargs: * All keyword arguments are passed on to a call to geokit.RegionMask.createRaster * Most notably: - 'dtype' is used to define the data type of the resulting raster - 'overwrite' is used to force overwrite an existing file """ meta={ "description":"The availability of each pixel", "units":"percent-available" } data = s.availability if not threshold is None: data = (data>=threshold).astype(np.uint8)*100 data[~s.region.mask] = 255 s.region.createRaster(output=output, data=data, noData=255, meta=meta, **kwargs) def draw(s, ax=None, goodColor="#9bbb59", excludedColor="#a6161a", legend=True, legendargs={"loc":"lower left"}, dataScalingFactor=1, geomSimplificationFactor=5000, **kwargs): """Draw the current availability matrix on a matplotlib figure Note: ----- To save the result somewhere, call 'plt.savefig(...)' immediately calling this function. To directly view the result, call 'plt.show()' Parameters: ----------- ax: matplotlib axis object; optional The axis to draw the figure onto * If given as 'None', then a fresh axis will be produced and displayed or saved immediately goodColor: A matplotlib color The color to apply to 'good' locations (having a value of 100) excludedColor: A matplotlib color The color to apply to 'excluded' locations (having a value of 0) legend: bool; optional If True, a legend will be drawn legendargs: dict; optional Arguments to pass to the drawn legend (via axes.legend(...)) dataScalingFactor: int; optional A down scaling factor to apply to the visualized availability matrix * Use this when visualizing a large areas * seting this to 1 will apply no scaling geomSimplificationFactor: int A down scaling factor to apply when drawing the geometry borders of the ExclusionCalculator's region * Use this when the region's geometry is extremely detailed compared to the scale over which it is drawn * Setting this to None will apply no simplification **kwargs: All keyword arguments are passed on to a call to geokit.drawImage Returns: -------- matplotlib axes object """ # import some things from matplotlib.colors import LinearSegmentedColormap # First draw the availability matrix b2g = LinearSegmentedColormap.from_list('bad_to_good',[excludedColor,goodColor]) if not "figsize" in kwargs: ratio = s.region.mask.shape[1]/s.region.mask.shape[0] kwargs["figsize"] = (8*ratio*1.2, 8) kwargs["topMargin"] = kwargs.get("topMargin", 0.01) kwargs["bottomMargin"] = kwargs.get("bottomMargin", 0.02) kwargs["rightMargin"] = kwargs.get("rightMargin", 0.01) kwargs["leftMargin"] = kwargs.get("leftMargin", 0.02) kwargs["hideAxis"] = kwargs.get("hideAxis", True) kwargs["cmap"] = kwargs.get("cmap", b2g) kwargs["cbar"] = kwargs.get("cbar", False) kwargs["vmin"] = kwargs.get("vmin", 0) kwargs["vmax"] = kwargs.get("vmax", 100) kwargs["cbarTitle"] = kwargs.get("cbarTitle", "Pixel Availability") axh1 = s.region.drawImage( s.availability, ax=ax, drawSelf=False, scaling=dataScalingFactor, **kwargs) # # Draw the mask to blank out the out of region areas # w2a = LinearSegmentedColormap.from_list('white_to_alpha',[(1,1,1,1),(1,1,1,0)]) # axh2 = s.region.drawImage( s.region.mask, ax=axh1, drawSelf=False, cmap=w2a, cbar=False) # Draw the Regional geometry axh3 = s.region.drawSelf( fc='None', ax=axh1, linewidth=2, simplificationFactor=geomSimplificationFactor ) # Draw Points, maybe? if not s._itemCoords is None: axh1.ax.plot(s._itemCoords[:,0],s._itemCoords[:,1],'ok') # Draw Areas, maybe? if not s._areas is None: gk.drawGeoms( s._areas, srs=s.region.srs, ax=axh1, fc='None', ec="k", linewidth=1, simplificationFactor=None ) # Make legend? if legend: from matplotlib.patches import Patch p = s.percentAvailable a = s.region.mask.sum(dtype=np.int64)*s.region.pixelWidth*s.region.pixelHeight areaLabel = s.region.srs.GetAttrValue("Unit").lower() if areaLabel=="metre" or areaLabel=="meter": a = a/1000000 areaLabel = "km" elif areaLabel=="feet" or areaLabel=="foot": areaLabel = "ft" elif areaLabel=="degree": areaLabel = "deg" if a<0.001: regionLabel = "{0:.3e} ${1}^2$".format(a, areaLabel) elif a<0: regionLabel = "{0:.4f} ${1}^2$".format(a, areaLabel) elif a<1000: regionLabel = "{0:.2f} ${1}^2$".format(a, areaLabel) else: regionLabel = "{0:,.0f} ${1}^2$".format(a, areaLabel) patches = [ Patch( ec="k", fc="None", linewidth=3, label=regionLabel), Patch( color=excludedColor, label="Excluded: %.2f%%"%(100-p) ), Patch( color=goodColor, label="Eligible: %.2f%%"%(p) ), ] if not s._itemCoords is None: h = axh1.ax.plot([],[],'ok', label="Items: {:,d}".format(s._itemCoords.shape[0]) ) patches.append( h[0] ) _legendargs = dict(loc="lower right", fontsize=14) _legendargs.update(legendargs) axh1.ax.legend(handles=patches, **_legendargs) # Done!! return axh1.ax @property def availability(s): """A matrix containing the availability of each location after all applied exclusions. * A value of 100 is interpreted as fully available * A value of 0 is interpreted as completely excluded * In between values are...in between""" tmp = s._availability.astype(np.float32) tmp[~s.region.mask] = np.nan return tmp @property def percentAvailable(s): """The percent of the region which remains available""" return s._availability.sum(dtype=np.int64)/s.region.mask.sum() @property def areaAvailable(s): """The area of the region which remains available * Units are defined by the srs used to initialize the ExclusionCalculator""" return s._availability.sum(dtype=np.int64)*s.region.pixelWidth*s.region.pixelHeight/100 ## General excluding functions def excludeRasterType(s, source, value=None, buffer=None, resolutionDiv=1, prewarp=False, invert=False, mode="exclude", **kwargs): """Exclude areas based off the values in a raster datasource Parameters: ----------- source : str or gdal.Dataset The raster datasource defining the criteria values for each location value : tuple, or numeric The exact value, or value range to exclude * If Numeric, should be The exact value to exclude * Generally this should only be done when the raster datasource contains integer values, otherwise a range of values should be used to avoid float comparison errors * If ( Numeric, Numeric ), the low and high boundary describing the range of values to exclude * If either boundary is given as None, then it is interpreted as unlimited buffer : float; optional A buffer region to add around the indicated pixels * Units are in the RegionMask's srs * The buffering occurs AFTER the indication and warping step and so it may not represent the original dataset exactly - Buffering can be made more accurate by increasing the 'resolutionDiv' input resolutionDiv : int; optional The factor by which to divide the RegionMask's native resolution * This is useful if you need to represent very fine details prewarp : bool or str or dict; optional When given, the source will be warped to the calculator's mask context before processing * If True, warping will be performed using the bilinear scheme * If str, warp using the indicated resampleAlgorithm - options: 'near', 'bilinear', 'cubic', 'average' * If dict, a dictionary of arguments is expected - These are passed along to geokit.RegionMask.warp invert: bool; optional If True, flip indications mode: string; optional * If 'exclude', then the indicated pixels are subtracted from the current availability matrix * If 'include', then the indicated pixel are added back into the availability matrix kwargs * All other keyword arguments are passed on to a call to geokit.RegionMask.indicateValues """ # Do prewarp, if needed if prewarp: prewarpArgs = dict(resampleAlg="bilinear") if isinstance(prewarp, str): prewarpArgs["resampleAlg"] = prewarp elif isinstance(prewarp, dict): prewarpArgs.update(prewarp) source = s.region.warp(source, returnAsSource=True, **prewarpArgs) # Indicate on the source areas = (s.region.indicateValues(source, value, buffer=buffer, resolutionDiv=resolutionDiv, applyMask=False, **kwargs)*100).astype(np.uint8) # exclude the indicated area from the total availability if mode == "exclude": s._availability = np.min([s._availability, areas if invert else 100-areas],axis=0) elif mode == "include": s._availability = np.max([s._availability, 100-areas if invert else areas],axis=0) s._availability[~s.region.mask] = 0 else: raise GlaesError("mode must be 'exclude' or 'include'") def excludeVectorType(s, source, where=None, buffer=None, bufferMethod='geom', invert=False, mode="exclude", resolutionDiv=1, **kwargs): """Exclude areas based off the features in a vector datasource Parameters: ----------- source : str or gdal.Dataset The raster datasource defining the criteria values for each location where : str A filtering statement to apply to the datasource before the indication * This is an SQL like statement which can operate on features in the datasource * For tips, see "http://www.gdal.org/ogr_sql.html" * For example... - If the datasource had features which each have an attribute called 'type' and only features with the type "protected" are wanted, the correct statement would be: where="type='protected'" buffer : float; optional A buffer region to add around the indicated pixels * Units are in the RegionMask's srs bufferMethod : str; optional An indicator determining the method to use when buffereing * Options are: 'geom' and 'area' * If 'geom', the function will attempt to grow each of the geometries directly using the ogr library - This can fail sometimes when the geometries are particularly complex or if some of the geometries are not valid (as in, they have self-intersections) * If 'area', the function will first rasterize the raw geometries and will then apply the buffer to the indicated pixels - This is the safer option although is not as accurate as the 'geom' option since it does not capture the exact edges of the geometries - This method can be made more accurate by increasing the 'resolutionDiv' input resolutionDiv : int; optional The factor by which to divide the RegionMask's native resolution * This is useful if you need to represent very fine details invert: bool; optional If True, flip indications mode: string; optional * If 'exclude', then the indicated pixels are subtracted from the current availability matrix * If 'include', then the indicated pixel are added back into the availability matrix kwargs * All other keyword arguments are passed on to a call to geokit.RegionMask.indicateFeatures """ if isinstance(source, PriorSource): edgeI = kwargs.pop("edgeIndex", np.argwhere(source.edges==source.typicalExclusion)) source = source.generateVectorFromEdge( s.region.extent, edgeIndex=edgeI ) # Indicate on the source areas = (s.region.indicateFeatures(source, where=where, buffer=buffer, resolutionDiv=resolutionDiv, bufferMethod=bufferMethod, applyMask=False, **kwargs)*100).astype(np.uint8) # exclude the indicated area from the total availability if mode == "exclude": s._availability = np.min([s._availability, areas if invert else 100-areas],axis=0) elif mode == "include": s._availability = np.max([s._availability, 100-areas if invert else areas],axis=0) s._availability[~s.region.mask] = 0 else: raise GlaesError("mode must be 'exclude' or 'include'") def excludePrior(s, prior, value=None, buffer=None, invert=False, mode="exclude", **kwargs): """Exclude areas based off the values in one of the Prior data sources * The Prior datasources are currently only defined over Europe * All Prior datasources are defined in the EPSG3035 projection system with 100x100 meter resolution * For each call to excludePrior, a temporary raster datasource is generated around the ExclusionCalculator's region, after which a call to ExclusionCalculator.excludeRasterType is made, therefore all the same inputs apply here as well Parameters: ----------- source : str or gdal.Dataset The raster datasource defining the criteria values for each location value : tuple or numeric The exact value, or value range to exclude * If Numeric, should be The exact value to exclude * Generally this should only be done when the raster datasource contains integer values, otherwise a range of values should be used to avoid float comparison errors * If ( Numeric, Numeric ), the low and high boundary describing the range of values to exclude * If either boundary is given as None, then it is interpreted as unlimited buffer : float; optional A buffer region to add around the indicated pixels * Units are in the RegionMask's srs * The buffering occurs AFTER the indication and warping step and so it may not represent the original dataset exactly - Buffering can be made more accurate by increasing the 'resolutionDiv' input invert: bool; optional If True, flip indications mode: string; optional * If 'exclude', then the indicated pixels are subtracted from the current availability matrix * If 'include', then the indicated pixel are added back into the availability matrix kwargs * All other keyword arguments are passed on to a call to geokit.RegionMask.indicateValues """ # make sure we have a Prior object if isinstance(prior, str): prior = Priors[prior] if not isinstance( prior, PriorSource): raise GlaesError("'prior' input must be a Prior object or an associated string") # try to get the default value if one isn't given if value is None: try: value = s.typicalExclusions[prior.displayName] except KeyError: raise GlaesError("Could not find a default exclusion set for %s"%prior.displayName) # Check the value input if isinstance(value, tuple): # Check the boundaries if not value[0] is None: prior.containsValue(value[0], True) if not value[1] is None: prior.containsValue(value[1], True) # Check edges if not value[0] is None: prior.valueOnEdge(value[0], True) if not value[1] is None: prior.valueOnEdge(value[1], True) else: if not value==0: warn("It is advisable to exclude by a value range instead of a singular value when using the Prior datasets", UserWarning) # Project to 'index space' try: v1, v2 = value if not v1 is None: v1 = np.interp(v1, prior._values_wide, np.arange(prior._values_wide.size)) if not v2 is None: v2 = np.interp(v2, prior._values_wide, np.arange(prior._values_wide.size)) value = (v1,v2) except TypeError: if not value == 0: value = np.interp(value, prior._values_wide, np.arange(prior._values_wide.size)) #source = prior.generateRaster( s.region.extent,) # Call the excluder s.excludeRasterType( prior.path, value=value, invert=invert, mode=mode, **kwargs) def excludeRegionEdge(s, buffer): """Exclude some distance from the region's edge Parameters: ----------- buffer : float A buffer region to add around the indicated pixels * Units are in the RegionMask's srs """ s.excludeVectorType(s.region.vector, buffer=-buffer, invert=True) def shrinkAvailability(s, dist, threshold=50): """Shrinks the current availability by a given distance in the given SRS""" geom = gk.geom.polygonizeMask(s._availability>=threshold, bounds=s.region.extent.xyXY, srs=s.region.srs, flat=False) geom = [g.Buffer(-dist) for g in geom] newAvail = (s.region.indicateGeoms(geom)*100).astype(np.uint8) s._availability = newAvail def pruneIsolatedAreas(s, minSize, threshold=50): """Removes contiguous areas which are smaller than 'minSize' * minSize is given in units of the calculator's srs """ # Create a vector file of geometries larger than 'minSize' geoms = gk.geom.polygonizeMask( s._availability>=threshold, bounds=s.region.extent.xyXY, srs=s.region.srs, flat=False) geoms = list(filter( lambda x: x.Area()>=minSize, geoms )) vec = gk.core.util.quickVector(geoms) # Replace current availability matrix s._availability = s.region.indicateFeatures(vec, applyMask=False).astype(np.uint8 )*100 <file_sep>from helpers import * def test_multiple_exclusions(): pr = gl.core.priors.PriorSource(priorSample) ec = gl.ExclusionCalculator(aachenShape) # apply exclusions ec.excludePrior(pr, valueMax=400) ec.excludeVectorType(cddaVector, where="YEAR>2000") ec.excludeRasterType(clcRaster, valueMax=12) if not (np.isclose(ec.availability.mean(), 14.79785738387133, 1e-6) and np.isclose(np.nanstd(ec.availability), 35.249694265461024, 1e-6)): raise RuntimeError("Multiple Exclusions - FAIL") def test_ExclusionCalculator___init__(): # Test by giving a shapefile ec = gl.ExclusionCalculator(aachenShape) compare(ec.region.mask.shape ,(509, 304) ) compareF(ec.region.mask.sum() , 70944 ) compareF(ec.region.mask.std(), 0.498273451386) # Test by giving a region mask rm = gk.RegionMask.load(aachenShape, padExtent=5000) ec = gl.ExclusionCalculator(rm) compare(ec.region.mask.shape ,(609, 404) ) compareF(ec.region.mask.sum() , 70944 ) compareF(ec.region.mask.std(), 0.45299387483) # Test by giving a region mask with different resolution and srs rm = gk.RegionMask.load(aachenShape, srs=gk.srs.EPSG4326, pixelRes=0.001) ec = gl.ExclusionCalculator(rm) compare(ec.region.mask.shape ,(457, 446) ) compareF(ec.region.mask.sum() , 90296 ) compareF(ec.region.mask.std(), 0.496741981394) print( "ExclusionCalculator___init__ passed") def test_ExclusionCalculator_save(): ec = gl.ExclusionCalculator(aachenShape) ec.save("results/save1.tif") mat = gk.raster.extractMatrix("results/save1.tif") compare( np.nansum(mat-ec.availability), 0 ) compareF(np.nansum(mat), 28461360) compareF(np.nanstd(mat), 77.2323849648) print( "ExclusionCalculator_save passed") def test_ExclusionCalculator_draw(): ec = gl.ExclusionCalculator(aachenShape) ec._availability[:, 140:160] = 0 ec._availability[140:160, :] = 0 ec.draw() plt.savefig("results/DrawnImage.png", dpi=200) plt.close() print( "ExclusionCalculator_draw passed, but outputs need to be checked") def test_ExclusionCalculator_excludeRasterType(): # exclude single value ec = gl.ExclusionCalculator(aachenShape) ec.excludeRasterType(clcRaster, 12) compareF(np.nanmean(ec.availability), 82.8033, "excludeRasterType: Single value exclusion") compareF(np.nanstd(ec.availability), 37.73514175, "excludeRasterType: Single value exclusion") # exclude value range ec = gl.ExclusionCalculator(aachenShape) ec.excludeRasterType(clcRaster, (5,12)) compareF(np.nanmean(ec.availability), 81.16260529, "excludeRasterType: Value range exclusion") compareF(np.nanstd(ec.availability), 39.10104752, "excludeRasterType: Value range exclusion") # exclude value maximum ecMax12 = gl.ExclusionCalculator(aachenShape) ecMax12.excludeRasterType(clcRaster, (None,12)) compareF(np.nanmean(ecMax12.availability), 58.52362442, "excludeRasterType: Value maximum exclusion") compareF(np.nanstd(ecMax12.availability), 49.26812363, "excludeRasterType: Value maximum exclusion") # exclude value minimum ecMin13 = gl.ExclusionCalculator(aachenShape) ecMin13.excludeRasterType(clcRaster, (13,None)) compareF(np.nanmean(ecMin13.availability), 41.47637558, "excludeRasterType: Value minimum exclusion") compareF(np.nanstd(ecMin13.availability), 49.26812363, "excludeRasterType: Value minimum exclusion") # Make sure min and max align if ((ecMax12.availability[ecMax12.region.mask]>0.5) == (ecMin13.availability[ecMax12.region.mask]>0.5)).any(): raise RuntimeError("excludeRasterType: minimum and maximum overlap - FAIL") if not (np.logical_or( ecMax12.availability[ecMax12.region.mask]>0.5, ecMin13.availability[ecMax12.region.mask]>0.5 ) == ecMin13.region.mask[ecMax12.region.mask]).all(): raise RuntimeError("excludeRasterType: minimum and maximum summation - FAIL") ### Test with a different projection system # exclude single value ec = gl.ExclusionCalculator(aachenShape, srs='latlon', pixelRes=0.005) ec.excludeRasterType(clcRaster, 12) compareF(np.nanmean(ec.availability), 82.95262909, "excludeRasterType: Other SRS") compareF(np.nanstd(ec.availability), 32.26681137, "excludeRasterType: Other SRS") print( "ExclusionCalculator_excludeRasterType passed") def test_ExclusionCalculator_excludeVectorType(): # exclude all features directly ec = gl.ExclusionCalculator(aachenShape) ec.excludeVectorType(cddaVector) compareF(np.nanmean(ec.availability), 76.47581482, "excludeVectorType: Single value exclusion, new srs") compareF(np.nanstd(ec.availability), 42.41498947, "excludeVectorType: Single value exclusion, new srs") # exclude all features directly, new srs ec = gl.ExclusionCalculator(aachenShape, srs='latlon', pixelRes=0.005) ec.excludeVectorType(cddaVector) compareF(np.nanmean(ec.availability), 76.31578827, "excludeVectorType: Single value exclusion, new srs ") compareF(np.nanstd(ec.availability), 42.51445770, "excludeVectorType: Single value exclusion, new srs ") # exclude a selection of features ec = gl.ExclusionCalculator(aachenShape) ec.excludeVectorType(cddaVector, where="YEAR>2000") compareF(np.nanmean(ec.availability), 86.89811707, "excludeVectorType: Single value exclusion, new srs") compareF(np.nanstd(ec.availability), 33.74209595, "excludeVectorType: Single value exclusion, new srs") # exclude a selection of features with buffer ec = gl.ExclusionCalculator(aachenShape) ec.excludeVectorType(cddaVector, where="YEAR>2000", buffer=400) compareF(np.nanmean(ec.availability), 77.95021057, "excludeVectorType: Single value exclusion, new srs") compareF(np.nanstd(ec.availability), 41.45823669, "excludeVectorType: Single value exclusion, new srs") print( "ExclusionCalculator_excludeVectorType passed") def test_ExclusionCalculator_excludePrior(): # make a prior source pr = gl.core.priors.PriorSource(priorSample) # test same srs ec = gl.ExclusionCalculator(aachenShape) ec.excludePrior(pr, value=(400,None)) compareF(np.nanmean(ec.availability), 24.77587891, "excludePrior: Same srs") compareF(np.nanstd(ec.availability), 43.17109680, "excludePrior: Same srs") # test different srs and resolution ec = gl.ExclusionCalculator(aachenShape, srs='latlon', pixelRes=0.001) ec.excludePrior(pr, value=(400,None)) compareF(np.nanmean(ec.availability), 24.83173180, "excludePrior: Different srs") compareF(np.nanstd(ec.availability), 41.84893036, "excludePrior: Different srs") print( "ExclusionCalculator_excludePrior passed") def test_ExclusionCalculator_excludeRegionEdge(): # make a prior source pr = gl.core.priors.PriorSource(priorSample) ec = gl.ExclusionCalculator(aachenShape) ec.excludePrior(pr, value=(None,400)) ec.excludeRegionEdge(500) compareF(np.nanmean(ec.availability), 63.68544388, "excludeRegionEdge") compareF(np.nanstd(ec.availability), 48.09062958, "excludeRegionEdge") print( "ExclusionCalculator_excludeRegionEdge passed") def test_ExclusionCalculator_shrinkAvailability(): # make a prior source pr = gl.core.priors.PriorSource(priorSample) ec = gl.ExclusionCalculator(aachenShape) ec.excludePrior(pr, value=(None,400)) ec.shrinkAvailability(500) compareF(np.nanmean(ec.availability), 41.88655853, "shrinkAvailability") compareF(np.nanstd(ec.availability), 49.33732986, "shrinkAvailability") print( "ExclusionCalculator_shrinkAvailability passed") def test_ExclusionCalculator_pruneIsolatedAreas(): # make a prior source pr = gl.core.priors.PriorSource(priorSample) ec = gl.ExclusionCalculator(aachenShape) ec.excludePrior(pr, value=(None,400)) ec.pruneIsolatedAreas(12000000) compareF(np.nanmean(ec.availability), 65.41215515, "pruneIsolatedAreas") compareF(np.nanstd(ec.availability), 47.56538391, "pruneIsolatedAreas") print( "ExclusionCalculator_pruneIsolatedAreas passed") if __name__ == "__main__": test_ExclusionCalculator___init__() test_ExclusionCalculator_save() test_ExclusionCalculator_draw() test_ExclusionCalculator_excludeRasterType() test_ExclusionCalculator_excludeVectorType() test_ExclusionCalculator_excludePrior() test_ExclusionCalculator_excludeRegionEdge() test_ExclusionCalculator_shrinkAvailability() test_ExclusionCalculator_pruneIsolatedAreas() <file_sep>from setuptools import setup, find_packages setup( name='glaes', version='1.1.2', author='<NAME>', url='https://github.com/FZJ-IEK3-VSA/glaes', packages = find_packages(), include_package_data=True, install_requires = [ "geokit>=1.1.1", "gdal>=2.0.0", "numpy>=1.13.2", "descartes>=1.1.0", "pandas>=0.22.0", "scipy>=1.0.0", "matplotlib>=2.1.1", ] ) <file_sep>import glaes as gl import geokit as gk import numpy as np import gdal from os.path import join import matplotlib.pyplot as plt import warnings aachenShape = join("data","aachenShapefile.shp") clcRaster = join("data", "clc-aachen_clipped.tif") priorSample = join("data", "roads_prior_clip.tif") cddaVector = join("data","CDDA_aachenClipped.shp") def compareF(v, expected, msg="None"): if not np.isclose(v, expected): raise RuntimeError("Expected:%.8f, Got:%.8f ,MSG:%s"%(expected, v, msg)) def compare(v, expected, msg="None"): if not expected==v: raise RuntimeError("Expected:%s, Got:%s ,MSG:%s"%(str(expected), str(v), msg))<file_sep>from helpers import * from glaes.core.priors import * def test_Prior___init__(): # Test success p = PriorSource("data/roads_prior_clip.tif") if not p.path == "data/roads_prior_clip.tif": raise RuntimeError("Path mismatch") if not len(p.edgeStr) == 37 and p.edgeStr[14] =="<=1600.00": raise RuntimeError("edge extraction") if not len(p.edges) == 37 and p.edges[14]==1600.00: raise RuntimeError("edge conversion") if not len(p.values) == 37 and p.values[14] ==1500.00: raise RuntimeError("value estimation") if not np.isclose(p.untouchedTight, 40000.001): raise RuntimeError("untouchedTight") if not np.isclose(p.untouchedWide, 100000000040000.0): raise RuntimeError("untouchedWide") if not np.isclose(p.noData, -999999): raise RuntimeError("noDataValue") # Test fail try: p = PriorSource("data/elevation.tif") raise RuntimeError("Prior fail") except PriorSource._LoadFail as e: pass print("Prior___init__ passed") def test_Prior_containsValue(): print("Prior_containsValue is trivial") def test_Prior_valueOnEdge(): print("Prior_valueOnEdge is trivial") def test_Prior_generateRaster(): p = PriorSource(gl._test_data_["roads_prior_clip.tif"]) ext = gk.Extent.load(gk._test_data_["aachenShapefile.shp"]) r = p.generateRaster( extent=ext, output="results/generatedRaster1.tif" ) mat = gk.raster.extractMatrix(r) compareF(269719875, mat.sum()) compareF(1287.87195567, mat.std()) ri = gk.raster.rasterInfo(r) compareF(ri.dx, 100) compareF(ri.dy, 100) compare(ri.bounds, (4035500.0, 3048700.0, 4069500.0, 3101000.0)) compare(ri.dtype, gdal.GDT_Float64) print("Prior_generateRaster passed") def test_Prior_generateVector(): #generateVector(s, extent, value, output=None) p = PriorSource(gl._test_data_["roads_prior_clip.tif"]) ext = gk.Extent.load(gk._test_data_["aachenShapefile.shp"]) # Test an on-edge generation v = p.generateVector(ext, value=4000, output="results/generatedVector1.shp") g = gk.vector.extractFeature(v, onlyGeom=True) compareF(g.Area(), 1684940000.0) # Test an off-edge generation v = p.generateVector(ext, value=5500, output="results/generatedVector2.shp") g = gk.vector.extractFeature(v, onlyGeom=True) compareF(g.Area(), 1851537325.6536) print("Prior_generateVectorFromEdge passed") def test_Prior_extractValues(): print("Prior_extractValues is trivial") def test_PriorSet___init__(): with warnings.catch_warnings(): warnings.simplefilter("ignore") ps = PriorSet("data") keys = list(ps._sources.keys()) compareF(len(keys), 2, "Prior count") compareF("roads_main_proximity" in keys, True, "Prior inclusion") compareF("settlement_proximity" in keys, True, "Prior inclusion") print("PriorSet___init__ passed") def test_PriorSet_loadDirectory(): print("PriorSet__loadDirectory is implicity tested") def test_PriorSet_regionIsOkay(): print("PriorSet_regionIsOkay not tested") def test_PriorSet_sources(): print("PriorSet_sources not tested") def test_PriorSet_listKeys(): print("PriorSet_listKeys not tested") def test_PriorSet___getitem__(): print("PriorSet___getitem__ not tested") def test_PriorSet_combinePriors(): print("PriorSet_combinePriors not tested") def test_setPriorDirectory(): print("setPriorDirectory not tested") if __name__ == "__main__": test_Prior___init__() test_Prior_containsValue() test_Prior_valueOnEdge() test_Prior_generateRaster() test_Prior_generateVector() test_Prior_extractValues() test_PriorSet___init__() test_PriorSet_loadDirectory() test_PriorSet_regionIsOkay() test_PriorSet_combinePriors()
6069f4cfee120d4af70aea1f814cdfab18ecbe20
[ "Python" ]
5
Python
PyPSA/glaes
cebac2f999992633dd67dd05334be9e8f7e61295
f113347557b64d87b53090009c70ded65086b34e
refs/heads/master
<repo_name>Colt3Avery/Lessen1_1C<file_sep>/Assets/Scripts/FollowPlayer.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class FollowPlayer : MonoBehaviour { public GameObject player; private Vector3 Offset = new Vector3(0, 7, -10); // the private is to set up where the camera is offset from the gameobject(the vehicle) void Start() { } void Update() { // the transform is the object that it's attached to (the camera) ((called scoping)) transform.position = player.transform.position + Offset; } }
ae5c4c50f25f49c4efdf9583e5ebeb739214e701
[ "C#" ]
1
C#
Colt3Avery/Lessen1_1C
e97c8cc24de9dfb8ebdd11d84d6cabbac8bb2074
9269a923c80c9d70f8b7a17c20d0cf679f877c6f
refs/heads/master
<file_sep>#!/bin/bash set -e if [ -n "${DISABLE_SOURCE_COMPRESSION}" ]; then exit 0 fi if [ ! -d "${GOPATH}/src/github.com/mholt/caddy" ]; then mkdir -p "${GOPATH}" tar xJ -C "${GOPATH}" -f "/usr/src/go.tar.xz" rm "/usr/src/go.tar.xz" fi <file_sep># Caddy Docker image This image simply provides Caddy precompiled and -installed, ready to use out of the box. Additionally, it allows for simple extension with plugins. ## Available tags All available tags are always listed [in Docker Hub](https://hub.docker.com/r/icedream/caddy/tags), the list below explains the maintained tags: - `latest`: Latest version of this image (intended to target `master` branch of Caddy). - `stable`, `0`, `0.10`, `0.11.0`: Latest stable version (last release of Caddy). ### Older tags - `0.10`, `0.10.14` - `0.9`, `0.9.5` ## About Caddy Caddy is a modern implementation of a web server with a focus on security and automation with ease of configuration. You can find out more about Caddy on the official website at https://caddyserver.com/. ## Features - Based on Alpine Linux - Transparent usage (the Caddy binary itself is the entrypoint of this image) - Easy installation of plugins through scripts shipped with the image ## Usage This image does not tweak Caddy itself in any way so it will technically run exactly as if you were running Caddy directly on the machine aside from the usual Docker isolation. Caddy needs at least a folder containing a website in order to run in a way that makes sense. You can mount such a website in as a volume like this: ```sh docker run -d -p "2015:2015" -w /data -v /path/to/your/website:/data icedream/caddy ``` Your website should then be available at http://localhost:2015 according to the [official Getting Started guide](https://caddyserver.com/docs/getting-started). Configuration can then be done as usual via your own `Caddyfile` in the working directory. ## Extension ### Custom image At some point you may want to put your website code into a custom Docker image to go along with Caddy itself. You can realize this idea using a new `Dockerfile` which contains at least the following lines: ```dockerfile FROM icedream/caddy WORKDIR /data COPY . /data/ ``` ### Installing plugins Additionally to just copying your website into the Docker image you can install a custom set of plugins and let the Docker image automatically rebuild Caddy with all these plugins for you: ```dockerfile RUN docker-caddy-install-plugin \ "https://github.com/captncraig/cors.git" \ "https://github.com/pyed/ipfilter.git#6b25e48ff3eef8d894f6fca240463f726ee7f7eb" &&\ rm -r "${GOPATH}" ``` Supported syntaxes for sources where to install plugins from are: - `protocol://server.com/user/repository.git` (will use latest commit on default branch) - `protocol://server.com/user/repository.git#reference` (reference can be any branch name, tag, commit hash, etc. to select a specific version of a plugin) Supported protocols are the same that Git supports (`git`, `https` and `http`). The last line makes sure to delete the Go workspace folder as an attempt on saving space in the final image output. <file_sep>#!/bin/bash set -e if [ -n "${DISABLE_SOURCE_COMPRESSION}" ]; then exit 0 fi if [ ! -d "${GOPATH}/src/github.com/mholt/caddy" ]; then echo "Tried to pack source when the source directory has been deleted." >&2 exit 1 fi ( cd "${GOPATH}" mkdir -p "/usr/src" tar cJ -f "/usr/src/go.tar.xz" . ) exec rm -r "${GOPATH}" <file_sep>#!/bin/bash set -e export PATH="$GOPATH/bin:$PATH" docker-caddy-unpack-source cd "$GOPATH/src/github.com/mholt/caddy/caddy" # Make sure all dependencies are available go get -d -v . docker-caddy-remove-git-metadata go run ./build.go "/usr/local/bin/caddy" mv caddy /usr/local/bin # Remove some reproducible and for runtime unnecessary build output files # to save on the image size later on rm -rfv \ "/tmp"/* \ "/var/tmp"/* \ "exec" \ "lib" \ "pkg" <file_sep>#!/bin/bash set -e if [ -n "${DISABLE_GIT_METADATA_REMOVAL}" ]; then exit 0 fi # Remove Git metadata exec find "${GOPATH}" \ -name .git -type d \ ! -path '*/src/github.com/mholt/caddy/*' \ -exec rm -r {} + <file_sep>#!/bin/bash set -e pluginspath="$GOPATH/src/github.com/mholt/caddy/caddy/caddymain/install_plugins.go" plugin() { echo "*** Fetching plugin $1..." # Generate Go import path from given Git URL importpath="${3:-$(echo "$1" | sed -e 's,^.\+://,,' -e 's,\.git$,,')}" git clone "$1" "$GOPATH/src/$importpath" ( cd "$GOPATH/src/$importpath" # Checkout wanted version if any given if [ ! -z "$2" ] then git checkout "$2" fi echo "*** Preparing plugin $1..." # Fetch dependencies go get -d -v . # Run generate across all files (if any extra tools are necessary you will # need to install them before running this script) go generate -v . ) docker-caddy-remove-git-metadata # Add the newly available plugin to an extra Go source file that will be # compiled into the Caddy binary along with the rest of the source tree. if [ ! -e "$pluginspath" ] then echo "package caddymain" > "$pluginspath" fi echo "*** Adding ${importpath} to $pluginspath..." echo "import _ \"${importpath}\"" >> "$pluginspath" } docker-caddy-unpack-source # Parse arguments and prepare each given plugin. # Supported syntaxes (where reference can be a commit hash or branch name etc.): # - http://server.com/user/repository.git # - https://server.com/user/repository.git # - git://server.com/user/repository.git # - http://server.com/user/repository.git#reference # - https://server.com/user/repository.git#reference # - git://server.com/user/repository.git#reference for plugin in "$@"; do (IFS='#'; plugin $plugin); done # Rebuild Caddy with the given plugins now installed exec docker-caddy-build
96e0d54aaf60d29daf84748c4eb7cca271498736
[ "Markdown", "Shell" ]
6
Shell
icedream/docker-caddy
48772cc1215047e8f4ec450141563550acaa2fe2
e8ee16f1f66356b037564fdf5ea14cc445404433
refs/heads/master
<file_sep>/* <NAME> V1.0 13th November */ //Program for Testing purposes //Allows you to insert, delete tree, search for a specific integer in the tree //Print in any orde you like #include "tree.h" #include <iostream> #include <cstdlib> #include <vector> #include <stdio.h> using namespace std; // int main() { BinaryTree tree; //choice variables char choice; int myint; void * void_value; string string_choice; //To measure length of input for(int i = 0; i > -1; i) { cout << "\npress i to insert an element into the hash table" << endl; cout << "press d to search for integer" << endl; cout << "press l to in order Print" << endl; cout << "press s to post order Print" << endl; cout << "press p to pre order print" << endl; cout << "press c to create a new tree and delete old one" << endl; cout << "press q to quit" << endl; cin >> string_choice; cout << "\n"; if(string_choice.size() > 1) choice='w'; else choice=string_choice.at(0); switch(choice) { case 'i': cout << "Please insert a value\nValue: "; cin >> myint; void_value = new int; *static_cast<int*>(void_value) = myint; tree.insert(void_value); break; case 'd': cout << "Please insert a value\nValue: "; cin >> myint; void_value = new int; *static_cast<int*>(void_value) = myint; if(tree.search(void_value) == NULL) cout << "\nIt's not in the tree\n"; else cout << "\nIt's in the tree\n"; break; case 'c': tree.delete_tree(); break; case 'l': tree.inorderPrint(); break; case 'p': tree.preorderPrint(); break; case 'q' : cout << "\nExiting Progam Now\n\n"; tree.delete_tree(); exit(1); break; case 's': tree.postorderPrint(); break; default: cout <<"\nNot one of the OPTIONS\n\n"; break; } } return 1; } <file_sep>/* <NAME> V1.0 13th November */ #include <iostream> using namespace std; //Template for class taken from cprogramming.com - article by <NAME> //Stucture with pointers to the memory where data is stored, the left leaf and right leaf struct node { void * m_value; //Stores a void pointer long int occurance_counter; node * left; node * right; }; //BinaryTree /* Insert and Search functions take a void pointer that points to an integer. Editing details to work with specific type in tree.cpp */ class BinaryTree { public: BinaryTree(); ~BinaryTree(); void insert(void * value); void delete_tree(); /* void preorderPrint(); void postorderPrint(); void inorderPrint(); node * search(void * value); */ void alphabetical_occurance_print(); void find_most_occuring(); private: /* void inorderPrint(node *root ); void preorderPrint(node *root); void postorderPrint(node *root); node * search(void * value, node *leaf); */ void delete_tree(node *leaf); void insert(void * value, node *leaf); void alphabetical_occurance_print(node *root, ofstream * filewriter); void find_most_occuring(node *root); node *root; node *most_occuring; }; <file_sep>/* <NAME> V1.0 13th November */ #include "tree.h" #include <iostream> #include <typeinfo> using namespace std; //Constructor //Sets deafault root to NULL BinaryTree::BinaryTree() { root = NULL; } //destructor calls delete_tree BinaryTree::~BinaryTree() { delete_tree(); } //Calls recursive function delete_tree(node *leaf) and sets Root to NULL which is essentially creating a brand new fresh tree void BinaryTree::delete_tree() { delete_tree(root); root= NULL; } //Recursively goes through the whole tree to delete everything that anything is pointed to void BinaryTree::delete_tree(node *leaf) { if(leaf!=NULL) { delete_tree(leaf->left); delete_tree(leaf->right); delete leaf; } return; } //Inserts to root if root is not set, else calls recursive version of itself while passing it root (which has a variable) void BinaryTree::insert(void * value) { if(root != NULL) insert(value, root); else { root = new node; root->m_value = value; root->left = NULL; root->right = NULL; } } //Recursively finds spot to place value //Uses static casting to compare the integers that the void pointer is pointing to //Can be edited for any type by changing the comparisons plus casting to be appropriate for the type void BinaryTree::insert(void * value, node * leaf) { if(*static_cast<int*>(value) < *static_cast<int*>(leaf->m_value)) { if(leaf->left != NULL) insert(value, leaf->left); //If node is taken, call itself while going left else { leaf->left=new node; //If node is NULL, create a node there leaf->left->m_value = value; //Give new node the pointer to leaf->left->left = NULL; //NULL the left leaf leaf->left->right = NULL; //NULL THE RIGHT leaf } } else if(*static_cast<int*>(value) >= *static_cast<int*>(leaf->m_value)) { if(leaf->right != NULL) insert(value, leaf->right); else { leaf->right=new node; //Ditto from above leaf->right->m_value = value; leaf->right->left = NULL; leaf->right->right = NULL; } } } node * BinaryTree::search(void * value) { return search(value, root); //Return result of the recursive version } //Can be edited for any type by changing the comparisons plus casting to be appropriate for the type node * BinaryTree::search(void * value, node * leaf) { if(leaf != NULL) //If not found yet { if(*static_cast<int*>(value) == *static_cast<int*>(leaf->m_value)) //Dereferences void pointer { return leaf; //If FOUND return the correct leaf pointer } if(*static_cast<int*>(value) < *static_cast<int*>(leaf->m_value)) //if smaller than after dereferancing { return search(value, leaf->left); //Recursively call to go deeper into the left tree } else { return search(value, leaf->right); //Recursively call to go deeper into the right of the tree } } else return NULL; } //Calls the post order printing process //Exists for the purpose that root is private and shouldn't be editable outside of tree functions void BinaryTree::postorderPrint() { postorderPrint(root); } //Prints from left to right of tree //Edit the cast for any type you like void BinaryTree::postorderPrint( node *root ) { if ( root != NULL ) { postorderPrint( root->left ); postorderPrint( root->right ); cout << *static_cast<int*>(root->m_value) << " "; } } //Calls the pre order printing process //Exists for the purpose that root is private and shouldn't be editable outside of tree functions void BinaryTree::preorderPrint() { preorderPrint(root); } //Prints from root to left to right of tree //Edit the cast for any type you like void BinaryTree::preorderPrint( node *root ) { if ( root != NULL ) { cout << *static_cast<int*>(root->m_value) << " "; preorderPrint( root->left ); preorderPrint( root->right ); } } //Calls the post order printing process //Exists for the purpose that root is private and shouldn't be editable outside of tree functions void BinaryTree::inorderPrint() { inorderPrint(root); } //Prints inorder fashion //Edit the cast for any type you like void BinaryTree::inorderPrint(node *root ) { if ( root != NULL ) { inorderPrint( root->left ); cout << *static_cast<int*>(root->m_value) << " "; inorderPrint( root->right ); } } <file_sep>#include <iostream> #include <string> #include <fstream> #include <sstream> #include <vector> #include <stdio.h> #include <cstdlib> using namespace std; int main() { string temp = "you--jem's"; stringstream ss; string string_store = "you--jem's"; for(int i = 0; i < string_store.size(); i++) { if(string_store.at(i) <= 'z' && string_store.at(i) >= 'a') { ss << string_store.at(i); } else { ss << " "; string_store.erase(i, 1); i--; } } while(ss >> string_store) { cout << string_store; } return 1; } <file_sep>/* <NAME> V1.0 13th November */ #include "tree.h" #include <iostream> #include <typeinfo> #include <stdio.h> #include <string.h> #include <cstring> #include <fstream> using namespace std; //Constructor //Sets deafault root to NULL //Sets default most_occuring to -1 after giving it a memory location BinaryTree::BinaryTree() { root = NULL; most_occuring = new node; most_occuring->occurance_counter = -1; } //destructor calls delete_tree BinaryTree::~BinaryTree() { delete_tree(); } //Calls recursive function delete_tree(node *leaf) and sets Root to NULL which is essentially creating a brand new fresh tree void BinaryTree::delete_tree() { delete_tree(root); root= NULL; } //Recursively goes through the whole tree to delete everything that anything is pointed to void BinaryTree::delete_tree(node *leaf) { if(leaf!=NULL) { delete_tree(leaf->left); delete_tree(leaf->right); delete leaf; } return; } //Inserts to root if root is not set, else calls recursive version of itself while passing it root (which has a variable) void BinaryTree::insert(void * value) { if(root != NULL) insert(value, root); else { root = new node; root->m_value = value; root->left = NULL; root->right = NULL; root->occurance_counter = 1; } } //Recursively finds spot to place value //Accepts void pointer but convers to char pointer in order to compare to other m_value void BinaryTree::insert(void * value, node * leaf) { //Using strcmp as alternative to string.compare(string string) in order to get result < 0 means it's smaller == 0 means it's the same string if(strcmp(static_cast<char*>(value), static_cast<char*>(leaf->m_value)) < 0) { if(leaf->left != NULL) insert(value, leaf->left); //If node is taken, call itself while going left else { leaf->left=new node; //If node is NULL, create a node there leaf->left->m_value = value; //Give new node the pointer to leaf->left->left = NULL; //NULL the left leaf leaf->left->right = NULL; //NULL THE RIGHT leaf leaf->left->occurance_counter = 1; } } else if(strcmp(static_cast<char*>(value), static_cast<char*>(leaf->m_value)) > 0) { //cout << "in more than\n"; if(leaf->right != NULL) insert(value, leaf->right); else { leaf->right=new node; //Ditto from above leaf->right->m_value = value; leaf->right->left = NULL; leaf->right->right = NULL; leaf->right->occurance_counter = 1; } } else //If strings are equal, add one to the occurance counter leaf->occurance_counter++; } //Prints the tree out alphabetically in accordance to the output.txt that we were given //Into a file cleverly named output.txt void BinaryTree::alphabetical_occurance_print() { string filename = "output.txt"; char * cstr = new char [filename.length()+1]; std::strcpy (cstr, filename.c_str()); //Convert filename to appropriate format for fstreams try { ofstream filewriter(cstr, std::ofstream::out); alphabetical_occurance_print(root, &filewriter); find_most_occuring(); filewriter << "(" << (char*)most_occuring->m_value << "," << most_occuring->occurance_counter << ") \n"; filewriter.close(); } catch(...) { } cout << "\noutput.txt created!\n\n"; } //Goes through the tree inorder and posts in accordance to the output.txt //converts the void pointer m_value to char pointer because we know that it is a //set of characters with a \0 terminating them. void BinaryTree::alphabetical_occurance_print(node *root, ofstream * filewriter) { if ( root != NULL ) { alphabetical_occurance_print( root->left , filewriter ); *filewriter << "(" << (char*)root->m_value << "," << root->occurance_counter << ") \n"; alphabetical_occurance_print( root->right , filewriter ); } } //goes through the ready tree comparing the occurance counters in order to print out the most occuring. void BinaryTree::find_most_occuring() { find_most_occuring(root); } void BinaryTree::find_most_occuring(node *root) { if(root != NULL) { find_most_occuring( root->left ); find_most_occuring( root->right ); if(most_occuring->occurance_counter < root->occurance_counter) most_occuring = root; } } <file_sep>/* <NAME> V1.0 13th November */ //Program for Testing purposes //Allows you to insert, delete tree, search for a specific integer in the tree //Print in any orde you like #include "tree.h" #include <iostream> #include <cstdlib> #include <vector> #include <stdio.h> #include <fstream> #include <sstream> #include <algorithm> #include <cstring> using namespace std; // int main() { BinaryTree tree; //Used for reading with ss out of file string string_store; //Used for passing to the insert function char * void_value; //Used to read from the filereader stringstream ss; //Used to get the name of the txt file string book_name; //Used to temporalily store the separated ready strings of the string_store vector<string>edited_string(5, ""); try { ifstream filereader; cout << "Please give me name of the book file\nFilename: "; cin >> book_name; char * cstr = new char [book_name.length()+1]; //ifstream won't open properly unless I convert it a pointer to char array std::strcpy (cstr, book_name.c_str()); filereader.open(cstr, ifstream::in); if(!filereader.is_open()) //If doesn't open cout <<"FAIL"; while(filereader >> string_store) //Continue until reaching endoffile { transform(string_store.begin(), string_store.end(), string_store.begin(), ::tolower); //Transform current string to lowercase for(int i = 0; i < string_store.size(); i++) //Continue while not at the end of string_store { if(string_store.at(i) <= 'z' && string_store.at(i) >= 'a') // if at(i) is a letter of alphabet, begin storing new word ss << string_store.at(i); else ss << " "; //Separating the stored strings with spaces instead of special characters } for(int i = 0; ss >> edited_string[i]; i++) //As long as there are thigns to take out. { void_value = new char [edited_string[i].size()+1]; //Allocate memory for the new string copy(edited_string[i].begin(), edited_string[i].end(), void_value); //Copy into the allocated memory void_value[edited_string[i].size()] = '\0'; //insert \0 at end of string tree.insert(void_value); //finally insert the pointer } ss.clear(); //Clear all flags of SS. } } catch(string e) //If error occurs, catch it. { cout << e << "\nBoo\n"; } tree.alphabetical_occurance_print(); //Prints out the correct output compared to output.txt tree.find_most_occuring(); //Prints out most occuring word tree.delete_tree(); //Deletes tree and frees memory to avoid leaks. return 1; //Returns 1 as SUCCESS. }
72001142c66493f5a639c3aa42d51b345371b319
[ "C++" ]
6
C++
azpopov/BinaryTreeCpp
6253b902ab2831a6ada388f74226ef7f84b20fae
7ecc0cc419848498dcb0bd10d3cf6a06693a1c7e
refs/heads/master
<repo_name>rafaelmellooo/bestwayexchange-backend<file_sep>/src/database/seeders/20190930040643-demo-housing_types.js 'use strict' module.exports = { up: queryInterface => { const housingTypes = [ { name: 'Host Family', description: 'Optando pela Host Family (ou homestay, como é conhecido no exterior) o intercambista se hospedará na casa de uma família nativa. Essas famílias são escritas em um programa do governo local e são rigorosamente avaliadas e selecionadas, para atender aos padrões exigidos, requerimentos e as regras da escola. Normalmente para que o intercambista faça sua escolha, são enviadas todas as informações sobre a família.' }, { name: 'Residência Estudantil', description: 'Residência Estudantil\',\'As residências estudantis estão localizadas dentro das próprias escolas ou em prédios próximos ao local de estudo. O intercambista pode escolher entre quarto compartilhado ou individual, e as áreas comuns como banheiro, sala e cozinha são coletivas. Normalmente nesse tipo de acomodação são oferecidas algumas facilidades tais como bar, academia, lavanderia, televisão, dentre outros.' }, { name: 'Apartamento', description: 'Apartamento\',\'Essa opção é um meio termo entre dormitórios universitários e Host Family. O estudante escolhe por alugar um apartamento sozinho ou dividir o aluguel e todas as outras contas com outros estudantes. Isso dependerá do que o intercambista deseja e o que ele pode pagar. Em caso de compartilhar o apartamento, normalmente é pago o valor por um quarto, que pode ser individual ou compartilhado, e geralmente áreas como banheiro, cozinha e sala são compartilhadas. Para encontrar esses apartamentos, o intercambista pode pesquisar em imobiliárias da região ou em grupos nas redes sociais, os grupos geralmente oferecem muitas opções para compartilhar.' }, { name: 'Hotel', description: 'Geralmente é fácil encontrar hotéis próximos as escolas, porém esse tipo de acomodação são considerados mais caras e o intercambista vai viver uma vida de turista, totalmente fora do ambiente estudantil. É pago por diária e tem acesso as facilidades que o hotel oferece.' }, { name: 'Hostel', description: 'O termo Hostel é muito famoso principalmente entre os mochileiros, que viajam de país á país. Essa é uma opção parecida com hotel, mas aqui tudo é compartilhado, banheiro, cozinha e quartos (salvo exceções, com opção de quarto individual). Se hospedar em hostel pode ser uma boa escolha para quem faz curso de curta duração, ou está a procurar de outra acomodação definitiva.' } ] const data = [] let id = 0 housingTypes.map(({ name, description }) => { id++ data.push({ id, name, description }) }) return queryInterface.bulkInsert('housing_types', data, {}) }, down: queryInterface => { return queryInterface.bulkDelete('housing_types', null, {}) } } <file_sep>/src/app/controllers/AgencyController.js const Agency = require('../models/Agency') const User = require('../models/User') const AgencyGrade = require('../models/AgencyGrade') const sequelize = require('sequelize') module.exports = { async show (req, res) { const agency = await Agency.findByPk(req.params.id, { attributes: ['name', 'description', 'filename', 'background'], include: [ { association: 'exchanges', attributes: ['id', 'name', 'filename', 'createdAt', 'time', 'price'], include: [ { association: 'exchangeType', attributes: ['name'] }, { association: 'city', attributes: ['name'], include: [ { association: 'country', attributes: ['name'] } ] } ] } ] }) const rate = await AgencyGrade.findAll({ where: { agencyId: req.params.id }, attributes: [[sequelize.fn('AVG', sequelize.col('gradeId')), 'avg']] }) res.status(200).json({ agency, rate }) }, async store (req, res) { const filename = req.file ? req.file.filename : undefined const { name, description, background } = req.body try { const agency = await Agency.create({ name, description, background, filename }) await User.update({ agencyId: agency.id }, { where: { id: req.user.id } }) res.status(200).json() } catch (err) { res.status(400).json(err) } }, async update (req, res) { const { name, description } = req.body try { await Agency.update({ name, description }, { where: { id: req.params.id } }) res.status(200).json() } catch (err) { res.status(400).json(err) } }, async destroy (req, res) { await Agency.destroy({ where: { id: req.params.id } }) res.status(200).json() } } <file_sep>/src/app/models/Agency.js const { Model, DataTypes } = require('sequelize') class Agency extends Model { static init (sequelize) { super.init({ name: { type: DataTypes.STRING, validate: { notEmpty: { msg: 'O nome não deve ser nulo' } } }, description: { type: DataTypes.TEXT('long'), validate: { notEmpty: { msg: 'A descrição não deve ser nula' } } }, filename: DataTypes.STRING, background: DataTypes.STRING }, { sequelize, tableName: 'agencies', timestamps: false }) } static associate (models) { this.hasMany(models.User, { foreignKey: 'agencyId', as: 'users' }) this.belongsToMany(models.User, { through: models.AgencyGrade, foreignKey: 'agencyId', as: 'grades' }) this.hasMany(models.Address, { foreignKey: 'agencyId', as: 'addresses' }) this.hasMany(models.Exchange, { as: 'exchanges', foreignKey: 'agencyId' }) } } module.exports = Agency <file_sep>/src/app/models/AgencyGrade.js const { Model } = require('sequelize') class AgencyGrade extends Model { static init (sequelize) { super.init({ }, { sequelize, tableName: 'agency_grades', updatedAt: false }) } static associate (models) { this.belongsTo(models.Agency, { foreignKey: 'agencyId', as: 'agency' }) this.belongsTo(models.User, { foreignKey: 'userId', as: 'user' }) this.belongsTo(models.Grade, { foreignKey: 'gradeId', as: 'grade' }) } } module.exports = AgencyGrade <file_sep>/src/database/seeders/20191014024830-demo-exchange_languages.js 'use strict' module.exports = { up: queryInterface => { const data = [] const exchangeLanguages = [] for (let i = 0; i < 735; i++) { let exchangeId = Math.floor((Math.random() * 100) + 1) let languageId = Math.floor((Math.random() * 10) + 1) while ( exchangeLanguages.some(([_exchangeId, _languageId]) => _exchangeId === exchangeId && _languageId === languageId) ) { exchangeId = Math.floor((Math.random() * 100) + 1) languageId = Math.floor((Math.random() * 10) + 1) } exchangeLanguages.push([ exchangeId, languageId ]) data.push({ exchangeId, languageId }) } return queryInterface.bulkInsert('exchange_languages', data, {}) }, down: queryInterface => { return queryInterface.bulkDelete('exchange_languages', null, {}) } } <file_sep>/src/app/controllers/EmployeeController.js const User = require('../models/User') module.exports = { async index (req, res) { const { agencyId } = req.params const employees = await User.findAll({ where: { agencyId, typeId: 2 }, attributes: ['name', 'email', 'filename', 'dateOfBirth'] }) res.status(200).json(employees) } } <file_sep>/src/app/models/Country.js const { Model, DataTypes } = require('sequelize') class Country extends Model { static init (sequelize) { super.init({ name: { type: DataTypes.STRING, validate: { notEmpty: { msg: 'O nome não deve ser nulo' } } }, description: DataTypes.TEXT, filename: DataTypes.STRING }, { sequelize, tableName: 'countries', timestamps: false }) } static associate (models) { this.hasMany(models.City, { as: 'cities', foreignKey: 'countryId' }) } } module.exports = Country <file_sep>/src/app/controllers/GradeController.js const Grade = require('../models/Grade') module.exports = { async index (req, res) { const grades = await Grade.findAll() res.status(200).json(grades) } } <file_sep>/src/routes/free.js const express = require('express') const multer = require('multer') const uploadConfig = require('../config/upload') const AgencyController = require('../app/controllers/AgencyController') const EmployeeController = require('../app/controllers/EmployeeController') const AgencyGradeController = require('../app/controllers/AgencyGradeController') const AuthController = require('../app/controllers/AuthController') const CityController = require('../app/controllers/CityController') const CountryController = require('../app/controllers/CountryController') const ExchangeController = require('../app/controllers/ExchangeController') const ExchangeTypeController = require('../app/controllers/ExchangeTypeController') const GradeController = require('../app/controllers/GradeController') const HousingTypeController = require('../app/controllers/HousingTypeController') const ItemController = require('../app/controllers/ItemController') const LanguageController = require('../app/controllers/LanguageController') const RateController = require('../app/controllers/RateController') const AddressController = require('../app/controllers/AddressController') const RankingController = require('../app/controllers/RankingController') const routes = express.Router() const upload = multer(uploadConfig) routes.post('/auth/register', upload.single('profile'), AuthController.register) routes.post('/auth/authenticate', AuthController.authenticate) routes.post('/auth/send_email', AuthController.sendEmail) routes.post('/auth/confirm_email', AuthController.confirmEmail) routes.get('/exchanges/:exchangeId/rates', RateController.index) routes.get('/languages', LanguageController.index) routes.get('/exchange_types', ExchangeTypeController.index) routes.get('/housing_types', HousingTypeController.index) routes.get('/countries', CountryController.index) routes.get('/countries/:countryId/cities', CityController.index) routes.get('/agencies/:agencyId/addresses', AddressController.index) routes.get('/agencies/:agencyId/rates', AgencyGradeController.index) routes.get('/grades', GradeController.index) routes.get('/items', ItemController.index) routes.get('/exchanges', ExchangeController.index) routes.get('/exchanges/:id', ExchangeController.show) routes.get('/agencies/:id', AgencyController.show) routes.get('/agencies/:agencyId/employees', EmployeeController.index) routes.get('/ranking', RankingController.show) module.exports = routes <file_sep>/src/database/seeders/20190930035935-demo-cities.js 'use strict' module.exports = { up: queryInterface => { const faker = require('faker') const data = [] for (let i = 0; i < 100; i++) { data.push({ id: i + 1, name: faker.address.city(), countryId: Math.floor((Math.random() * 10) + 1) }) } return queryInterface.bulkInsert('cities', data, {}) }, down: queryInterface => { return queryInterface.bulkDelete('cities', null, {}) } } <file_sep>/src/database/seeders/20190930043442-demo-chats.js 'use strict' module.exports = { up: queryInterface => { const { addSeconds, getMonth, setDate } = require('date-fns') const agencies = [] const tmp = { employee: 0, exchange: 0 } for (let i = 0; i < 10; i++) { const employees = [] const exchanges = [] for (let j = 0; j < 4; j++) { tmp.employee++ employees.push(tmp.employee) } for (let j = 0; j < 10; j++) { tmp.exchange++ exchanges.push(tmp.exchange) } agencies.push({ employees, exchanges }) } const data = [] let id = 0 const today = new Date() let createdAt = setDate(today, getMonth(today) - 1) for (let i = 0; i < 120; i++) { if (i % 5 !== 0) { continue } for (let j = 0; j < 10; j++) { if (j % 5 !== 0) { continue } const agency = agencies[j] const employees = { 0: agency.employees[1], 4: agency.employees[2], 8: agency.employees[3] } for (let k = 0; k < 10; k++) { if (k % 4 !== 0) { continue } const exchangeId = agency.exchanges[k] const employeeId = employees[k] createdAt = addSeconds(createdAt, 1) id++ data.push({ id, userId: i + 41, employeeId, createdAt, exchangeId }) } } } return queryInterface.bulkInsert('chats', data, {}) }, down: queryInterface => { return queryInterface.bulkDelete('chats', null, {}) } } <file_sep>/src/app/controllers/LogController.js const { Op } = require('sequelize') const { setMonth, getMonth } = require('date-fns') const Exchange = require('../models/Exchange') const Rate = require('../models/Rate') const Chat = require('../models/Chat') module.exports = { async show (req, res) { const agency = req.user.agency try { const exchanges = await Exchange.findAll({ order: [ ['createdAt', 'DESC'] ], where: { agencyId: agency }, attributes: ['id', 'name'] }) await Promise.all(exchanges.map(async exchange => { const today = new Date() const lastMonth = setMonth(today, getMonth(today) - 1) const purchasers = await Rate.count({ where: { exchangeId: exchange.id, createdAt: { [Op.gt]: lastMonth } } }) const stakeholders = await Chat.count({ where: { exchangeId: exchange.id, createdAt: { [Op.gt]: lastMonth } } }) exchange.dataValues.purchasers = purchasers exchange.dataValues.stakeholders = stakeholders })) res.status(200).json(exchanges) } catch (err) { console.log(err) } } } <file_sep>/src/database/seeders/20190930043844-demo-rates.js 'use strict' module.exports = { up: queryInterface => { const faker = require('faker') const data = [] const rates = [] for (let i = 0; i < 1714; i++) { let userId = Math.floor((Math.random() * 120) + 41) let exchangeId = Math.floor((Math.random() * 100) + 1) while ( rates.some(([_userId, _exchangeId]) => _userId === userId && _exchangeId === exchangeId) ) { userId = Math.floor((Math.random() * 120) + 41) exchangeId = Math.floor((Math.random() * 100) + 1) } rates.push([ userId, exchangeId ]) const isRated = faker.random.boolean(); data.push({ id: i + 1, userId, exchangeId, comment: isRated ? faker.lorem.paragraph() : null, isRated, createdAt: new Date(), updatedAt: new Date() }) } return queryInterface.bulkInsert('rates', data, {}) }, down: queryInterface => { return queryInterface.bulkDelete('rates', null, {}) } } <file_sep>/src/database/seeders/20190929162728-demo-users.js 'use strict' module.exports = { up: function (queryInterface) { const faker = require('faker') const filenames = [ '099012-1574649476777.png', '099013-1574649476778.png', '099014-1574649477074.png', '099015-1574649477075.png', '099016-1574649530252.png', '099017-1574649476387.png', '099018-1574649476388.png', '099019-1574649476389.png', '099020-1574649476776.png', '099021-1574649395861.png', '099022-1574649395862.png', '099023-1574649396127.png', '099024-1574649396128.png', '099025-1574649396129.png', '099026-1574649396452.png', '099027-1574649396453.png', '099028-1574649476386.png', '099029-1574649395425.png', '099030-1574649395426.png', '099031-1574649395860.png', '099036-1574649298478.png', '099037-1574649298479.png', '099038-1574649298480.png', '099039-1574649395424.png', '099040-1574649295152.png', '099041-1574649295153.png', '099042-1574649297466.png', '099043-1574649297467.png', '099044-1574649297468.png', '099045-1574649298117.png', '099046-1574649298118.png', '099047-1574649298119.png', '099048-1574649295150.png', '099049-1574649295151.png', null ] const data = [] let id = 0 const create = (typeId, agencyId = undefined) => { id++ data.push({ id, email: faker.internet.exampleEmail(), name: faker.name.findName(), password: <PASSWORD>', typeId, agencyId, token: '<PASSWORD>1495bcb4b8c760628648', expiresIn: '2019-10-05 00:49:52', isActive: true, dateOfBirth: '2001-07-15', filename: filenames[Math.floor(Math.random() * filenames.length)] }) } for (let i = 0; i < 10; i++) { create(3, i + 1) for (let j = 0; j < 3; j++) { create(2, i + 1) } } for (let i = 0; i < 120; i++) { create(1) } return queryInterface.bulkInsert('users', data, {}) }, down: queryInterface => { return queryInterface.bulkDelete('users', null, {}) } } <file_sep>/src/app/models/ExchangeHousingType.js const { Model } = require('sequelize') class ExchangeHousingType extends Model { static init (sequelize) { super.init({ }, { sequelize, tableName: 'exchange_housing_types', timestamps: false }) } } module.exports = ExchangeHousingType <file_sep>/src/app/models/Language.js const { Model, DataTypes } = require('sequelize') class Language extends Model { static init (sequelize) { super.init({ name: DataTypes.STRING }, { sequelize, tableName: 'languages', timestamps: false }) } static associate (models) { this.belongsToMany(models.Exchange, { through: models.ExchangeLanguage, as: 'exchanges', foreignKey: 'languageId' }) } } module.exports = Language <file_sep>/src/app/controllers/BackgroundController.js const Country = require('../models/Country') module.exports = { async index (req, res) { const countries = await Country.findAll({ attributes: ['id', 'name', 'filename'] }) res.status(200).json(countries) } } <file_sep>/src/app/controllers/MessageController.js const Message = require('../models/Message') const Chat = require('../models/Chat') const { Op } = require('sequelize') module.exports = { async index (req, res) { const { chatId } = req.params const userId = req.user.id const type = { 1: { userId }, 2: { employeeId: userId } } const chat = await Chat.findOne({ where: { id: chatId, ...type[req.user.type] } }) if (!chat) { return res.status(401).json() } await Message.update({ isVisualized: true }, { where: { chatId, from: { [Op.ne]: userId }, isVisualized: false } }) const { page = 1 } = req.query const messages = await Message.paginate({ order: [ ['createdAt', 'DESC'] ], attributes: ['body', 'filename', 'from', 'createdAt'], page, paginate: 10, where: { chatId } }) res.status(200).json(messages) }, async store (req, res) { const { chatId } = req.params const userId = req.user.id const type = { 1: { where: { userId }, attributes: 'employeeId' }, 2: { where: { employeeId: userId }, attributes: 'userId' } } const chat = await Chat.findOne({ attributes: ['id', [type[req.user.type].attributes, 'user']], where: { id: chatId, ...type[req.user.type].where } }) if (!chat) { return res.status(401).json() } const filename = req.file ? req.file.filename : undefined const { body } = req.body const message = await Message.create({ body, filename, chatId, from: userId }) const receiver = req.connectedUsers[chat.dataValues.user] if (receiver) { req.io.to(receiver).emit('response', message) } res.status(200).json(message) }, async update (req, res) { const { chatId } = req.params const userId = req.user.id const type = { 1: { userId }, 2: { employeeId: userId } } const chat = await Chat.findOne({ where: { id: chatId, ...type[req.user.type] } }) if (!chat) { return res.status(401).json() } await Message.update({ isVisualized: true }, { where: { chatId, from: { [Op.ne]: userId } } }) res.status(200).json() } } <file_sep>/src/app/controllers/LanguageController.js const Language = require('../models/Language') module.exports = { async index (req, res) { const languages = await Language.findAll({ order: [ 'name' ] }) res.status(200).json(languages) } } <file_sep>/src/config/algorithmia.js module.exports = { apiKey: process.env.AUGORITHMIA_API_KEY } <file_sep>/src/database/seeders/20190930041152-demo-items.js 'use strict' module.exports = { up: queryInterface => { const names = ['Qualidade no Atendimento', 'Experiência do Intercâmbio', 'Relação de custo-benefício'] const data = [] let id = 0 names.map(name => { id++ data.push({ id, name }) }) return queryInterface.bulkInsert('items', data, {}) }, down: queryInterface => { return queryInterface.bulkDelete('items', null, {}) } } <file_sep>/src/app/controllers/AuthController.js const User = require('../models/User') const bcrypt = require('bcryptjs') const jwt = require('jsonwebtoken') const authConfig = require('../../config/auth') const crypto = require('crypto') const Mail = require('../../lib/Mail') const path = require('path') const sequelize = require('sequelize') module.exports = { async register (req, res) { const filename = req.file ? req.file.filename : undefined const { type, agency, name, email, password, dateOfBirth } = req.body try { await User.create({ typeId: type, agencyId: agency, filename, name, password, email, dateOfBirth }) res.status(200).json(); } catch (err) { res.status(400).json(err) } }, async authenticate (req, res) { const { email, password } = req.body const user = await User.findOne({ where: { email }, attributes: ['id', 'typeId', 'agencyId', 'password', 'isActive'] }) if (!user) return res.status(400).json({ error: 'E-mail inválido' }) if (!(await bcrypt.compare(password, user.password))) { return res.status(400).json({ error: 'Senha inválida' }) } if (!user.isActive) return res.status(401).json() const { id, typeId, agencyId } = user const token = jwt.sign({ user: { id, type: typeId, agency: agencyId } }, authConfig.secret, { expiresIn: 86400 }) res.status(200).json({ token }) }, async sendEmail (req, res) { const { email } = req.body const user = await User.findOne({ attributes: ['id', 'name', [ sequelize.fn('date_format', sequelize.col('dateOfBirth'), '%d/%m/%Y'), 'dateOfBirth' ]], include: [ { attributes: ['name'], association: 'type' } ], where: { email } }) if (!user) return res.status(400).json({ error: 'Usuário não encontrado' }) const token = crypto.randomBytes(20).toString('hex') const expiresIn = new Date() expiresIn.setHours(expiresIn.getHours() + 1) await user.update({ token, expiresIn }) const { name, dateOfBirth, type } = user Mail.sendMail({ from: 'Best Way Exchange <<EMAIL>>', to: `${name} <${email}>`, template: 'send_email', context: { name, dateOfBirth, type: type.name, email, token }, attachments: [ { filename: 'logo.png', path: path.resolve(__dirname, '..', 'views', 'emails', 'attachments', 'logo.png'), cid: 'logo' // same cid value as in the html img src } ] }, err => { console.log(err); if (err) { return res.status(400).json({ error: 'Erro ao enviar e-mail' }) } res.status(200).json() }) }, async confirmEmail (req, res) { const { email, token } = req.body const user = await User.findOne({ where: { email } }) if (!user) return res.status(400).json({ error: 'Usuário não encontrado' }) if (token !== user.token) return res.status(400).json({ error: 'Autenticação inválida' }) const now = new Date() if (now > user.expiresIn) return res.status(400).json({ error: 'Autenticação expirada, envie outro e-mail de confirmação' }) await user.update({ isActive: true }) res.status(200).json() } } <file_sep>/src/database/seeders/20190930043016-demo-favorites.js 'use strict' module.exports = { up: queryInterface => { const data = [] const favorites = [] for (let i = 0; i < 1714; i++) { let exchangeId = Math.floor((Math.random() * 100) + 1) let userId = Math.floor((Math.random() * 120) + 41) while ( favorites.some(([_exchangeId, _userId]) => _exchangeId === exchangeId && _userId === userId) ) { exchangeId = Math.floor((Math.random() * 100) + 1) userId = Math.floor((Math.random() * 120) + 41) } favorites.push([ exchangeId, userId ]) data.push({ exchangeId, userId, createdAt: new Date() }) } return queryInterface.bulkInsert('favorites', data, {}) }, down: queryInterface => { return queryInterface.bulkDelete('favorites', null, {}) } } <file_sep>/src/app/controllers/AddressController.js const Address = require('../models/Address') const cep = require('cep-promise') module.exports = { async index (req, res) { const { agencyId } = req.params const addresses = await Address.findAll({ where: { agencyId } }) res.status(200).json(addresses) }, async store (req, res) { const { zipCode } = req.body try { const { state, city, neighborhood, street } = await cep(zipCode) const address = await Address.create({ zipCode, state, city, neighborhood, street, agencyId: req.user.agency }) res.status(200).json(address) } catch (err) { res.status(400).json(err) } }, async update (req, res) { const { number, complement } = req.body try { await Address.update({ number, complement }, { where: { id: req.params.id } }) res.status(200).json() } catch (err) { res.status(400).json(err) } }, async destroy (req, res) { await Address.destroy({ where: { id: req.params.id } }) res.status(200).json() } } <file_sep>/src/database/seeders/20191015225434-demo-agency_grades.js 'use strict' module.exports = { up: queryInterface => { const data = [] const userAgencies = [] for (let i = 0; i < 600; i++) { let agencyId = Math.floor((Math.random() * 10) + 1) let userId = Math.floor((Math.random() * 120) + 41) while ( userAgencies.some(([_agencyId, _userId]) => _agencyId === agencyId && _userId === userId) ) { agencyId = Math.floor((Math.random() * 10) + 1) userId = Math.floor((Math.random() * 120) + 41) } userAgencies.push([ agencyId, userId ]) data.push({ agencyId, userId, gradeId: Math.floor((Math.random() * 5) + 1), createdAt: new Date() }) } return queryInterface.bulkInsert('agency_grades', data, {}) }, down: queryInterface => { return queryInterface.bulkDelete('agency_grades', null, {}) } } <file_sep>/src/app/middlewares/AuthMiddleware.js const jwt = require('jsonwebtoken') const authConfig = require('../../config/auth') module.exports = (req, res, next) => { const authHeader = req.headers.authorization if (!authHeader) return res.status(401).json({ error: 'No token provided' }) const parts = authHeader.split(' ') if (!parts.length === 2) { return res.status(401).json({ error: 'Token error' }) } const [scheme, token] = parts if (!/^Bearer$/i.test(scheme)) { return res.status(401).json({ error: 'Token malformatted' }) } jwt.verify(token, authConfig.secret, (err, decoded) => { if (err) return res.status(401).json({ error: 'Token invalid' }) const { id, type, agency } = decoded.user req.user = { id, type, agency } next() }) } <file_sep>/src/app/models/Item.js const { Model, DataTypes } = require('sequelize') class Item extends Model { static init (sequelize) { super.init({ name: DataTypes.STRING }, { sequelize, tableName: 'items', timestamps: false }) } static associate (models) { this.belongsToMany(models.Rate, { through: models.ItemRate, foreignKey: 'itemId', as: 'rates' }) } } module.exports = Item <file_sep>/src/database/migrations/20191012232238-create-exchange_housing_types.js 'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('exchange_housing_types', { exchangeId: { allowNull: false, primaryKey: true, type: Sequelize.INTEGER, references: { model: 'exchanges', key: 'id' }, onDelete: 'CASCADE' }, housingTypeId: { allowNull: false, primaryKey: true, type: Sequelize.INTEGER, references: { model: 'housing_types', key: 'id' }, onDelete: 'CASCADE' } }) }, down: queryInterface => { return queryInterface.dropTable('exchange_housing_types') } } <file_sep>/src/app/models/ExchangeType.js const { Model, DataTypes } = require('sequelize') class ExchangeType extends Model { static init (sequelize) { super.init({ name: DataTypes.STRING, description: DataTypes.TEXT }, { sequelize, tableName: 'exchange_types', timestamps: false }) } static associate (models) { this.hasMany(models.Exchange, { as: 'exchanges', foreignKey: 'exchangeTypeId' }) } } module.exports = ExchangeType <file_sep>/src/app/models/Message.js const { Model, DataTypes } = require('sequelize') class Message extends Model { static init (sequelize) { super.init({ body: DataTypes.TEXT('long'), filename: DataTypes.STRING, isVisualized: { type: DataTypes.BOOLEAN, defaultValue: false } }, { sequelize, tableName: 'messages', updatedAt: false }) this.removeAttribute('id') require('sequelize-paginate').paginate(this) } static associate (models) { this.belongsTo(models.Chat, { as: 'chat', foreignKey: 'chatId' }) this.belongsTo(models.User, { as: 'user', foreignKey: 'from' }) } } module.exports = Message <file_sep>/src/app/models/UserType.js const { Model, DataTypes } = require('sequelize') class UserType extends Model { static init (sequelize) { super.init({ name: DataTypes.STRING }, { sequelize, tableName: 'user_types', timestamps: false }) } static associate (models) { this.hasMany(models.User, { foreignKey: 'typeId', as: 'users' }) } } module.exports = UserType <file_sep>/src/routes/index.js const express = require('express') const free = require('./free') const logged = require('./logged') const AuthMiddleware = require('../app/middlewares/AuthMiddleware') const routes = express.Router() routes.use(free) routes.use(AuthMiddleware) routes.use(logged) module.exports = routes <file_sep>/src/app/models/Rate.js const { Model, DataTypes } = require('sequelize') class Rate extends Model { static init (sequelize) { super.init({ comment: { type: DataTypes.TEXT('long'), validate: { notEmpty: { msg: 'A descrição não deve ser nula' } } }, isRated: { type: DataTypes.BOOLEAN, defaultValue: false } }, { sequelize, tableName: 'rates' }) require('sequelize-paginate').paginate(this) } static associate (models) { this.belongsTo(models.Exchange, { foreignKey: 'exchangeId', as: 'exchanges' }) this.belongsTo(models.User, { foreignKey: 'userId', as: 'users' }) this.belongsToMany(models.Item, { through: models.ItemRate, as: 'items', foreignKey: 'rateId' }) } } module.exports = Rate <file_sep>/src/app/models/User.js const { Model, DataTypes } = require('sequelize') const bcrypt = require('bcryptjs') class User extends Model { static init (sequelize) { super.init({ email: { type: DataTypes.STRING, unique: { msg: 'E-mail já cadastrado no sistema' }, validate: { notEmpty: { msg: 'O e-mail não deve ser nulo' }, isEmail: { msg: 'E-mail informado está no formato inválido' } } }, name: { type: DataTypes.STRING, validate: { notEmpty: { msg: 'O nome não deve ser nulo' } } }, password: { type: DataTypes.STRING, validate: { notEmpty: { msg: 'A senha não deve ser nula' }, len: { args: [7, 42], msg: 'A senha deve conter entre 7 e 42 caracteres' } } }, token: DataTypes.STRING, expiresIn: DataTypes.DATE, dateOfBirth: { type: DataTypes.DATEONLY, validate: { isDate: { msg: 'Formato de data inválido' } } }, isActive: { type: DataTypes.BOOLEAN, defaultValue: false }, filename: DataTypes.STRING }, { sequelize, tableName: 'users', timestamps: false, hooks: { beforeCreate: async user => { user.password = await bcrypt.hash(user.password, 10) } } }) } static associate (models) { this.belongsTo(models.UserType, { foreignKey: 'typeId', as: 'type' }) this.belongsTo(models.Agency, { foreignKey: 'agencyId', as: 'agency' }) this.hasMany(models.Favorite, { as: 'favorites', foreignKey: 'userId' }) this.hasMany(models.Rate, { as: 'rates', foreignKey: 'userId' }) this.hasMany(models.Chat, { as: 'chats', foreignKey: 'userId', otherKey: 'employeeId' }) this.belongsToMany(models.Agency, { through: models.AgencyGrade, foreignKey: 'userId', as: 'agencies' }) this.hasMany(models.Message, { as: 'messages', foreignKey: 'from' }) } } module.exports = User <file_sep>/src/app/models/Favorite.js const { Model } = require('sequelize') class Favorite extends Model { static init (sequelize) { super.init({ }, { sequelize, tableName: 'favorites', updatedAt: false }) this.removeAttribute('id') } static associate (models) { this.belongsTo(models.User, { foreignKey: 'userId', as: 'user' }) this.belongsTo(models.Exchange, { foreignKey: 'exchangeId', as: 'exchange' }) } } module.exports = Favorite <file_sep>/src/app/controllers/NotificationController.js const { Op } = require('sequelize') const Message = require('../models/Message') const Rate = require('../models/Rate') module.exports = { async index (req, res) { const userId = req.user.id const type = { 1: { userId }, 2: { employeeId: userId } } const { page = 1 } = req.query const messages = await Message.paginate({ attributes: ['createdAt'], page, paginate: 2, order: [ ['createdAt', 'DESC'] ], where: { from: { [Op.ne]: userId }, isVisualized: false }, include: [ { association: 'user', attributes: ['id', 'name', 'filename'] }, { association: 'chat', where: type[req.user.type], attributes: ['id'], include: [ { association: 'exchange', attributes: ['id', 'name', 'filename'] } ] } ] }) messages.docs.map(message => { delete message.chatId }) const rates = await Rate.paginate({ page, paginate: 2, order: [ ['createdAt', 'DESC'] ], where: { userId, isRated: false }, attributes: ['id', 'createdAt'], include: [ { association: 'exchanges', attributes: ['id', 'name', 'filename'] } ] }) res.status(200).json({ messages, rates }) } } <file_sep>/src/app/models/Grade.js const { Model, DataTypes } = require('sequelize') class Grade extends Model { static init (sequelize) { super.init({ name: DataTypes.STRING }, { sequelize, tableName: 'grades', timestamps: false }) } static associate (models) { this.hasMany(models.AgencyGrade, { foreignKey: 'gradeId', as: 'agencies' }) this.hasMany(models.ItemRate, { foreignKey: 'gradeId', as: 'rates' }) } } module.exports = Grade <file_sep>/src/database/seeders/20190930042140-demo-exchange_types.js 'use strict' module.exports = { up: queryInterface => { const exchangeTypes = [ { name: 'Estudo de Idiomas', description: 'Essa modalidade de intercâmbio tem como objetivo o aprendizado de uma nova língua. Tanto pode ser feia por pessoas que têm um nível inicial na língua estrangeira quanto por pessoas que já possuem um nível mais avançados e desejam evoluir ainda mais.' }, { name: 'Au Pair', description: 'Cuidar de crianças, ser pago por isso e se manter nos Estados Unidos com o que recebe da família contratante é o objetivo de quem deseja fazer intercâmbio do tipo Au Pair. Com esse tipo de programa é possível passar cerca de uma ano nos Estados Unidos. Além da remuneração, a família contratante ainda paga um curso para a babá.' }, { name: 'Graduação', description: 'O estudante pode tanto cursar a graduação inteira em instituições estrangeiras quanto um semestre ou período específico.' }, { name: 'Especialização profissional', description: 'É possível fazer uma especialização profissional fora do país, como um mestrado, doutorado ou algum curso que ofereça capacitação específica para um aspecto da área de conhecimento estudada.' }, { name: 'Work and Travel', description: 'Estudar e trabalhar também é um dos tipos de intercâmbio possíveis. Nesse caso, não necessariamente a viagem estará vinculada à uma instituição de ensino. A pessoa irá para outro país através de programas de trabalho que trarão mais experiência para o currículo, aprendizado da língua estrangeira e nova vivências interpessoais.' }, { name: 'Voluntariado', description: 'O voluntariado é considerado uma das formas mais generosas de intercâmbio. Nessa modalidade a pessoa viajar para trabalhar voluntariamente em uma ONG ou outro tipo de organização que realiza trabalhos sociais. A partir das vivências vem o aprendizado, assim como no Work and travel, a melhora nas habilidades de fala e compreensão da língua é desenvolvida através do contato com outras pessoas.' } ] const data = [] let id = 0 exchangeTypes.map(({ name, description }) => { id++ data.push({ id, name, description }) }) return queryInterface.bulkInsert('exchange_types', data, {}) }, down: queryInterface => { return queryInterface.bulkDelete('exchange_types', null, {}) } } <file_sep>/src/database/seeders/20190930035743-demo-countries.js 'use strict' module.exports = { up: queryInterface => { const countries = [ { name: 'Suíça', description: ` Charmosos e encantadores, os principais pontos turísticos da Suíça atraem visitantes de todo o mundo, inclusive brasileiros. As atrações têm características que agradam aos gostos mais variados, desde Alpes e oportunidades de escalada para aventureiros até belos castelos e construções repletas de histórias, lendas e curiosidades. `, filename: 'Suíça-1574404044419.jpg' }, { name: 'Brasil', description: ` O Brasil oferece aos turistas nacionais e internacionais uma ampla gama de opções, sendo que as áreas naturais são o seu produto turístico mais popular, uma combinação de ecoturismo com lazer e recreação, principalmente sol e praia e turismo de aventura, bem como o turismo histórico e cultural. `, filename: 'Brasil-1574404044423.jpg' }, { name: 'Finlândia', description: ` De país substancialmente agrícola a um dos mais desenvolvidos da Europa, a Finlândia tem muito a ensinar - não só para os viajantes como para o mundo todo. O país exibe alguns dos melhores indicadores sociais do mundo, como renda, escolaridade e qualidade de vida e já foi considerado o segundo país mais estável do globo, ficando atrás apenas da Dinamarca. `, filename: 'Finlândia-1574404044426.jpg' }, { name: 'Canadá', description: ` Como não considerar fazer um intercâmbio no Canadá? Tem neve e tem praia, tem Inglês e Francês, moradores hospitaleiros e paisagens de cinema. Com tanta variedade e uma enorme preocupação com a qualidade de vida, não é por acaso que o Canadá está entre os destinos preferidos dos estudantes brasileiros, que têm o privilégio de mergulhar na riqueza multicultural de um país mestre em receber outros povos de braços abertos. `, filename: 'Canadá-1574404044429.jpg' }, { name: '<NAME>', description: ` A viagem dura quase um dia inteiro e o fuso horário tem quinze horas de diferença em relação ao Brasil. Mas nenhum sacrifício é muito grande quando se trata da Nova Zelândia. Quem desembarca na terra dos kiwis – o nome que os habitantes locais ganharam em homenagem a um pássaro típico da região – logo fica deslumbrado com o clima tropical, a hospitalidade dos moradores e a bela paisagem, favorável aos esportes radicais ou apenas à contemplação. `, filename: 'Nova Zelândia-1574404044430.jpg' }, { name: 'Austrália', description: ` A Austrália é maior país da Oceania, ex-colônia britânica e hoje é uma das nações mais ricas do mundo e um dos destinos preferidos de quem procura o exótico com um gosto familiar. Fazer um intercâmbio na Austrália é poder desfrutar de paisagens inacreditáveis e raras, também praias maravilhosas, um clima parecido ao nosso e peculiaridades que tornam a estada ainda mais agradável. Os australianos são conhecidos pelo jeitão relax e por saberem acolher o viajante, até facilitando as coisas para quem vai fazer algum curso – a Austrália é um dos poucos países que permitem que o estrangeiro trabalhe enquanto estuda. `, filename: 'Austrália-1574404044431.jpg' }, { name: 'Suécia', description: ` O melhor da Suécia é a sua natureza e paisagens. É, por isso, longe das cidades, que se concentram na metade sul do país, que com mais facilidade vai tropeçar em argumentos de cortar a respiração e que valem qualquer viagem. Caminhadas, ciclismo, campismo, esqui e passeios de barco são das atividades mais procuradas por quem vive na Suécia, assim como a pesca e a “caça” aos cogumelos e bagas. `, filename: 'Suécia-1574404244212.jpg' }, { name: 'Noruega', description: ` A Noruega possui uma extensa costa litorânea, recortada por fiordes (golfos estreitos e profundos, delimitados por montanhas). Essas características físicas proporcionam belas paisagens, além de impulsionarem a atividade pesqueira. `, filename: 'Noruega-1574404244213.jpg' }, { name: 'Dinamarca', description: ` A Dinamarca é gigante em cultura, culinária e beleza natural. Atrações como Tivoli, a Pequena Sereia e Legoland fascinam os visitantes de todo o mundo há anos. Além disso, o país figura no top 3 dos mais felizes do mundo nos últimos anos de acordo com o Relatório Mundial da Felicidade, das Nações Unidas. `, filename: 'Dinamarca-1574404244214.jpg' }, { name: 'Holanda', description: ` Charmosa, moderna e liberal. Essa é uma das melhores definições para a Holanda, que na verdade se divide em duas províncias: Holanda do Norte, onde fica a capital Amsterdã, e Holanda do Sul, onde se situa a sede do governo Haia. Ambas fazem parte da área chamada de Países Baixos, devido à baixa altitude. Cerca de um terço do território holandês encontra-se abaixo do nível do mar. `, filename: 'Holanda-1574404244215.jpg' } ] const data = [] let id = 0 countries.map(({ name, description, filename }) => { id++ data.push({ id, name, description, filename }) }) return queryInterface.bulkInsert('countries', data, {}) }, down: queryInterface => { return queryInterface.bulkDelete('countries', null, {}) } } <file_sep>/src/app/models/Address.js const { Model, DataTypes } = require('sequelize') class Address extends Model { static init (sequelize) { super.init({ zipCode: { type: DataTypes.STRING(8), validate: { notEmpty: { msg: 'O CEP não deve ser nulo' } } }, street: DataTypes.STRING, neighborhood: DataTypes.STRING, number: { type: DataTypes.INTEGER, validate: { notEmpty: { msg: 'O número não deve ser nulo' }, isInt: { msg: 'O número deve ser numérico' } } }, complement: DataTypes.STRING, city: DataTypes.STRING, state: DataTypes.STRING }, { sequelize, tableName: 'addresses', timestamps: false }) } static associate (models) { this.belongsTo(models.Agency, { foreignKey: 'agencyId', as: 'agency' }) } } module.exports = Address <file_sep>/src/database/seeders/20190930041431-demo-addresses.js 'use strict' module.exports = { up: queryInterface => { const faker = require('faker/locale/pt_BR') const data = [] console.log(faker.address.zipCode()) for (let i = 0; i < 30; i++) { data.push({ id: i + 1, zipCode: parseInt(faker.address.zipCode()), street: faker.address.streetName(), neighborhood: faker.lorem.words(), number: faker.random.number(), complement: faker.lorem.words(), city: faker.address.city(), agencyId: Math.floor((Math.random() * 10) + 1), state: faker.address.state() }) } return queryInterface.bulkInsert('addresses', data, {}) }, down: queryInterface => { return queryInterface.bulkDelete('addresses', null, {}) } } <file_sep>/src/database/seeders/20190930035047-demo-languages.js 'use strict' module.exports = { up: queryInterface => { const names = ['Chinês', 'Espanhol', 'Inglês', 'Hindi', 'Árabe', 'Português', 'Bengali', 'Russo', 'Japonês', 'Punjabi/Lahnda'] const data = [] let id = 0 names.map(name => { id++ data.push({ id, name }) }) return queryInterface.bulkInsert('languages', data, {}) }, down: queryInterface => { return queryInterface.bulkDelete('languages', null, {}) } } <file_sep>/src/app/controllers/HousingTypeController.js const HousingType = require('../models/HousingType') module.exports = { async index (req, res) { const housingTypes = await HousingType.findAll({ order: [ 'name' ] }) res.status(200).json(housingTypes) } } <file_sep>/src/app/models/ExchangeLanguage.js const { Model } = require('sequelize') class ExchangeLanguage extends Model { static init (sequelize) { super.init({ }, { sequelize, tableName: 'exchange_languages', timestamps: false }) } } module.exports = ExchangeLanguage <file_sep>/src/config/auth.js module.exports = { secret: process.env.SECRET_API } <file_sep>/src/app/controllers/FavoriteController.js const Favorite = require('../models/Favorite') module.exports = { async index (req, res) { const exchanges = await Favorite.findAll({ order: [ ['createdAt', 'DESC'] ], where: { userId: req.user.id }, attributes: ['createdAt'], include: [ { association: 'exchange', attributes: ['id', 'name', 'filename', 'createdAt', 'time', 'price'], include: [ { association: 'exchangeType', attributes: ['name'] }, { association: 'city', attributes: ['name'], include: [ { association: 'country', attributes: ['name'] } ] } ] } ] }) res.status(200).json(exchanges) }, async show (req, res) { const { exchangeId } = req.params const favorite = await Favorite.findOne({ where: { exchangeId, userId: req.user.id } }) res.status(200).json(!!favorite) }, async store (req, res) { const { exchangeId } = req.params const userId = req.user.id await Favorite.create({ userId, exchangeId }) res.status(200).json() }, async destroy (req, res) { const { exchangeId } = req.params const userId = req.user.id await Favorite.destroy({ where: { userId, exchangeId } }) res.status(200).json() } } <file_sep>/src/config/googleapis.js module.exports = { apiKey: process.env.GOOGLEAPIS_API_KEY, searchEngineId: '009869278601531910603:raqsbcjn6sa' } <file_sep>/src/database/seeders/20191012233559-demo-exchange_housing_types.js 'use strict' module.exports = { up: queryInterface => { const data = [] const exchangeHousingTypes = [] for (let i = 0; i < 345; i++) { let exchangeId = Math.floor((Math.random() * 100) + 1) let housingTypeId = Math.floor((Math.random() * 5) + 1) while ( exchangeHousingTypes.some(([_exchangeId, _housingTypeId]) => _exchangeId === exchangeId && _housingTypeId === housingTypeId) ) { exchangeId = Math.floor((Math.random() * 100) + 1) housingTypeId = Math.floor((Math.random() * 5) + 1) } exchangeHousingTypes.push([ exchangeId, housingTypeId ]) data.push({ exchangeId, housingTypeId }) } return queryInterface.bulkInsert('exchange_housing_types', data, {}) }, down: queryInterface => { return queryInterface.bulkDelete('exchange_housing_types', null, {}) } } <file_sep>/src/app/controllers/UserController.js const User = require('../models/User') module.exports = { async update (req, res) { const { name, email, password } = req.body if (req.user.id !== parseInt(req.params.id)) { return res.status(401).json() } try { await User.update({ name, email, password }, { where: { id: req.params.id } }) res.status(200).json() } catch (err) { res.status(400).json(err) } }, async destroy (req, res) { const user = await User.findByPk(req.params.id, { attributes: ['id', 'typeId', 'agencyId'] }) if (user.typeId === 2) { if (req.user.type !== 3) { return res.status(401).json() } if (user.agencyId !== req.user.agency) { return res.status(401).json() } } else { if (req.user.id !== parseInt(user.id)) { return res.status(401).json() } } await User.destroy({ where: { id: req.params.id } }) res.status(200).json() } } <file_sep>/src/database/seeders/20190930044543-demo-item_rates.js 'use strict' module.exports = { up: queryInterface => { const data = [] for (let i = 0; i < 1714; i++) { for (let j = 0; j < 3; j++) { data.push({ rateId: i + 1, itemId: j + 1, gradeId: Math.floor((Math.random() * 5) + 1) }) } } return queryInterface.bulkInsert('item_rates', data, {}) }, down: queryInterface => { return queryInterface.bulkDelete('item_rates', null, {}) } } <file_sep>/src/app/controllers/CityController.js const City = require('../models/City') module.exports = { async index (req, res) { const { countryId } = req.params const cities = await City.findAll({ order: [ 'name' ], where: { countryId }, attributes: ['id', 'name'] }) res.status(200).json(cities) }, async store (req, res) { const { countryId } = req.params const { name } = req.body try { await City.create({ name, countryId }) res.status(200).json() } catch (err) { res.status(400).json(err) } } } <file_sep>/src/app/models/City.js const { Model, DataTypes } = require('sequelize') class City extends Model { static init (sequelize) { super.init({ name: { type: DataTypes.STRING, validate: { notEmpty: { msg: 'O nome não deve ser nulo' } } } }, { sequelize, tableName: 'cities', timestamps: false }) } static associate (models) { this.hasMany(models.Exchange, { as: 'exchanges', foreignKey: 'cityId' }) this.belongsTo(models.Country, { as: 'country', foreignKey: 'countryId' }) } } module.exports = City
134df5d5e9bb633964ae78da7691de9e5ec2fc44
[ "JavaScript" ]
52
JavaScript
rafaelmellooo/bestwayexchange-backend
fd7b7d7aab1eb6b0845bed2a1c45165d47413f31
591538ad1b953535f9b93aa13c77261a309bb08b
refs/heads/master
<repo_name>miekd/torang<file_sep>/server/router.js var static = require('node-static'); function Router() { this.staticServer = new static.Server('../client'); } Router.prototype.route = function(handle, parsedURL, req, res) { console.log("Routing request for " + parsedURL.pathname + "?" + parsedURL.query); if (typeof handle[parsedURL.pathname] === 'function') { handle[parsedURL.pathname](req, res, parsedURL); } else { this.staticServer.serve(req, res); } } exports.Router = Router; <file_sep>/README.md torang ======
2026413211453539656aa08dc27c8517823f3dd3
[ "JavaScript", "Markdown" ]
2
JavaScript
miekd/torang
a6fb9825079a5ee42a5c2b5dc40603293bb2f9cc
508ac401839b0b77498c51186485042dd3be7786
refs/heads/main
<repo_name>SinghVivek96/PriceTracker<file_sep>/src/main/resources/static/JS/postrequest.js $( document ).ready(function() { // SUBMIT FORM function ajaxPost(urlF,dateF,priceF){ // PREPARE FORM DATA var formData = { url : urlF, date : dateF, price : priceF } //console.log(formData); console.log(JSON.stringify(formData),"hah"); // DO POST $.ajax({ type : "POST", contentType : "application/json; charset=utf-8", url : window.location + "welcome/update/save", data : JSON.stringify(formData), dataType : 'json', success : function(result) { if(result.status == "Done"){ $("#successValue").html( "<input class='form-control form-control-lg' type='text' placeholder='.form-control-lg' value='"+result.data.url+"''>"+ "<input class='form-control' type='text' placeholder='Default input' value='"+result.data.date+"'>"+ "<input class='form-control form-control-sm' type='text' placeholder='.form-control-sm' value='"+result.data.price+"'>" ); }else{ $("#postResultDiv").html("<strong>Error</strong>"); } //console.log(result); }, error : function(e) { //alert("Error!") console.log("ERROR: ", e); } }); // Reset FormData after Posting resetData(); } function resetData(){ $("#url").val(""); $("#date").val(""); $("#price").val(""); } var url_home = ""; document.getElementById("urlSubmit").addEventListener("click", function(event){ if(document.getElementById("urlValue").value != null) { url_home=document.getElementById("urlValue").value; console.log(url_home); document.getElementById("urlValue").value=""; mobileNext(url_home); //mobileHome(url_home); } event.preventDefault(); }); //$("#customerForm").submit(function(event) { // Prevent the form from submitting via the browser. // event.preventDefault(); //}); let url_next = "" ; var page=0; var isPaused = false; function mobileNext(url_next) { if(!isPaused) { isPaused=true; fetch(url_next).then(function (response) { return response.text(); }).then(function (html) { // Convert the HTML string into a document object var parser = new DOMParser(); var doc = parser.parseFromString(html, 'text/html'); var filteredData_links = doc.getElementsByClassName("s-main-slot s-result-list s-search-results sg-row")[0].getElementsByClassName("a-link-normal s-no-hover a-text-normal"); var filteredData_price = doc.getElementsByClassName("s-main-slot s-result-list s-search-results sg-row")[0].getElementsByClassName("a-price-whole"); nextPageHome = doc.getElementsByClassName("a-selected")[0].nextSibling.nextSibling.getElementsByTagName('a')[0].href; nextPageHome = "https://www.amazon.in"+nextPageHome.slice(nextPageHome.search("\/[\s]")); url_next = nextPageHome; var bar = new Promise((resolve,reject)=>{ for (var data=0;data<filteredData_links.length;data++) { // console.log(filteredData_price[data].innerText); // console.log("https://www.amazon.in"+filteredData_links[data].getAttribute('href')); var finalUrl="https://www.amazon.in"+filteredData_links[data].getAttribute('href'); finalUrl=finalUrl.split("/ref")[0]; var finalPrice=filteredData_price[data].innerText; let today = new Date().toISOString().slice(0, 10); if(!finalUrl.includes("slredirect")) { ajaxPost(finalUrl,today,finalPrice); } console.log("--------------------------"); if(data==filteredData_links.length-1) { page++; console.log(page); resolve(); } } }); bar.then(() => { isPaused=false; if(page<399) { setTimeout( function(){ mobileNext(url_next);}, 1000); } }); }).catch(function (err) { console.warn('Something went wrong.', err); }); } } function haha() { console.log("adsdfgh"); } function mobileHome(url_home) { if(!isPaused) { isPaused=true; fetch(url_home).then(function (response) { return response.text(); }).then(function (html) { // Convert the HTML string into a document object var parser = new DOMParser(); var doc = parser.parseFromString(html, 'text/html'); var nextPageHome = doc.getElementsByClassName("pagnRA")[0].getElementsByTagName('a')[0].href; nextPageHome = "https://www.amazon.in/s/" + nextPageHome.slice(nextPageHome.search("ref")); url_next = nextPageHome; var bar = new Promise((resolve,reject)=>{ var indexx =0 for(indexx =0;indexx<24;indexx++) { var fetchId = "result_"+indexx; var link = doc.getElementById(fetchId).getElementsByTagName('a'); var price = doc.getElementById(fetchId).getElementsByTagName("span"); var hrefs = []; var finalPrice; var finalUrl; for(var i=0; i < link.length; i++){ if((link[i].href).includes("www.amazon.in")) { // console.log(link[i].href); finalUrl=link[i].href; finalUrl=finalUrl.split("/ref")[0]; break; } } for(var i=0; i < price.length; i++){ if(price[i].className == "a-size-base a-color-price s-price a-text-bold") { // console.log(price[i].innerText); finalPrice=price[i].innerText; } } let today = new Date().toISOString().slice(0, 10) if(!finalUrl.includes("slredirect")) { ajaxPost(finalUrl,today,finalPrice); } // ajaxPost(finalUrl,today,finalPrice); console.log("------------------------------------------------------"); if(indexx==23) { page++; console.log(page); resolve(); } } }); bar.then(() => { isPaused=false; mobileNext(url_next); }); }).catch(function (err) { // There was an error console.warn('Something went wrong.', err); }); } } })<file_sep>/src/main/resources/application.properties spring.datasource.url=jdbc:mysql://localhost:3306/pricetracker spring.datasource.username=root spring.datasource.password=<PASSWORD> spring.jpa.hibernate.ddl-auto=none spring.jpa.properties.hibernate.format_sql=true <file_sep>/src/main/java/com/vivek/priceTracker/Amazon/Entities/AmazonEntityCopy.java package com.vivek.priceTracker.Amazon.Entities; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; public class AmazonEntityCopy{ private String url; private String date; private String price; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } @Override public String toString() { return "AmazonEntity [url=" + url + ", date=" + date + ", price=" + price + "]"; } public AmazonEntityCopy() { } public AmazonEntityCopy(String url, String date, String price) { super(); this.url = url; this.date = date; this.price = price; } }
26482b16e37f5dc0c6868e5f3c4decbfe4b1a146
[ "JavaScript", "Java", "INI" ]
3
JavaScript
SinghVivek96/PriceTracker
1162fa58bb30884024af0657246e4ca7501937d3
fe2942c460ce65f1aedb5165a127f12e9cdf7ab5
refs/heads/main
<file_sep>import getHash from '../utils/getHash'; import getDataMovie from '../utils/getDataMovie'; const Pelicula = async () =>{ const id = getHash(); const pelicula = await getDataMovie(id); const img_url = 'https://image.tmdb.org/t/p/w500'; const view = ` <div class="Movies-inner"> <article class="Movies-card"> <img src="${img_url}${pelicula.poster_path}" alt="${pelicula.title}"/> </article> <article class="Movies-card"> <h2>${pelicula.title}</h2> <h4>Sinopsis: <i>${pelicula.overview} </i></h4> <h4>Fecha de estreno: <i> </i>${pelicula.release_date}</h4> <h4>Puntuación: <i>${pelicula.vote_average}/10</i> </h4> </article> </div> `; return view; } export default Pelicula;<file_sep>const Header = () =>{ const view = ` <div class="header-a"> <a href="#"> Peliculas </a> </div> `; return view; } export default Header;<file_sep>import router from './src/routes'; window.addEventListener('load',router); window.addEventListener('hashchange',router);<file_sep> Deploy: https://1alexishuck1.github.io/SPA-pelicula-vanilla/ # SPA-peliculas # SPA-vanilla # SPA-pelicula-vanilla
1ca5bdb2e6055f74c7ecf198b57377b147b46297
[ "JavaScript", "Markdown" ]
4
JavaScript
1alexishuck1/SPA-pelicula-vanilla
d3e596b896c43cb72ff8e2afa8c5c5a638159ca2
1505d0e6a155bf0e78280bbe616ee92d877eb051
refs/heads/master
<repo_name>thiagochacon/LingGenXSocGen<file_sep>/LingGenXSocGen.R setwd("/Users/sarahpeoples/Documents/PhD_Orga/Conferences_Workshops_Presentations/QMSS_2017/LingGenXSocGen/") setwd("C:/Users/jn/OneDrive/Courses/QMSS 2017/LingGenXSocGen/") # Read in data files socgen= read.csv(file="dplace-societies-2017-05-09_socialgender.csv", header=T, skip = 1, encoding = "UTF-8") str(socgen) descent= read.csv(file="dplace-societies-2017-05-12_descent.csv", header=T, skip = 1, encoding = "UTF-8") #Glottolog code socgen $ Glottolog.language.dialect.id str(descent) # # option 1: (can only be used when you are absolutely SURE that the rows are in exactly the same order in both data frames!!) create a copy of the data, create a variable of the code from descent, then add the descent code to the new data # new.data= socgen # descentcode=descent$Code..EA043.Descent..major.type # new.data$descentcode <- descentcode # str(new.data) # option 2: merge d-place data merge.data= merge(socgen, descent, by="Glottolog.language.dialect.id") str(merge.data) clean.data= data.frame(merge.data$Glottolog.language.dialect.id, merge.data$Preferred.society.name.x, merge.data$ Society.id.x, merge.data$ Language.family.x , merge.data$ Code..EA050.Sex.differences..gathering, merge.data$ Code..EA052.Sex.Differences..fishing, merge.data$ Code..EA054.Sex.differences..agriculture, merge.data$ Code..EA051.Sex.differences..hunting, merge.data$ Revised.latitude.x, merge.data$ Revised.longitude.x, merge.data$ Code..EA043.Descent..major.type) str(clean.data) # merge d-place data and grambank data grambank= read.table("gb51_fixed.txt", sep='\t', stringsAsFactors=F, header=T, encoding = "UTF-8") str(grambank) clean.gdata = data.frame(grambank$Glottolog, grambank$Gender_Value) # names.gdata=c("Glottolog.language.dialect.id", "GB_Feature", "gramgender") # names(clean.gdata)= names.gdata str(clean.gdata) clean.data = merge(clean.data, clean.gdata, by.x= "merge.data.Glottolog.language.dialect.id", by.y="grambank.Glottolog") str(clean.data) ### Step 1: look at gender in society and language hist(clean.data$grambank.Gender_Value) hist(clean.data $ merge.data.Code..EA050.Sex.differences..gathering) hist(clean.data $ merge.data.Code..EA051.Sex.differences..hunting) hist(clean.data $ merge.data.Code..EA054.Sex.differences..agriculture) hist(clean.data$ merge.data.Code..EA052.Sex.Differences..fishing) ### Step 2: in D-Place, 1&2 should be coded as 1, 3&4 as 0, 5&6 as 1 data_wo_descent<-clean.data[,-which(names(clean.data)=="merge.data.Code..EA043.Descent..major.type")] recode = function(x){ y = rep(0,length(x)) y[x %in% c(1,2,5,6)] = 2 y[x %in% c(3)] = 1 y[x %in% c(4,7)] = 0 y[x %in% c(8,9)] = NA y } #recode = function(x){ # y = rep(0,length(x)) # y[x %in% c(1,2,5,6)] = 1 # y[x %in% c(3,4,7)] = 0 # y[x %in% c(8,9)] = NA # y #} data_wo_descent$gathering = recode(data_wo_descent$merge.data.Code..EA050.Sex.differences..gathering) data_wo_descent$fishing = recode(data_wo_descent$merge.data.Code..EA052.Sex.Differences..fishing) data_wo_descent$agriculture = recode(data_wo_descent$merge.data.Code..EA054.Sex.differences..agriculture) data_wo_descent$hunting = recode(data_wo_descent$merge.data.Code..EA051.Sex.differences..hunting) hist(data_wo_descent$gathering) hist(data_wo_descent$fishing) hist(data_wo_descent$agriculture) hist(data_wo_descent$hunting) boxplot(data_wo_descent$grambank.Gender_Value, data_wo_descent$hunting) boxplot(data_wo_descent$grambank.Gender_Value, data_wo_descent$gathering) boxplot(data_wo_descent$grambank.Gender_Value, data_wo_descent$fishing) data_wo_descent$soc_gen_score = rowSums(data_wo_descent[,c("gathering","fishing","agriculture","hunting")], na.rm = T) plot(data_wo_descent$grambank.Gender_Value, data_wo_descent$soc_gen_score) boxplot(data_wo_descent$grambank.Gender_Value, data_wo_descent$soc_gen_score) table(data_wo_descent$grambank.Gender_Value) # boxplot suggests that languages without sex-based gender, have lower social gender score (sex-based distinctions) and vice versa # greater variation in languages with sex-based gender # consistent with general hypothesis that language mirrors society, but society changes faster than language #families: Austronesian, Atlantic-Congo, Afro-Asiatic, Arawakan # mixed effects model: with geography, lang family as random effects and social score as predictor variable # look at lgs with gender but with low social gender score # coding of Social Gender Score (SGS) = 0 means society does not have gender segregation in an acivity; 1 = neutral; 2 = social roles well defined based on gender library(maps) #language sample languages = unique(data_wo_descent$merge.data.Preferred.society.name.x) colours = rainbow(length(languages)) map() points(data_wo_descent$merge.data.Revised.longitude.x, data_wo_descent$merge.data.Revised.latitude.x, col = colours, pch=16, ncol=2) #language families lang_fam = unique(data_wo_descent$merge.data.Language.family.x) colours = rainbow(length(lang_fam)) map() points(data_wo_descent$merge.data.Revised.longitude.x, data_wo_descent$merge.data.Revised.latitude.x, col = colours, pch=16, ncol=2) legend(-45,-40, legend=lang_fam, col=colours, pch=16, ncol=2) # sex-based gender gender = unique(data_wo_descent$grambank.Gender_Value) colours = rainbow(length(gender)) map() points(data_wo_descent$merge.data.Revised.longitude.x, data_wo_descent$merge.data.Revised.latitude.x, col = colours, pch=16, ncol=2) legend(-45,-40, legend=gender, col=colours, pch=16, ncol=2)
f6c1d9e65612ce243fdd28d2c84950a087062d78
[ "R" ]
1
R
thiagochacon/LingGenXSocGen
bda6526e5d3fdf5abd1a34a43318104ed04ea94d
3ce37d2f7287bc4b9db4c23f565630e066031aca
refs/heads/master
<repo_name>Solorio17/Js_Budz<file_sep>/J's_Budz/scripts/Inventory.js var imagesq = [ "images/dank5.jpg", "images/dank9.jpg", "images/dank4.jpg", "images/dank11.jpg", "images/dankone.jpg", "images/danktwo.jpg", "images/dankthree.jpg" ]; //Start at Zero var num = 0; //Function next() Moves Images to Next One function next() { var slider = document.getElementById("slider"); num++; if(num >= imagesq.length) { num = 0; } slider.src = imagesq[num]; } //Function prev() Moves Images to Previous One function prev() { var slider = document.getElementById("slider"); num--; if(num < 0) { num = imagesq.length-1; } slider.src = imagesq[num]; } var imagesx = [ "images/dab3.jpg", "images/dab2.jpeg", "images/dab5.jpg", "images/dab4.jpg", "images/dabone.jpg", "images/dabtwo.jpg", "images/dabthree.jpg" ]; //Start at Zero var num = 0; //Function next() Moves Images to Next One function nexti() { var slider = document.getElementById("sliders"); num++; if(num >= imagesx.length) { num = 0; } slider.src = imagesx[num]; } //Function prev() Moves Images to Previous One function previ() { var slider = document.getElementById("sliders"); num--; if(num < 0) { num = imagesx.length-1; } slider.src = imagesx[num]; } var imagesxx = [ "images/edibles.jpg", "images/edible1.jpg", "images/edible2.jpg", "images/edible3.jpg", "images/edible4.jpg" ]; //Start at Zero var num = 0; //Function next() Moves Images to Next One function nextis() { var slider = document.getElementById("sliderss"); num++; if (num >= imagesxx.length) { num = 0; } slider.src = imagesxx[num]; } //Function prev() Moves Images to Previous One function previs() { var slider = document.getElementById("sliderss"); num--; if (num < 0) { num = imagesxx.length - 1; } slider.src = imagesxx[num]; } var imagesxxx = [ "images/accessories.jpg", "images/acc1.JPG", "images/acc2.jpg", "images/acc3.jpg", "images/acc4.jpg", "images/acc5.jpg", "images/acc6.jpg" ]; //Start at Zero var num = 0; //Function next() Moves Images to Next One function nextit() { var slider = document.getElementById("slidersss"); num++; if (num >= imagesxxx.length) { num = 0; } slider.src = imagesxxx[num]; } //Function prev() Moves Images to Previous One function previt() { var slider = document.getElementById("slidersss"); num--; if (num < 0) { num = imagesxxx.length - 1; } slider.src = imagesxxx[num]; }<file_sep>/README.md # J-s-Budz
85d6a3fdc9e35ba281996f1d1adfda39fc5ce05e
[ "JavaScript", "Markdown" ]
2
JavaScript
Solorio17/Js_Budz
03b4f140fa509023b983ec1c4ae3629f82298a1d
15ccd5ffd7a32081fcf893ddf0144a4cbd8aa6e7
refs/heads/master
<repo_name>imust98/FE-Learning<file_sep>/前端知识点总结/01-html/04-cookie和session,sessionStorage和localStorage区别.md #### 请你谈谈Cookie的弊端 ``` cookie虽然在持久保存客户端数据提供了方便,分担了服务器存储的负担,但还是有很多局限性的。 第一:每个特定的域名下最多生成20个cookie 1.IE6或更低版本最多20个cookie 2.IE7和之后的版本最后可以有50个cookie。 3.Firefox最多50个cookie 4.chrome和Safari没有做硬性限制 IE和Opera 会清理近期最少使用的cookie,Firefox会随机清理cookie。 cookie的最大大约为4096字节,为了兼容性,一般不能超过4095字节,每个cookie长度不能超过4KB,否则会被截掉. ``` #### 浏览器本地存储 ``` html5中的Web Storage包括了两种存储方式:sessionStorage和localStorage。 sessionStorage用于本地存储一个会话(session)中的数据,这些数据只有在同一个会话中的页面才能访问并且当会话结束后数据也随之销毁。 因此sessionStorage不是一种持久化的本地存储,仅仅是会话级别的存储。 而localStorage用于持久化的本地存储,除非主动删除数据,否则数据是永远不会过期的。 ``` #### web storage和cookie的区别 ``` Web Storage的概念和cookie相似,区别是它是为了更大容量存储设计的。 Cookie的大小是受限的,并且每次你请求一个新的页面的时候Cookie都会被发送过去,这样无形中浪费了带宽, 另外cookie还需要指定作用域,不可以跨域调用。 除此之外,Web Storage拥有setItem,getItem,removeItem,clear等方法,不像cookie需要前端开发者自己封装setCookie,getCookie。 但是cookie也是不可以或缺的:cookie的作用是与服务器进行交互,作为HTTP规范的一部分而存在 , 而Web Storage仅仅是为了在本地“存储”数据而生。 localStorage和sessionStorage都具有相同的操作方法,例如setItem、getItem和removeItem等 ``` #### cookie 和session 的区别: ``` 1、cookie数据存放在客户的浏览器上,session数据放在服务器上。 2、cookie不是很安全,别人可以分析存放在本地的COOKIE并进行COOKIE欺骗 考虑到安全应当使用session。 3、session会在一定时间内保存在服务器上。当访问增多,会比较占用你服务器的性能 考虑到减轻服务器性能方面,应当使用COOKIE。 4、单个cookie保存的数据不能超过4K,很多浏览器都限制一个站点最多保存20个cookie。 5、所以个人建议: 将登陆信息等重要信息存放为SESSION 其他信息如果需要保留,可以放在COOKIE中 ```<file_sep>/前端知识点总结/01-html/09-各浏览器并行下载资源数.md #### ie各版本和chrome可以并行下载多少个资源 ``` IE6 两个并发,iE7升级之后的6个并发,之后版本也是6个 Firefox,chrome也是6个 ```<file_sep>/css学习笔记/精通CSS/02-选择器.md ### 选择器-为样式找到应用目标 #### 1. 基本选择器 - 元素(标签)选择器 - 后代选择器: 使用空格表示,例如 `p span` - id选择器 - 类选择器 `不要过度使用id和class,适量使用配合其他选择器!` - 伪类选择器 ``` :link和:visited称为链接伪类,只能用于链接; :hover、:active、:focus称为动态伪类,理论上可用于任何元素。 巧记: Lord Vador Hates Furry Animals(韦德公爵讨厌带毛的动物) ``` - 通用选择器(*): 最强大但是日常中应该最少使用的选择器,作用像通配符。 #### 2. 高级选择器 - 子选择器(>): 选择元素的直接后代,即子元素。例: #nav > li - 相邻同胞选择器(+): 用于定位同一个父元素下某个元素之后的元素。 例: h2 + p - 属性选择器: a[title] a[title='xxx'] a[title~='xxx'] <file_sep>/前端知识点总结/01-html/04-01-cookie和session完全总结(!!!).md #### cookie机制 ``` Cookies是服务器在本地机器上存储的小段文本并随每一个请求发送至同一个服务器。 网络服务器用HTTP头向客户端发送cookies,在客户终端,浏览器解析这些cookies并将它们保存为一个本地文件, 它会自动将同一服务器的任何请求缚上这些cookies 。 ``` ``` 具体来说cookie机制采用的是在客户端保持状态的方案。 它是在用户端的会话状态的存贮机制,他需要用户打开客户端的cookie支持。cookie的作用就是为了解决HTTP协议无状态的缺陷所作的努力。 ``` ``` 正统的cookie分发是通过扩展HTTP协议来实现的,服务器通过在HTTP的响应头中加上一行特殊的指示以提示浏览器按照指示生成相应的cookie。 然而纯粹的客户端脚本如JavaScript也可以生成cookie。而cookie的使用是由浏览器按照一定的原则在后台自动发送给服务器的。 浏览器检查所有存储的cookie,如果某个cookie所声明的作用范围大于等于将要请求的资源所在的位置, 则把该cookie附在请求资源的HTTP请求头上发送给服务器。 ``` ``` cookie的内容主要包括:名字,值,过期时间,路径和域。路径与域一起构成cookie的作用范围。 若不设置过期时间,则表示这个cookie的生命期为浏览器会话期间,关闭浏览器窗口,cookie就消失。 这种生命期为浏览器会话期的cookie被称为会话cookie。会话cookie一般不存储在硬盘上而是保存在内存里,当然这种行为并不是规范规定的。 若设置了过期时间,浏览器就会把cookie保存到硬盘上,关闭后再次打开浏览器,这些cookie仍然有效直到超过设定的过期时间。 存储在硬盘上的cookie可以在不同的浏览器进程间共享,比如两个IE窗口。而对于保存在内存里的cookie,不同的浏览器有不同的处理方式。 ``` #### session机制 ``` 而session机制采用的是一种在服务器端保持状态的解决方案。同时我们也看到,由于采用服务器端保持状态的方案在客户端也需要保存一个标识, 所以session机制可能需要借助于cookie机制来达到保存标识的目的。而session提供了方便管理全局变量的方式 。 ``` ``` session是针对每一个用户的,变量的值保存在服务器上,用一个sessionID来区分是哪个用户session变量, 这个值是通过用户的浏览器在访问的时候返回给服务器,当客户禁用cookie时,这个值也可能设置为由get来返回给服务器。 ``` ``` 就安全性来说:当你访问一个使用session 的站点,同时在自己机子上建立一个cookie,建议在服务器端的session机制更安全些, 因为它不会任意读取客户存储的信息。 session机制是一种服务器端的机制,服务器使用一种类似于散列表的结构(也可能就是使用散列表)来保存信息。 ``` ``` 当程序需要为某个客户端的请求创建一个session时,服务器首先检查这个客户端的请求里是否已包含了一个session标识(称为session id), 如果已包含则说明以前已经为此客户端创建过session,服务器就按照session id把这个session检索出来使用(检索不到,会新建一个), 如果客户端请求不包含session id,则为此客户端创建一个session并且生成一个与此session相关联的session id, session id的值应该是一个既不会重复,又不容易被找到规律以仿造的字符串,这个session id将被在本次响应中返回给客户端保存。 保存这个session id的方式可以采用cookie,这样在交互过程中浏览器可以自动的按照规则把这个标识发挥给服务器。 一般这个cookie的名字都是类似于SEEESIONID。但cookie可以被人为的禁止,则必须有其他机制以便在cookie被禁止时仍然能够把 session id传递回服务器。 经常被使用的一种技术叫做URL重写,就是把session id直接附加在URL路径的后面。还有一种技术叫做表单隐藏字段。 就是服务器会自动修改表单,添加一个隐藏字段,以便在表单提交时能够把session id传递回服务器。 ``` Cookie与Session都能够进行会话跟踪,但是完成的原理不太一样。普通状况下二者均能够满足需求,但有时分不能够运用Cookie, 有时分不能够运用Session。下面经过比拟阐明二者的特性以及适用的场所。 ``` 1、存取方式的不同 Cookie中只能保管ASCII字符串,假如需求存取Unicode字符或者二进制数据,需求先进行编码。Cookie中也不能直接存取Java对象。 若要存储略微复杂的信息,运用Cookie是比拟艰难的。 而Session中能够存取任何类型的数据,包括而不限于String、Integer、List、Map等。Session中也能够直接保管Java Bean乃至任何Java类, 对象等,运用起来十分便当。能够把Session看做是一个Java容器类。 2、隐私策略的不同 Cookie存储在客户端阅读器中,对客户端是可见的,客户端的一些程序可能会窥探、复制以至修正Cookie中的内容。 而Session存储在服务器上,对客户端是透明的,不存在敏感信息泄露的风险。 假如选用Cookie,比较好的方法是,敏感的信息如账号密码等尽量不要写到Cookie中。最好是像Google、Baidu那样将Cookie信息加密, 提交到服务器后再进行解密,保证Cookie中的信息只要本人能读得懂。而假如选择Session就省事多了,反正是放在服务器上, Session里任何隐私都能够有效的保护。 3、有效期上的不同 使用过Google的人都晓得,假如登录过Google,则Google的登录信息长期有效。用户不用每次访问都重新登录, Google会持久地记载该用户的登录信息。要到达这种效果,运用Cookie会是比较好的选择。只需要设置Cookie的过期时间属性为一个很大很大的数字。 由于Session依赖于名为JSESSIONID的Cookie,而Cookie JSESSIONID的过期时间默许为–1,只需关闭了阅读器该Session就会失效, 因而Session不能完成信息永世有效的效果。运用URL地址重写也不能完成。 而且假如设置Session的超时时间过长,服务器累计的Session就会越多,越容易招致内存溢出。 4、服务器压力的不同 Session是保管在服务器端的,每个用户都会产生一个Session。假如并发访问的用户十分多,会产生十分多的Session,耗费大量的内存。 因而像Google、Baidu、Sina这样并发访问量极高的网站,是不太可能运用Session来追踪客户会话的。 而Cookie保管在客户端,不占用服务器资源。假如并发阅读的用户十分多,Cookie是很好的选择。 关于Google、Baidu、Sina来说,Cookie或许是唯一的选择。 5、浏览器支持的不同 Cookie是需要客户端浏览器支持的。假如客户端禁用了Cookie,或者不支持Cookie,则会话跟踪会失效。 关于WAP上的应用,常规的Cookie就派不上用场了。 假如客户端浏览器不支持Cookie,需要运用Session以及URL地址重写。需要注意的是一切的用到Session程序的URL都要进行URL地址重写, 否则Session会话跟踪还会失效。关于WAP应用来说,Session+URL地址重写或许是它唯一的选择。 假如客户端支持Cookie,则Cookie既能够设为本浏览器窗口以及子窗口内有效(把过期时间设为–1), 也能够设为一切阅读器窗口内有效(把过期时间设为某个大于0的整数)。但Session只能在本阅读器窗口以及其子窗口内有效。 假如两个浏览器窗口互不相干,它们将运用两个不同的Session。(IE8下不同窗口Session相干) 6、跨域支持上的不同 Cookie支持跨域名访问,例如将domain属性设置为“.biaodianfu.com”,则以“.biaodianfu.com”为后缀的一切域名均能够访问该Cookie。 跨域名Cookie如今被普遍用在网络中,例如Google、Baidu、Sina等。而Session则不会支持跨域名访问。Session仅在他所在的域名内有效。 仅运用Cookie或者仅运用Session可能完成不了理想的效果。这时应该尝试一下同时运用Cookie与Session。 Cookie与Session的搭配运用在实践项目中会完成很多意想不到的效果。 ```<file_sep>/css学习笔记/00-README.md #### 系统学习,打好地基!!! 1. 《精通css》 2. 《css权威指南》<file_sep>/前端知识点总结/03-javascript/09-02-跨域.md #### 1. 跨域资源共享 CORS 对于web开发来讲,由于浏览器的同源策略,我们需要经常使用一些hack的方法去跨域获取资源,但是hack的方法总归是hack。 直到W3C出了一个标准-CORS-"跨域资源共享"(Cross-origin resource sharing)。 它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。 首先来说 CORS 需要浏览器和服务端同时支持的,对于兼容性来说主要是ie10+,其它现代浏览器都是支持的。 使用 CORS 跨域的时候其实和普通的 ajax 过程是一样的,只是浏览器在发现这是一个跨域请求的时候会自动帮我们处理一些事, 比如验证等等,所以说只要服务端提供支持,前端是不需要做额外的事情的。 两种请求 CORS 的请求分两种,这也是浏览器为了安全做的一些处理,不同情况下浏览器执行的操作也是不一样的,主要分为两种请求, 当然这一切我们是不需要做额外处理的,浏览器会自动处理的。 ``` 1. 简单请求(simple request) 只要同时满足以下两大条件,就属于简单请求。 条件 1) 请求方法是以下三种方法中的一个: HEAD GET POST 2)HTTP的头信息不超出以下几种字段: Accept Accept-Language Content-Language Last-Event-ID Content-Type:只限于三个值application/x-www-form-urlencoded、multipart/form-data、text/plain 过程 对于简单的跨域请求,浏览器会自动在请求的头信息加上 Origin 字段,表示本次请求来自哪个源(协议 + 域名 + 端口), 服务端会获取到这个值,然后判断是否同意这次请求并返回。 // 请求 GET /cors HTTP/1.1 Origin: http://api.qiutc.me Host: api.alice.com Accept-Language: en-US Connection: keep-alive User-Agent: Mozilla/5.0... 1.服务端允许 如果服务端许可本次请求,就会在返回的头信息多出几个字段: // 返回 Access-Control-Allow-Origin: http://api.qiutc.me Access-Control-Allow-Credentials: true Access-Control-Expose-Headers: Info Content-Type: text/html; charset=utf-8 这三个带有 Access-Control 开头的字段分别表示: Access-Control-Allow-Origin 必须。它的值是请求时Origin字段的值或者 *,表示接受任意域名的请求。 Access-Control-Allow-Credentials; 可选。它的值是一个布尔值,表示是否允许发送Cookie。默认情况下,Cookie不包括在CORS请求之中。 设为true,即表示服务器明确许可,Cookie可以包含在请求中,一起发给服务器。 再需要发送cookie的时候还需要注意要在AJAX请求中打开withCredentials属性: var xhr = new XMLHttpRequest(); xhr.withCredentials = true; 需要注意的是,如果要发送Cookie,Access-Control-Allow-Origin就不能设为*,必须指定明确的、与请求网页一致的域名。 同时,Cookie依然遵循同源政策,只有用服务器域名设置的Cookie才会上传,其他域名的Cookie并不会上传, 且原网页代码中的document.cookie也无法读取服务器域名下的Cookie。 Access-Control-Expose-Headers 可选。CORS请求时,XMLHttpRequest对象的getResponseHeader()方法只能拿到6个基本字段: Cache-Control、 Content-Language、 Content-Type、 Expires、 Last-Modified、 Pragma。如果想拿到其他字段,就必须在Access-Control-Expose-Headers里面指定。 上面的例子指定,getResponseHeader('Info')可以返回Info字段的值。 2.服务端拒绝 当然我们为了防止接口被乱调用,需要限制源,对于不允许的源,服务端还是会返回一个正常的HTTP回应, 但是不会带上 Access-Control-Allow-Origin 字段,浏览器发现这个跨域请求的返回头信息没有该字段, 就会抛出一个错误,会被 XMLHttpRequest 的 onerror 回调捕获到。 这种错误无法通过 HTTP 状态码判断,因为回应的状态码有可能是200 2.非简单请求 条件 出了简单请求以外的CORS请求。 非简单请求是那种对服务器有特殊要求的请求,比如请求方法是PUT或DELETE,或者Content-Type字段的类型是application/json。 过程 1)预检请求 非简单请求的CORS请求,会在正式通信之前,增加一次HTTP查询请求,称为"预检"请求(preflight)。 浏览器先询问服务器,当前网页所在的域名是否在服务器的许可名单之中,以及可以使用哪些HTTP动词和头信息字段。 只有得到肯定答复,浏览器才会发出正式的XMLHttpRequest请求,否则就报错。 预检请求的发送请求: OPTIONS /cors HTTP/1.1 Origin: http://api.qiutc.me Access-Control-Request-Method: PUT Access-Control-Request-Headers: X-Custom-Header Host: api.qiutc.com Accept-Language: en-US Connection: keep-alive User-Agent: Mozilla/5.0... "预检"请求用的请求方法是OPTIONS,表示这个请求是用来询问的。头信息里面,关键字段是Origin,表示请求来自哪个源。 除了Origin字段,"预检"请求的头信息包括两个特殊字段。 Access-Control-Request-Method 该字段是必须的,用来列出浏览器的CORS请求会用到哪些HTTP方法,上例是PUT。 Access-Control-Request-Headers 该字段是一个逗号分隔的字符串,指定浏览器CORS请求会额外发送的头信息字段,上例是X-Custom-Header。 预检请求的返回: HTTP/1.1 200 OK Date: Mon, 01 Dec 2008 01:15:39 GMT Server: Apache/2.0.61 (Unix) Access-Control-Allow-Origin: http://api.qiutc.me Access-Control-Allow-Methods: GET, POST, PUT Access-Control-Allow-Headers: X-Custom-Header Content-Type: text/html; charset=utf-8 Content-Encoding: gzip Content-Length: 0 Keep-Alive: timeout=2, max=100 Connection: Keep-Alive Content-Type: text/plain Access-Control-Allow-Methods 必需,它的值是逗号分隔的一个字符串,表明服务器支持的所有跨域请求的方法。注意,返回的是所有支持的方法, 而不单是浏览器请求的那个方法。这是为了避免多次"预检"请求。 Access-Control-Allow-Headers 如果浏览器请求包括Access-Control-Request-Headers字段,则Access-Control-Allow-Headers字段是必需的。 它也是一个逗号分隔的字符串,表明服务器支持的所有头信息字段,不限于浏览器在"预检"中请求的字段。 Access-Control-Max-Age 该字段可选,用来指定本次预检请求的有效期,单位为秒。上面结果中,有效期是20天(1728000秒), 即允许缓存该条回应1728000秒(即20天),在此期间,不用发出另一条预检请求。 2)浏览器的正常请求和回应 一旦服务器通过了"预检"请求,以后每次浏览器正常的CORS请求,就都跟简单请求一样,会有一个Origin头信息字段。 服务器的回应,也都会有一个Access-Control-Allow-Origin头信息字段。 参考:[《跨域资源共享 CORS 详解》]()http://www.ruanyifeng.com/blog/2016/04/cors.html ) 阮大神的文章,复制粘贴了不少。 ``` #### 2. jsonp jsonp = json + padding 其实对于常用性来说,jsonp应该是使用最经常的一种跨域方式了,他不受浏览器兼容性的限制。但是他也有他的局限性,`只能发送 GET 请求`, 需要服务端和前端规定好,写法丑陋。 它的原理在于浏览器请求 script 资源不受同源策略限制,并且请求到 script 资源后立即执行。 主要做法是这样的: ``` 在浏览器端: 首先全局注册一个callback回调函数,记住这个函数名字(比如:resolveJson),这个函数接受一个参数,参数是期望的到的服务端返回数据, 函数的具体内容是处理这个数据。然后动态生成一个 script 标签,src 为:请求资源的地址+获取函数的字段名+回调函数名称, 这里的获取函数的字段名是要和服务端约定好的,是为了让服务端拿到回调函数名称。(如:www.qiute.com?callbackName=resolveJson)。 function resolveJosn(result) { console.log(result.name); } var jsonpScript= document.createElement("script"); jsonpScript.type = "text/javascript"; jsonpScript.src = "http://www.qiute.com?callbackName=resolveJson"; document.getElementsByTagName("head")[0].appendChild(jsonpScript); 服务端 在接受到浏览器端 script 的请求之后,从url的query的callbackName获取到回调函数的名字,例子中是resolveJson。 然后动态生成一段javascript片段去给这个函数传入参数执行这个函数。比如: resolveJson({name: 'qiutc'}); 执行 服务端返回这个 script 之后,浏览器端获取到 script 资源,然后会立即执行这个 javascript,也就是上面那个片段。 这样就能根据之前写好的回调函数处理这些数据了。 在一些第三方库往往都会封装jsonp的操作,比如 jQuery 的$.getJSON。 ``` #### 3. document.domain 一个页面框架(iframe/frame)之间(父子或同辈),是能够获取到彼此的window对象的, 但是这个 window 不能拿到方法和属性(尼玛这有什么用,甩脸)。 ``` // 当前页面域名 http://blog.qiutc.me/a.html <script> function onLoad() { var iframe =document.getElementById('iframe'); var iframeWindow = iframe.contentWindow; // 这里可以获取 iframe 里面 window 对象,但是几乎没用 var doc = iframeWindow.document; // 获取不到 } </script> <iframe src="http://www.qiutc.me/b.html" onload="onLoad()"</iframe> 这个时候,document.domain 就可以派上用场了,我们只要把 http://blog.qiutc.me/a.html 和 http://www.qiutc.me/b.html 这两个页面的 document.domain 都设成相同的域名就可以了。 前提条件:这两个域名必须属于同一个基础域名!而且所用的协议,端口都要一致。 但要注意的是,document.domain 的设置是有限制的,我们只能把 document.domain 设置成自身或更高一级的父域,且主域必须相同。 例如:a.b.example.com 中某个文档的 document.domain 可以设成a.b.example.com、b.example.com 、example.com中的任意一个, 但是不可以设成 c.a.b.example.com,因为这是当前域的子域,也不可以设成baidu.com,因为主域已经不相同了。 这样我们就可以通过js访问到iframe中的各种属性和对象了。 // 主页面:http://blog.qiutc.me/a.html <script> document.domain = 'qiutc.me'; function onLoad() { var iframe =document.getElementById('iframe'); var iframeWindow = iframe.contentWindow; // 这里可以获取 iframe 里面 window 对象并且能得到方法和属性 var doc = iframeWindow.document; // 获取到 } </script> <iframe src="http://www.qiutc.me/b.html" onload="onLoad()"</iframe> // iframe 里面的页面 <script> document.domain = 'qiutc.me'; </script> ``` #### 4. window.name window对象有个name属性,该属性有个特征:即在一个窗口(window)的生命周期内,窗口载入的所有的页面都是共享一个 window.name 的, 每个页面对 window.name 都有读写的权限,window.name 是持久存在一个窗口载入过的所有页面中的,并不会因新页面的载入而进行重置。 比如有一个www.qiutc.me/a.html页面,需要通过a.html页面里的js来获取另一个位于不同域上的页面www.qiutc.com/data.html里的数据。 data.html页面里的代码很简单,就是给当前的window.name设置一个a.html页面想要得到的数据值。data.html里的代码: ``` <script> window.name = '我是被期望得到的数据'; </script> 那么在 a.html 页面中,我们怎么把 data.html 页面载入进来呢?显然我们不能直接在 a.html 页面中通过改变 window.location 来载入data.html页面(这简直扯蛋)因为我们想要即使 a.html 页面不跳转也能得到 data.html 里的数据。 答案就是在 a.html 页面中使用一个隐藏的 iframe 来充当一个中间人角色,由 iframe 去获取 data.html 的数据, 然后 a.html 再去得到 iframe 获取到的数据。 充当中间人的 iframe 想要获取到data.html的通过window.name设置的数据,只需要把这个iframe的src设为 www.qiutc.com/data.html就行了。然后a.html想要得到iframe所获取到的数据,也就是想要得到iframe的window.name的值, 还必须把这个iframe的src设成跟a.html页面同一个域才行,不然根据前面讲的同源策略, a.html是不能访问到iframe里的window.name属性的。这就是整个跨域过程。 // a.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script> function getData() { var iframe =document.getElementById('iframe'); iframe.onload = function() { var data = iframe.contentWindow.name; // 得到 } iframe.src = 'b.html'; // 这里b和a同源 } </script> </head> <body> <iframe src="http://www.qiutc.com/data.html" style="display:none" onload="getData()"</iframe> </body> </html> ``` #### 5. HTML5中新引进的window.postMessage window.postMessage(message, targetOrigin) 方法是html5新引进的特性,可以使用它来向其它的window对象发送消息, 无论这个window对象是属于同源或不同源。 ``` 调用postMessage方法的window对象是指要接收消息的那一个window对象,该方法的第一个参数message为要发送的消息, 类型只能为字符串;第二个参数targetOrigin用来限定接收消息的那个window对象所在的域,如果不想限定域,可以使用通配符 * 。 需要接收消息的window对象,可是通过监听自身的message事件来获取传过来的消息,消息内容储存在该事件对象的data属性中。 上面所说的向其他window对象发送消息,其实就是指一个页面有几个框架的那种情况,因为每一个框架都有一个window对象。 在讨论第种方法的时候,我们说过,不同域的框架间是可以获取到对方的window对象的,虽然没什么用, 但是有一个方法是可用的-window.postMessage。下面看一个简单的示例,有两个页面: // 主页面 blog.qiutc.com <script> function onLoad() { var iframe =document.getElementById('iframe'); var iframeWindow = iframe.contentWindow; iframeWindow.postMessage("I'm message from main page."); } </script> <iframe src="http://www.qiutc.me/b.html" onload="onLoad()"</iframe> // b 页面 <script> window.onmessage = function(e) { e = e || event; console.log(e.data); } </script> ``` #### 6.CSST (CSS Text Transformation) 一种用 CSS 跨域传输文本的方案。 优点:相比 JSONP 更为安全,不需要执行跨站脚本。 缺点:没有 JSONP 适配广,CSST 依赖支持 CSS3 的浏览器。 原理:通过读取 CSS3 content 属性获取传送内容。 具体可以参考:CSST (CSS Text Transformation) #### 7.利用flash flash 嘛,这个东西注定灭亡,不想说了。。。<file_sep>/README.md # 阅读前端书籍的过程中,总结笔记。 ## 目录 #### 1.前端常见的知识点总结 #### 2.javascript数据结构与算法 #### 3.javascript设计模式 #### 4.Javascript函数式编程 #### 5.MongoDB笔记 #### 6.其他 - git基本使用指南 - MarkDown语法指南 - 理解Redux设计理念<file_sep>/数据结构与算法javascript实现/01-栈的应用/05-两个栈实现队列.js var Stack = require('../data-structures/02_Stack'); /*** * 利用2个栈实现一个队列, 只需要实现先进先出的功能 * @constructor */ var Queue = function () { this.stack1 = new Stack(); this.stack2 = new Stack(); } Queue.prototype.enqueue = function (ele) { this.stack1.push(ele); //入队操作都压入栈1 } Queue.prototype.dequeue = function () { if (this.stack2.length()) { //栈2不空,直接pop return this.stack2.pop(); } else { //若第二个栈不空,则将第一个栈中的所有元素出栈并压入栈2,并pop一次 while (this.stack1.length()) { this.stack2.push(this.stack1.pop()); } return this.stack2.pop(); } } var q = new Queue(); q.enqueue(1); q.enqueue(2); q.enqueue(3); console.log(q.dequeue()); console.log(q.dequeue()); console.log(q.stack1); console.log(q.stack2); console.log('----------------------------'); q.enqueue(4); q.enqueue(5); console.log(q.dequeue()); console.log(q.stack1); console.log(q.stack2); console.log('----------------------------'); console.log(q.dequeue()); console.log(q.dequeue()); console.log(q.stack1); console.log(q.stack2); console.log('----------------------------'); <file_sep>/前端知识点总结/03-javascript/09-01-跨域方式.md #### 如何解决跨域问题 #### 1.JSONP: `原理是:动态插入script标签,通过script标签引入一个js文件,这个js文件载入成功后会执行我们在url参数中指定的函数,并且会把我们需要的json数据作为参数传入。` ``` 由于同源策略的限制,XmlHttpRequest只允许请求当前源(域名、协议、端口)的资源,为了实现跨域请求,可以通过script标签实现跨域请求,然后在服务端输出JSON数据并执行回调函数,从而解决了跨域的数据请求。 优点是兼容性好,简单易用,支持浏览器与服务器双向通信。缺点是只支持GET请求。 JSONP:json+padding(内填充),顾名思义,就是把JSON填充到一个盒子里 <script> function createJs(sUrl){ var oScript = document.createElement('script'); oScript.type = 'text/javascript'; oScript.src = sUrl; document.getElementsByTagName('head')[0].appendChild(oScript); } createJs('jsonp.js'); box({ 'name': 'test' }); function box(json){ alert(json.name); } </script> ``` #### 2.CORS ``` 服务器端对于CORS的支持,主要就是通过设置Access-Control-Allow-Origin来进行的。 如果浏览器检测到相应的设置,就可以允许Ajax进行跨域的访问。 ``` #### 3.通过修改document.domain来跨子域 ``` 将子域和主域的document.domain设为同一个主域.前提条件:这两个域名必须属于同一个基础域名!而且所用的协议,端口都要一致, 否则无法利用document.domain进行跨域,主域相同的使用document.domain ``` #### 4.使用window.name来进行跨域 ``` window对象有个name属性,该属性有个特征:即在一个窗口(window)的生命周期内,窗口载入的所有的页面都是共享一个window.name的, 每个页面对window.name都有读写的权限,window.name是持久存在一个窗口载入过的所有页面中的 ``` #### 5.使用HTML5中新引进的window.postMessage方法来跨域传送数据 #### 6.还有flash、在服务器上设置代理页面等跨域方式。 `window.name的方法既不复杂,也能兼容到几乎所有浏览器,这真是极好的一种跨域方法。` <file_sep>/前端知识点总结/03-javascript/08-Ajax工作原理.md #### Ajax工作原理 ``` 1.使用CSS和XHTML来表示。 2. 使用DOM模型来交互和动态显示。 3.使用XMLHttpRequest来和服务器进行异步通信。 4.使用javascript来绑定和调用。 ``` #### ajax原理和XmlHttpRequest对象 ``` Ajax的原理简单来说通过XmlHttpRequest对象来向服务器发异步请求,从服务器获得数据,然后用javascript来操作DOM而更新页面。 这其中最关键的一步就是从服务器获得请求数据。要清楚这个过程和原理,我们必须对 XMLHttpRequest有所了解。 XMLHttpRequest是ajax的核心机制,它是在IE5中首先引入的,是一种支持异步请求的技术。简单的说,也就是javascript可以及时向服务器提出请求和处理响应, 而不阻塞用户。达到无刷新的效果。 ```  首先,我们先来看看XMLHttpRequest这个对象的属性。 ```   onreadystatechange 每次状态改变所触发事件的事件处理程序。   responseText 从服务器进程返回数据的字符串形式。   responseXML 从服务器进程返回的DOM兼容的文档数据对象。   status 从服务器返回的数字代码,比如常见的404(未找到)和200(已就绪)   status Text 伴随状态码的字符串信息   readyState 对象状态值     0 (未初始化) 对象已建立,但是尚未初始化(尚未调用open方法)     1 (初始化) 对象已建立,尚未调用send方法     2 (发送数据) send方法已调用,但是当前的状态及http头未知     3 (数据传送中) 已接收部分数据,因为响应及http头不全,这时通过responseBody和responseText获取部分数据会出现错误,     4 (完成) 数据接收完毕,此时可以通过通过responseXml和responseText获取完整的回应数据 ``` 但是,由于各浏览器之间存在差异,所以创建一个XMLHttpRequest对象可能需要不同的方法。这个差异主要体现在IE和其它浏览器之间。 下面是一个比较标准的创建XMLHttpRequest对象的方法。 ``` function CreateXmlHttp() { //非IE浏览器创建XmlHttpRequest对象 if (window.XmlHttpRequest) { xmlhttp = new XmlHttpRequest(); } //IE浏览器创建XmlHttpRequest对象 if (window.ActiveXObject) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("msxml2.XMLHTTP"); } catch (ex) { } } } } ``` ``` function ajax() { var data = document.getElementById("username").value; CreateXmlHttp(); if (!xmlhttp) { alert("创建xmlhttp对象异常!"); return false; } xmlhttp.open("POST", url, false); xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4) { document.getElementById("user1").innerHTML = "数据正在加载..."; if (xmlhttp.status == 200) { document.write(xmlhttp.responseText); } } } xmlhttp.send(); } ``` 如上所示,函数首先检查XMLHttpRequest的整体状态并且保证它已经完成(readyStatus=4),即数据已经发送完毕。 然后根据服务器的设定询问请求状态,如果一切已经就绪(status=200),那么就执行下面需要的操作。 对于XmlHttpRequest的两个方法,open和send,其中: open方法指定了: a、向服务器提交数据的类型,即post还是get。 b、请求的url地址和传递的参数。 c、传输方式,false为同步,true为异步。默认为true。如果是异步通信方式(true),客户机就不等待服务器的响应; 如果是同步方式(false),客户机就要等到服务器返回消息后才去执行其他操作。我们需要根据实际需要来指定同步方式,在某些页面中, 可能会发出多个请求,甚至是有组织有计划有队形大规模的高强度的request,而后一个是会覆盖前一个的,这个时候当然要指定同步方式。 Send方法用来发送请求。 ``` 知道了XMLHttpRequest的工作流程,我们可以看出,XMLHttpRequest是完全用来向服务器发出一个请求的,它的作用也局限于此, 但它的作用是整个ajax实现的关键,因为ajax无非是两个过程,发出请求和响应请求。并且它完全是一种客户端的技术。 而XMLHttpRequest正是处理了服务器端和客户端通信的问题所以才会如此的重要。 现在,我们对ajax的原理大概可以有一个了解了。我们可以把服务器端看成一个数据接口,它返回的是一个纯文本流,当然,这个文本流可以是XML格式, 可以是Html,可以是Javascript代码,也可以只是一个字符串。 这时候,XMLHttpRequest向服务器端请求这个页面,服务器端将文本的结果写入页面,这和普通的web开发流程是一样的,不同的是, 客户端在异步获取这个结果后,不是直接显示在页面,而是先由javascript来处理,然后再显示在页面。至于现在流行的很多ajax控件, 比如magicajax等,可以返回DataSet等其它数据类型,只是将这个过程封装了的结果,本质上他们并没有什么太大的区别。 ``` #### ajax的优点 ``` Ajax的给我们带来的好处大家基本上都深有体会,在这里我只简单的讲几点: 1、最大的一点是页面无刷新,在页面内与服务器通信,给用户的体验非常好。   2、使用异步方式与服务器通信,不需要打断用户的操作,具有更加迅速的响应能力。   3、可以把以前一些服务器负担的工作转嫁到客户端,利用客户端闲置的能力来处理,减轻服务器和带宽的负担,节约空间和宽带租用成本。并且减轻服务器的负担,ajax的原则是“按需取数据”,可以最大程度的减少冗余请求,和响应对服务器造成的负担。 4、基于标准化的并被广泛支持的技术,不需要下载插件或者小程序。 ``` #### ajax的缺点 ```   下面所阐述的ajax的缺陷都是它先天所产生的。  1、ajax干掉了back按钮,即对浏览器后退机制的破坏。后退按钮是一个标准的web站点的重要功能,但是它没法和js进行很好的合作。 这是ajax所带来的一个比较严重的问题,因为用户往往是希望能够通过后退来取消前一次操作的。那么对于这个问题有没有办法? 答案是肯定的,用过Gmail的知道,Gmail下面采用的ajax技术解决了这个问题,在Gmail下面是可以后退的,但是,它也并不能改变ajax的机制, 它只是采用的一个比较笨但是有效的办法,即用户单击后退按钮访问历史记录时,通过创建或使用一个隐藏的IFRAME来重现页面上的变更。 (例如,当用户在Google Maps中单击后退时,它在一个隐藏的IFRAME中进行搜索,然后将搜索结果反映到Ajax元素上,以便将应用程序状态恢复到当时的状态。) 但是,虽然说这个问题是可以解决的,但是它所带来的开发成本是非常高的,和ajax框架所要求的快速开发是相背离的。这是ajax所带来的一个非常严重的问题。 2、安全问题。技术同时也对IT企业带来了新的安全威胁,ajax技术就如同对企业数据建立了一个直接通道。这使得开发者在不经意间会暴露比以前更多的数据 和服务器逻辑。ajax的逻辑可以对客户端的安全扫描技术隐藏起来,允许黑客从远端服务器上建立新的攻击。 还有ajax也难以避免一些已知的安全弱点,诸如跨站点脚步攻击、SQL注入攻击和基于credentials的安全漏洞等。 3、对搜索引擎的支持比较弱。 4、破坏了程序的异常机制。至少从目前看来,像ajax.dll,ajaxpro.dll这些ajax框架是会破坏程序的异常机制的。 5、另外,像其他方面的一些问题,比如说违背了url和资源定位的初衷。 例如,我给你一个url地址,如果采用了ajax技术,也许你在该url地址下面看到的和我在这个url地址下看到的内容是不同的。这个和资源定位的初衷是相背离的。 6、一些手持设备(如手机、PDA等)现在还不能很好的支持ajax,比如说我们在手机的浏览器上打开采用ajax技术的网站时, 它目前是不支持的,当然,这个问题和我们没太多关系。 ``` <file_sep>/前端知识点总结/01-html/02-浏览器的标准模式与怪异模式区别.md #### 要想写出跨浏览器的CSS,必须知道浏览器解析CSS的两种模式:标准模式(strict mode)和怪异模式(quirks mode)。 ``` 所谓的标准模式是指,浏览器按W3C标准解析执行代码; 怪异模式则是使用浏览器自己的方式解析执行代码,因为不同浏览器解析执行的方式不一样,所以我们称之为怪异模式。 浏览器解析时到底使用标准模式还是怪异模式,与你网页中的DTD声明直接相关,DTD声明定义了标准文档的类型(标准模式解析) 文档类型,会使浏览器使用相应的方式加载网页并显示,忽略DTD声明,将使网页进入怪异模式(quirks mode)。 ``` 如果你的网页代码不含有任何声明,那么浏览器就会采用怪异模式解析,便是如果你的网页代码含有DTD声明,浏览器就会按你所声明的标准解析。 ``` <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">   上面的代码,浏览器会按HTML 4.01的标准进行解析。 ``` #### 到底标准模式和怪异模式有什么不同呢? ``` 标准模式中IE6不认识!important声明,IE7、IE8、Firefox、Chrome等浏览器认识; 而在怪异模式中,IE6/7/8都不认识!important声明,这只是区别的一种,还有很多其它区别。 所以,要想写出跨浏览器CSS,你最好采用标准模式。 ``` 到底都有哪些声明呢?哪种声明更好呢?我们建议你使用XHTML 1.0最严格模式,从一开始我们就应该严格的要求自己,具体声明如下: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> ``` 如果你接手的是一个遗留网页,最初并没有DTD声明,并且使用了很多在XHTML中已经废除的标签,那么建议你使用XHTML兼容模式,声明如下: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ```<file_sep>/前端知识点总结/02-css/01-什么是css-reset.md #### 什么是CSS Reset。 ``` HTML标签在浏览器中都有默认的样式,例如p标签有上下边距,strong标签有字体加粗样式等。 不同浏览器的默认样式之间存在差别,例如ul默认带有缩进样式,在IE下,它的缩进是由margin实现的, 而在Firefox下却是由padding实现的。开发时浏览器的默认样式可能会给我们带来多浏览器兼容性问题, 影响开发效率。现在很流行的解决方法是一开始就将浏览器的默认样式全部覆盖掉,这就是CSS reset。 ``` ``` 部分CSS reset内容如下 html {color:#000;background:#FFF;}t5 body,div,dl,dt,dd,ul,ol,li, h1,h2,h3,h4,h5,h6, pre,code,form,fieldset,legend, input,textarea,p,blockquote,th,td{margin:0;padding:0;} table {border-collapse:collapse;border-spacing:0;} fieldset,img {border:0;} address,caption,cite,code,dfn,em,strong,th,var {font-style:normal;font-weight:normal;} li {list-style:none;} caption,th {text-align:left;} h1,h2,h3,h4,h5,h6 {font-size:100%;font-weight:normal;} q:before,q:after {content:'';} abbr,acronym {border:0;font-variant:normal;} sup {vertical-align:text-top;} sub {vertical-align:text-bottom;} input,textarea,select {font-family:inherit;font-size:inherit;font-weight:inherit;} input,textarea,select {*font-size:100%;} legend {color:#000;} ```<file_sep>/数据结构与算法javascript实现/00-需要非常熟练掌握的数据结构.md #### 需要熟练掌握的数据结构和算法 1. 链表、栈、队列、树和哈希表以及操作,链表的插入删除! 树的递归遍历和循环遍历! 2. 查找:重点是二分查找! 3. 各种排序算法及其复杂度: 重点是归并排序和快排! 4. 动态规划! <file_sep>/数据结构与算法javascript实现/00-排序算法/01-冒泡排序.js /*** * 冒泡排序: 最慢的排序算法,基本上用不着!!! * */ var generateTestData = require('./00-TestDataGenerator'); var bubbleSort = function (data) { var l = data.length; for (var i = 0; i <= l - 1; i++) { //外层循环表示要进行length趟排序 //内层循环表示在每一趟中两两交换进行排序 for (var j = 1; j <= l; j++) { if (data[j] < data[j - 1]) { var tmp = data[j]; data[j] = data[j - 1]; data[j - 1] = tmp; } } } return data; } var data = generateTestData(20000); var start = new Date().getTime(); console.log('start sorting....'); var result = bubbleSort(data); var end = new Date().getTime(); console.log('耗时: ' + (end - start) + ' ms'); // console.log(result);
8043e3cfd40d8bc3e3f77b54992b90b2c3e16a95
[ "Markdown", "JavaScript" ]
14
Markdown
imust98/FE-Learning
2794625d67c1c42a02a5e0a937796b8f113d16d1
071cbc3536d4f1d5c6fc418ee1403ceeba40364a
refs/heads/master
<repo_name>claireve/reveclair<file_sep>/modules/method.php <?php //content modules should not be accessed directly through a URL since they would then lack the HTML Template //we'll see if a constant is defined (which should be included first thing in the index file, prior to including this page) if (!defined('BASE_URL')) { require('../includes/config.inc.php'); $url = BASE_URL . 'method.php'; header("Location:$url"); exit; } ?> <div class="path-container"> <div class="row"> <div class="large-12 columns"> <h1>Nos méthodes</h1> </div> </div> <div class="row path-item"> <div class="large-7 push-5 columns"> <div class="circle circle-left "></div> </div> <div class="large-5 pull-7 columns path-text left"> <h3>Ecoute de vos besoins et attentes</h3> <p>Notre petite structure nous permet d'être très réactif. Nous ne travaillons que sur un projet à la fois. Ce choix nous laisse la possibilité d'être plus attentif à la qualité, de peaufiner les détails et de délivrer le produit rapidement.</p> </div> </div> <div class="row path-item"> <div class="large-7 columns"> <div class="circle circle-right right"></div> </div> <div class="large-5 columns path-text right"> <h3>Ebauche du projet et production rapide pour aucun malentendu</h3> <p>Nous suivons les principes AGILE pour le management de nos projets, cette méthode nous paraissant très cohérente et étant réputée extrêmement efficace. En quelques mots, cela consiste à une mise en production très rapide avec un feedback de votre part fréquent pour un développement en complète cohérence avec vos attentes. </p> </div> </div> <div class="row get-feedback path-item"> <div class="large-7 push-5 columns"> <div class="circle circle-left"></div> </div> <div class="large-5 pull-7 columns path-text left"> <h3>Tout au long du projet, rigueur et qualité du développement avec des tests fonctionnels</h3> <p>Nous aimons le travail bien fait, maintenable et facilement évolutif. Nous mettons un point d'orgue à un écrire du code propre, minimaliste, documenté et testé.</p> </div> </div> <div class="row land-job path-item"> <div class="large-7 columns"> <div class="circle circle-right right"></div> </div> <div class="large-5 columns path-text right"> <h3>Stratégie SEO, graphisme et livraison finale</h3> <p></p> </div> </div> <span class="line hide-for-small"></span> </div><file_sep>/modules/blog/list_category.php <?php // Script 9.8 - logout.php /* This is the logout page. It destroys the session information. */ // Define a page title and include the header: define('TITLE', 'Blog'); // use Michelf\Markdown; require_once 'ressources/php_markdown_lib_1.4.1/Michelf/Markdown.inc.php'; include(DB); ?> <div class="wrapper"> <div class="row"> <div class='large-9 columns aside'> <h4 class="page-title">Blog - <?php $q = "SELECT c.name, c.description, c.slug, c.id FROM Category c WHERE c.slug = '{$_GET['slug']}'"; if ($result= mysqli_query($dbc, $q)) { $r1 = mysqli_fetch_row($result); print $r1[0].'</h4>'; } ?><hr/> <?php echo '<p class="description">'.$r1[1].'</p><hr/>'; ?> <?php $query = "SELECT e.title, e.entry, e.entry_id, e.slug, e.isPublic, e.date_entered,c.name FROM entries e LEFT JOIN Category c ON e.category_id = c.id WHERE c.slug = '{$_GET['slug']}' ORDER BY e.date_entered DESC"; if ($r = mysqli_query($dbc, $query)) { while ($row = mysqli_fetch_array($r)) { $name = strtoupper($row['name']); //si l'user est connecte, il a acces a tous les posts sans restriction if (isset($_SESSION['valid_user'])) { $entry = \Michelf\Markdown::defaultTransform($row['entry']); $format = 'Y-m-d H:i:s'; $date_entry = date_create_from_format($format, $row['date_entered']); if (isset($row['name'])) echo "<div class='ribbon'><div class='ribbon-stitches-top'></div><strong class='ribbon-content'><h1>{$name}</h1></strong><div class='ribbon-stitches-bottom'></div></div>"; print " <div class='panel multiple-post'> <h1> <a href=\"/posts/{$row['slug']}\">{$row['title']}</a>"; print "</h1>".$date_entry->format('d/m/Y').$entry; if (isset($_SESSION['valid_user'])) { print "<a href=\"/index.php?p=edit_entry&id={$row['entry_id']}\">Edit</a> <a href=\"/index.php?p=delete_entry&id={$row['entry_id']}\">Delete</a></div>\n"; } } //sinon il n'a acces qu'aux posts publics else { if ($row['isPublic'] == 1){ $entry = \Michelf\Markdown::defaultTransform($row['entry']); $format = 'Y-m-d H:i:s'; $date_entry = date_create_from_format($format, $row['date_entered']); if (isset($row['name'])) echo "<div class='ribbon'><div class='ribbon-stitches-top'></div><strong class='ribbon-content'><h1>{$name}</h1></strong><div class='ribbon-stitches-bottom'></div></div>"; print "<div class='panel multiple-post'> <h3> <a href=\"/posts/{$row['slug']}\">{$row['title']}</a>"; if ($row['isPublic'] == 0) echo ' PRIVE'; print "</h3> {$entry}</div>\n"; } } } } else { // Query didn't run. print '<p style="color: red;"> Could not retrieve the data because:<br />' . mysql_error($dbc) . '.</p> <p>The query being run was: ' . $query . '</p>'; } // End of query IF. ?> </div> <div class="large-3 columns"> <?php include('templates/blog_sidenav.html'); ?> </div> </div> <div class="push"></div> </div> <script language="javascript"> $(document).ready(function() { $(this).attr("title", $(".page-title").text()); }); </script> <?php mysqli_close($dbc); ?><file_sep>/templates/header.php <?php ob_start(); header("Content-Type: text/html;charset=UTF-8"); include_once('includes/functions.php'); if (!isset($page_title)) $page_title = 'Reveclair';?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title><?php echo $page_title; ?> | Reveclair </title> <link rel="shortcut icon" type="image/x-icon" href="/ressources/images/favicon.ico" /> <link rel="stylesheet" href="/ressources/css/foundation.min.css"> <link rel="stylesheet" href="/ressources/css/foundation-icons.css"> <link href='http://fonts.googleapis.com/css?family=Pathway+Gothic+One|Marvel|Coda|Cookie|Wire+One|Rochester|Pompiere|Dosis|Roboto+Condensed|Roboto' rel='stylesheet' type='text/css'> <link href="/ressources/css/sh/shCore.css" rel="stylesheet" type="text/css" /> <link href="/ressources/css/sh/shCoreRDark.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="/ressources/css/main.css" type="text/css"> <link rel="stylesheet" href="/ressources/jquery-ui-1.11.2.custom/jquery-ui.min.css" type="text/css"> <link rel="stylesheet" href="/ressources/js/highlight/styles/zenburn.css"> <script src="/ressources/js/vendor/modernizr.js"></script> <script src="/ressources/js/vendor/jquery.js"></script> <script src="/ressources/js/foundation.min.js"></script> <script src="/ressources/ckeditor/ckeditor.js"></script> <script src="/ressources/jquery-ui-1.11.2.custom/jquery-ui.min.js"></script> <script src="/ressources/jquery-ui-1.11.2.custom/datepicker-fr.js"></script> <script src="/ressources/js/jquery-maskedinput.1.4.0.min.js"></script> <script src="/ressources/js/jquery.validate.min.js"></script> <script src="/ressources/js/highlight/highlight.pack.js"></script> <script>hljs.initHighlightingOnLoad();</script> </head> <body> <div class="sticky"> <nav class="top-bar" role="navigation" data-topbar data-options="sticky_on: large"> <ul class="title-area"> <li class="name"> <h1><a href="/index.php"><img style="height:30px;margin-right:10px;margin-bottom:4px;"src="/ressources/images/lr1.png" alt="Example" />REVECLAIR</a></h1> </li> <li class="toggle-topbar menu-icon"> <a href="#"><span>menu</span></a> </li> </ul> <section class="top-bar-section"> <?php $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];?> <ul class="left"> <li> <a <?php if (false !== strpos($url,'team')) { print "class='active'"; } ?> href="/team">Notre petite équipe</a> </li> <li> <a <?php if (false !== strpos($url,'method')) { print "class='active'"; } ?> href="/method">Nos méthodes</a> </li> <li> <a <?php if (false !== strpos($url,'work')) { print "class='active'"; } ?>href="/work">Notre travail</a> </li> <li><a href="/blog">Blog</a></li> <!-- if ( (is_administrator() && (basename($_SERVER['PHP_SELF']) != 'logout.php')) OR (isset($loggedin) && $loggedin) ) {print '<li> --> </ul> <!-- Right Nav Section --> <ul class="right"> <?php if (isset($_SESSION['valid_user'])): ?> <li class="has-dropdown"> <a href="#">Admin</a> <ul class="dropdown"> <li><a href="/index.php?p=add_category">Ajouter une catégorie</a></li> <li><a href="/index.php?p=add_entry">Ajouter un post</a></li> </ul> </li> <?php endif; ?> <li class="active"><a class="contact" href="/contact">Contactez-nous !</a></li> </ul> </section> </nav> </div><file_sep>/modules/contact.php <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $from = 'From: TangledDemo'; $to = '<EMAIL>'; $subject = 'Hello'; $company = $_POST['company']; $company_description = $_POST['company_description']; $human = $_POST['human']; $date_start = $_POST['date_start']; $date_stop = $_POST['date_stop']; $budget = $_POST['budget']; $body = "From: $name\n E-Mail: $email\n Projet:\n $message \n Entreprise:\n $company\n Description entreprise:\n $company_description \n Date début souhaitée:\n $date_start \n Date fin souhaitée:\n $date_stop \n Budget estimé:\n $budget"; if ($_POST['submit'] && $human == '4') { if (mail ($to, $subject, $body, $from)) { echo '<p class="success">Merci pour votre message. Vous recevrez une réponse de notre part rapidement.</p>'; } else { echo '<p>Something went wrong, go back and try again!</p>'; } } else if ($_POST['submit'] && $human != '4') { echo '<p>You answered the anti-spam question incorrectly!</p>'; } } ?> <div class="row"> <div class="large-9 columns panel"> <h3>Contactez-nous !</h3> <p>N'hésitez pas à nous contacter, que ce soit pour un appel à projet, une simple question ou une remarque, ça nous fait toujours plaisir.</p> <div class="section-container tabs" data-section> <section class="section"> <h5 class="title">Contactez Reveclair</h5> <div class="content" data-slug="panel1"> <form id="contactForm" method="post" target="index.php?p=contact" novalidate> <div class="row collapse"> <div class="large-2 columns"> <label class="inline">Votre nom <small>Requis</small></label> </div> <div class="large-10 columns"> <input required name="name" type="text" id="yourName"> </div> </div> <div class="row collapse"> <div class="large-2 columns"> <label class="inline"> Votre Email <small>Requis</small></label> </div> <div class="large-10 columns"> <input name="email" required type="email" id="yourEmail"> </div> </div> <div class="row collapse"> <div class="large-2 columns"> <label class="inline"> Votre entreprise</label> </div> <div class="large-10 columns"> <input type="text" name="company" id="yourCompany"> </div> </div> <label>Décrivez votre entreprise </label> <textarea name="company_description" ></textarea> <label>Décrivez le projet pour lequel vous nous contacter <small>Requis</small></label> <textarea name="message"></textarea> <div class="row collapse"> <div class="large-6 columns"> <label class="inline"> Quand voulez-vous commencer ?</label> </div> <div class="large-6 columns"> <input name="date_start" type="text" id="date_start"> </div> </div> <div class="row collapse"> <div class="large-6 columns"> <label class="inline"> Quand le projet doit être fini ?</label> </div> <div class="large-6 columns"> <input name="date_stop" type="text" id="date_stop"> </div> </div> <div class="row collapse"> <div class="large-6 columns"> <label class="inline"> Votre budget estimé</label> </div> <div class="large-5 columns"> <input id="budget" name="budget" type="text"> </div> <div class="small-1 columns"> <span class="postfix">€</span> </div> </div> <div class="row collapse"> <div class="large-2 columns"> <label>Somme de 2+2 ? (vérification anti-spam)</label> </div> <div class="large-10 columns"> <input name="human" placeholder="Résultat en chiffre"> </div> </div> <input type="submit" name="submit" type="submit" value="Envoyer" class="radius button" /> </form> </div> </section> </div> </div> <div class="large-3 columns"> <!-- <p> <a href="" data-reveal-id="mapModal"><img src="http://placehold.it/400x280"></a><br/> <a href="" data-reveal-id="mapModal">View Map</a> </p> <p> 123 Awesome St.<br/> Barsoom, MA 95155 </p> --> </div> </div> <script> $( document ).ready(function() { $("#contactForm").validate({ rules: { name: "required", email: { required: true, email: true }, message: { required: true, }, human: { required: true, range: [4, 4] } }, messages: { name: "Merci de renseigner votre nom.", email: { required: "Merci de renseigner votre email.", email: "Merci de renseigner une adresse email valide." }, message: "Merci de décrire le projet pour lequel vous nous contactez.", human:{ required:"Merci de donner un résultat.", range: "Ce n'est pas le bon résultat." } } }); $.datepicker.setDefaults($.datepicker.regional["fr"]); $( "#date_start" ).datepicker({dateFormat: 'dd/mm/yy', minDate: 0}, $.datepicker.regional[ "fr" ]); $( "#date_stop" ).datepicker({dateFormat: 'dd/mm/yy', minDate: 1}, $.datepicker.regional[ "fr" ]); // $( "#date_start" ).mask('99/99/9999'); // $( "#date_begin" ).mask('99/99/9999'); }); </script> <file_sep>/modules/authentication/login_att.php <?php define('TITLE', 'Login'); $loggedin = false; $error = false; ?> <div class="row"> <div class="large-9 columns panel"> <h1>Login</h1> <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { $problem = FALSE; //handle the form if ((!empty($_POST['email'])) && (!empty($_POST['password']))) { if ((strtolower($_POST['email']) == '<EMAIL>') && ($_POST ['password'] == '<PASSWORD>') ) { setcookie('Samuel', 'Clemens',time()+3600); $loggedin = true; } else { // Incorrect! $error = 'The submitted email address and password do not match those on file!'; } } else { $problem = TRUE; print '<p class="error">vous avez oublie de remplir un champ</p>'; } if ($error) { print '<p class="error">' . $error . '</p>';} } if ($loggedin) { print '<p>You are now logged in!</p>';} else { print ' <form action="index.php?p=login" method="post"> <div class="row"> <div class="small-8"> <div class="row"> <div class="small-3 columns"> <label for="right-label" class="right">Email</label> </div> <div class="small-9 columns"> <input type="text" name="email" id="right-label" placeholder="Inline Text Input"> </div> </div> <div class="row"> <div class="small-3 columns"> <label for="right-label" class="right">Mot de passe</label> </div> <div class="small-9 columns"> <input type=password name="password" id="right-label" placeholder="Inline Text Input"> </div> </div> <button type="submit" class="radius button">Envoyer</button> </div> </div> </form>';} ?> </div> </div><file_sep>/modules/authentication/logout.php <?php // Script 9.8 - logout.php /* This is the logout page. It destroys the session information. */ // // Need the session: // session_start(); // // Delete the session variable: // unset($_SESSION); // // Reset the session array: // $_SESSION = array(); // Define a page title and include the header: define('TITLE', 'Logout'); // store to test if they *were* logged in $old_user = $_SESSION['valid_user']; unset($_SESSION['valid_user']); session_destroy(); ?> <h1>Log out</h1> <?php if (!empty($old_user)) { echo 'Logged out.<br />'; } else { // if they weren’t logged in but came to this page somehow echo 'You were not logged in, and so have not been logged out.<br />'; } ?> <a href="/index.php?p=login">Back to main page</a><file_sep>/phpinfo.php <?php $to = "<EMAIL>"; $subject = "My subject"; $txt = "Hello world!"; $headers = "From: <EMAIL>" . "\r\n" . "CC: <EMAIL>"; mail($to,$subject,$txt,$headers); phpinfo(); ?><file_sep>/modules/blog/add_category.php <?php // Script 9.8 - logout.php /* This is the logout page. It destroys the session information. */ // Define a page title and include the header: define('TITLE', 'Add category'); include_once('includes/functions.php'); ?> <div class="row"> <div class="large-9 columns panel"> <h1>Add a Category for this blog</h1> <?php if (!isset($_SESSION['valid_user'])) { print '<h2>Access Denied!</h2> <p class="error">You do not have permission to access this page.</p>'; include('templates/footer.php'); exit(); } if ($_SERVER['REQUEST_METHOD'] == 'POST') { $problem = FALSE; if (!empty($_POST['category_name']) && !empty($_POST['description'])) { include(DB); $category_name = mysqli_real_escape_string($dbc, trim(strip_tags($_POST['category_name']))); $description = mysqli_real_escape_string($dbc, trim(strip_tags($_POST['description']))); $slug = slugify($category_name); } else { print '<p style="color:red;">Please submit both a title and an entry.</p>'; $problem = TRUE; } if (!$problem) {$query = "INSERT INTO Category (name, description, slug) VALUES ('$category_name', '$description', '$slug')";} if (@mysqli_query($dbc,$query)) { print '<p>The category has been added!</p>';} else { print '<p style="color: red;"> Could not add the category because:<br />' . mysqli_error($dbc) . '.</p> <p>The query being run was: ' . $query . '</p>';} // No problem! mysqli_close($dbc); } // End of form submission IF. ?> <form accept-charset="utf-8" action="index.php?p=add_category" method="post"> <p>Category name: <input type="text" name="category_name" size="40" maxsize="100" /></p> <p>Description: <textarea name="description" cols="40" rows="5"></textarea></p> <input type="submit" name= ̈"submit" value="Add this Category!" /> </form> </div> </div><file_sep>/modules/blog/show_entry.php <?php // Script 13.9 -edit_quote.php require_once 'ressources/php_markdown_lib_1.4.1/Michelf/Markdown.inc.php';?> <div class="wrapper"> <div class="row"> <div class="large-9 columns aside"> <?php include(DB); if (isset($_GET['slug']) && ($_GET['slug'] != null)) { $query = "SELECT e.entry_id, e.title,e.entry,c.name, c.id FROM entries e LEFT JOIN Category c ON e.category_id = c.id WHERE e.slug='{$_GET['slug']}'"; if ($r = mysqli_query($dbc, $query)) { $row = mysqli_fetch_array($r); $text = \Michelf\Markdown::defaultTransform($row[2]); print '<h1 class="page-title">Blog - '.$row[3].'</h1><div class=\'panel single-post\'><h1>'.$row[1].'</h1><p>'.$text.'</p></div>'; $page_title = $row[1]; if (isset($_SESSION['valid_user'])){ print "<a href=\"/index.php?p=edit_category&id={$row['id']}\">Modifier la catégorie</a> <a href=\"/index.php?p=edit_entry&id={$row['entry_id']}\">Edit</a>"; } } else echo 'bla'; } ?> <div id="disqus_thread"></div> <script type="text/javascript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = 'reveclair'; // required: replace example with your forum shortname /* * * DON'T EDIT BELOW THIS LINE * * */ (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> </div> <div class="large-3 columns"> <?php include('templates/blog_sidenav.html'); ?> </div> </div> <div class="push"></div> </div> <script language="javascript"> $(document).ready(function() { $(this).attr("title", $(".single-post h1").text()); }); </script> <file_sep>/includes/functions.php <?php function is_administrator($name ='Samuel', $value = 'Clemens') { if (isset($_COOKIE[$name]) && ($_COOKIE[$name] == $value)) { return true; } else { return false; } } /** * Modifies a string to remove all non ASCII characters and spaces. */ function slugify($text) { // replace non letter or digits by - $text = preg_replace('~[^\\pL\d]+~u', '-', $text); // trim $text = trim($text, '-'); // transliterate if (function_exists('iconv')) { $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text); } // lowercase $text = strtolower($text); // remove unwanted characters $text = preg_replace('~[^-\w]+~', '', $text); if (empty($text)) { return 'n-a'; } return $text; } //takes a MySQL result identifier and returns a numerically indexed array of rows, where each row is an associative array function db_result_to_array($result) { $res_array = array(); for ($count=0; $row = $result->fetch_assoc(); $count++) { $res_array[$count] = $row; } return $res_array; } function get_categories() { // query database for a list of categories $conn = db_connect(); $query = "select id, name from categories"; $result = @$conn->query($query); if (!$result) {return false; } $num_cats = @$result->num_rows; if ($num_cats == 0) {return false; } $result = db_result_to_array($result); return $result; } function display_categories($cat_array) { if (!is_array($cat_array)) { echo "<p>No categories currently available</p>"; return; } echo "<ul>"; foreach ($cat_array as $row) { $url = "show_cat.php?catid=".($row['catid']); $title = $row['catname']; echo "<li>"; do_html_url($url, $title); echo "</li>"; } echo "</ul>"; echo "<hr />"; } ?><file_sep>/modules/blog/posts.php <?php define('TITLE', 'Blog'); include_once('includes/functions.php'); require_once 'ressources/php_markdown_lib_1.4.1/Michelf/Markdown.inc.php'; ?> <div class="wrapper"> <div class="row"> <div class='large-9 columns aside'> <h4 class="page-title">Blog</h4><hr/> <?php include(DB); $display = 1; // Determine how many pages there are... if (isset($_GET['page']) && is_numeric($_GET ['page'])) { $pages = $_GET['page']; } else { $q = "SELECT COUNT(entry_id) FROM entries"; $r = @mysqli_query($dbc, $q); $row = @mysqli_fetch_array($r, MYSQLI_NUM); $records = $row[0]; if ($records > $display) { $pages = ceil($records/$display); } else { $pages = 1; } } // Determine where in the database to start returning results... if (isset($_GET['s']) && is_numeric($_GET['s'])) { $start = $_GET['s']; } else { $start =0; } // Make the query: $q = "SELECT e.title, e.entry, c.name, e.entry_id, e.isPublic, e.date_entered, e.slug FROM entries e LEFT JOIN Category c ON e.category_id = c.id ORDER BY e.date_entered DESC LIMIT $start, $display"; $r = @mysqli_query($dbc, $q); // Fetch and print all the records.... 60 $bg = '#eeeeee'; // Set the initial background color. while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) { $bg = ($bg=='#eeeeee' ? '#ffffff' : '#eeeeee'); // Switch the background color. echo '<tr bgcolor="' . $bg . '"> <td align="left">' . $row['title'] . '</td> <td align="left">' . $row['name'] . '</td> <td align="left">' . $row['slug'] . '</td> </tr> '; } // End of WHILE loop. echo '</table>'; mysqli_free_result ($r); mysqli_close($dbc); if ($pages > 1) { echo '<br /><p>'; $current_page = ($start/$display) + 1; if ($current_page != 1) { echo '<a href="/index.php?p=posts?s=' . ($start - $display) . '&page=' . $pages . '">Previous</a> '; } for ($i = 1; $i <= $pages; $i++) { if ($i != $current_page) { echo '<a href="/index.php?p=posts?s=' . (($display * ($i - 1))) . '&page=' . $pages . '">' . $i . '</a> '; } else { echo$i.''; } } // If it's not the last page, make a Next button: if ($current_page != $pages) { echo '<a href="/index.php?p=posts?s=' . ($start + $display) . '&page=' . $pages . '">Next</a>'; } echo '</p>'; // Close the paragraph. } // End of links section. ?> </div> <div class="large-3 columns"> <?php include('templates/blog_sidenav.html'); ?> </div> </div> <div class="push"></div> </div> <?php mysqli_close($dbc); ?> <file_sep>/modules/work.php <?php //content modules should not be accessed directly through a URL since they would then lack the HTML Template //we'll see if a constant is defined (which should be included first thing in the index file, prior to including this page) if (!defined('BASE_URL')) { require('../includes/config.inc.php'); $url = BASE_URL . 'work.php'; header("Location:$url"); exit; } ?> <div class="row"> <div class="large-12 columns"> <ul class="example-orbit" data-orbit> <li> <img src="ressources/images/ab.png" alt="slide 1" /> <div class="orbit-caption"><h3>Site de recettes <small>olive-et-pistache.com</small></h3> <p>Construit sous Symfony 2.3, ce site permet de présenter une galerie de produits, avec une vente en ligne possible. Pour le gérant, le site permet aussi de gérer sa comptabilité avec diverses extractions possibles des données. </p> </div> </li> <li> <img src="ressources/images/op.png" alt="slide 1" /> <div class="orbit-caption"><h3>Site de recettes <small>olive-et-pistache.com</small></h3> <p>Construit sous Symfony 2.3, ce site permet de trier et de chercher rapidement des recettes selon des critères variés. Les informations nutritionnelles de chaque recette sont mises à jour avec la technologie Ajax. Par ailleurs, pour l'administrateur du site, l'ajout de recettes se fait via une interface admin graphique et épurée. </p> </div> </li> <li class="active"> <img src="ressources/images/vo.png" alt="slide 2" /> <div class="orbit-caption"><h3>Showroom vélos <small>velo-occaz.com</small></h3> <p>Construit sous Django 1.7 (Python 3), ce site est un showroom agréable, rapide et simple à parcourir pour le client. Les nombreuses photos se chargent rapidement grâce à l'utilisation d'Ajax.</p> </div> </li> <li> <img src="ressources/images/pot.png" alt="slide 3" /> <div class="orbit-caption"><h3>Site d'information sur le potager <small>potager-et-co.fr</small></h3> <p>Construit avec Django 1.6.5</p> </div> </li> </ul> </div> </div><file_sep>/modules/blog/add_entry.php <?php // Script 9.8 - logout.php /* This is the logout page. It destroys the session information. */ // Define a page title and include the header: define('TITLE', 'Add entry'); include_once('includes/functions.php'); ?> <div class="row"> <div class="large-9 columns panel"> <h1>Add a Blog Entry</h1> <?php if (!isset($_SESSION['valid_user'])) { print '<h2>Access Denied!</h2> <p class="error">You do not have permission to access this page.</p>'; include('templates/footer.php'); exit(); } else { print "<em>Les articles de ce blog sont issus de notre expérience personnelle et d'ouvrages spécialisés.</em>"; } ?> <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { $problem = FALSE; if (!empty($_POST['title']) && !empty($_POST['entry']) && !empty($_POST['category_id']) && isset($_POST['is_public'])) { include(DB); $title = mysqli_real_escape_string($dbc, trim(strip_tags($_POST['title']))); if (!get_magic_quotes_gpc()) { $entry = addslashes($_POST['entry']); } else { $entry = $_POST['entry'];} $category_id = mysqli_real_escape_string($dbc, trim(strip_tags($_POST['category_id']))); $isPublic = $_POST['is_public']; $slug = slugify($title); // echo $slug; // die(); } else { print '<p class="error">Please submit both a title and an entry and public.</p>'; $problem = TRUE; } if (!$problem) { $query = "INSERT INTO entries (entry_id, title, entry, category_id, isPublic, date_entered, slug) VALUES (0, '$title', '$entry', '$category_id', '$isPublic', NOW(), '$slug')"; } if (@mysqli_query($dbc, $query)) { print '<p>The blog entry has been added!</p>'; $url = BASE_URL . 'index.php'; header ("Location: $url"); exit; } else { print ' <p style="color: red;"> Could not add the entry because:<br />' . mysqli_error($dbc) . '.</p> <p>The query being run was: ' . $query . '</p>'; } // No problem! mysqli_close($dbc); } // End of form submission IF. ?> <form accept-charset="utf-8" action="/index.php?p=add_entry" method="post"> <p>Entry Title: <input type="text" name="title" size="40" maxsize="100" /></p> <select name="category_id">; <?php include(DB); //fetch nurse name $query = "SELECT id,name FROM Category;"; $result = mysqli_query($dbc, $query) or die(mysqli_error()); //note: use mysql_error() for development only //print results while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { echo '<option value='.$row['id'].'>'.$row['name'].'</option>'; } echo "</select>"; ?> <p>Entry Text: <textarea id="editor1" name="entry" cols="40" rows="5"></textarea></p> <p>Public ? <input type="radio" name="is_public" value="1" id="isPublicTrue"><label for="isPublicTrue">Oui</label> <input type="radio" name="is_public" value="0" id="isPublicFalse"><label for="isPublicFalse">Non</label> </p> <input type="submit" name="submit" value="Post This Entry!" /> </form> </div> </div> <file_sep>/modules/content.php <?php //content modules should not be accessed directly through a URL since they would then lack the HTML Template //we'll see if a constant is defined (which should be included first thing in the index file, prior to including this page) if (!defined('BASE_URL')) { require('../includes/config.inc.php'); $url = BASE_URL . 'content.php'; header("Location:$url"); exit; } ?> <div class="row"> <div class="large-12 columns"> <div id="featured"> <h1 style="text-align:center;">Des sites modernes, propres et robustes. <?php if (isset($_SESSION['email'])) {print '<p>Hello, ' . $_SESSION['email'] . '!</p>'; } ?></h1> <p><b>Créer</b> des sites propres correspondant à vos besoins selon les technologies et méthodes actuelles les plus éprouvées : méthode de développement AGILE avec tests et mise en production rapide, frameworks Symfony 2 ou Django.</p> </div> </div> </div> <div class="row hide-for-small"> <div class="large-3 small-6 columns"> <a href="http://www.velo-occaz.com" target="_blank"> <img src="ressources/images/vo.png"> <h6 class="panel radius">E-commerce pour vélos vintage</h6> </a> </div> <div class="large-3 small-6 columns"> <a href="http://www.art-de-broc.com" target="_blank"> <img src="ressources/images/ab.png"> <h6 class="panel radius">E-commerce pour objets de luxe et oeuvres d'art</h6> </a> </div> <div class="large-3 small-6 columns"> <a href="http://www.olive-et-pistache.com" target="_blank"> <img src="ressources/images/op.png"> <h6 class="panel radius">Site de cuisine</h6> </a> </div> <div class="large-3 small-6 columns"> <a href="http://www.potager-et-co.fr" target="_blank"> <img src="ressources/images/pot.png"> <h6 class="panel radius">Blog sur le potager</h6> </a> </div> </div> <div class="row"> <div class="large-8 columns "> <div class="panel radius border-panel"> <div class="row"> <div class="large-6 small-12 columns"> <h4>Notre petite entreprise</h4> <hr> <p>Après des études à Centrale et Polytechnique et diverses expériences, nous (<NAME> Victor) avons décidé de travailler à notre compte. <br/> Nous sommes maintenant un bureau indépendant de création de sites Web et nouvellement d'application iOS. Notre philosophie est de combiner la technique et le design pour une expérience utilsateur agréable et rapide et pour l'entreprise de la performance. </p> <div class="show-for-small" style="text-align: center"> <a class="small radius button" href="/contact">Contactez nous !</a><br> </div> </div> <div class="large-6 small-12 columns"> <p><b>Pourquoi travailler avec nous ?</b><br/>Vous avez besoin de créer un site facilement modulable pour représenter votre travail ou gérer des données (type galerie de produits, recettes, articles ...) autrement qu'avec une simple plateforme de blog. Nous avons une passion commune pour l'informatique et une forte sensibilité pour la recherche de la solution la plus adaptée à un problème donné. Notre petite structure nous permet d'être très réactif, de faire un seul projet à la fois, de nous focaliser sur sa qualité et donc de le faire bien. </p> </div> </div> </div> </div> <div class="large-4 columns hide-for-small"> <div class="panel radius"> <h4>Nos compétences</h4> <ul> <li>Programmation web et iOS</li> <li>Graphisme</li> <li>Management de projet</li> <li>Maintenance et administration</li> </ul> <!-- <div class="row"> <div class="small-9 large-centered columns"> <a href="#" data-reveal-id="firstModal" class="radius button">Plus de détails</a> </div> </div> --> </div> <a href="hide-for-small"> <div class="panel radius callout" style="text-align: center"> <strong>Contactez nous !</strong> </div> </a> </div> </div> <file_sep>/modules/work_att1.php <?php //content modules should not be accessed directly through a URL since they would then lack the HTML Template //we'll see if a constant is defined (which should be included first thing in the index file, prior to including this page) if (!defined('BASE_URL')) { require('../includes/config.inc.php'); $url = BASE_URL . 'work.php'; header("Location:$url"); exit; } ?> <div class="row"> <div class="large-10 columns"> <h1>Notre travail</h1> <div class="row"> <div class="large-8 columns"> <img src="ressources/images/op.png" alt="slide 1" /> <div class="panel"> <h3>Site de recettes <small>olive-et-pistache.com</small></h3> <p>Construit sous Symfony 2.3, ce site permet de trier et de chercher rapidement des recettes selon des critères variés. Les informations nutritionnelles de chaque recette sont mises à jour avec la technologie Ajax. Par ailleurs, pour l'administrateur du site, l'ajout de recettes se fait via une interface admin graphique et épurée.</p> </div> </div> <div class="large-4 columns"> <div class="panel"> <h3>Technologies utilisées</h3> <ul> <li>Symfony 2.3</li> <li>Ajax</li> <li>SOLR</li> </ul> </div> <div class="panel"> <h3>Marketing</h3> <ul> <li>Twitter API</li> <li>Facebook API</li> <li>Instagram</li> </ul> </div> </div> </div> <hr/> <div class="row"> <div class="large-8 columns"> <img src="ressources/images/vo.png" /> <div class="panel"> <h3>Showroom vélos <small>velo-occaz.com</small></h3> <p>Construit sous Symfony 2.3, ce site est un showroom agréable, rapide et simple à parcourir pour le client. Les nombreuses photos se chargent rapidement grâce à l'utilisation d'Ajax.</p> </div> <div class="panel"> <h3>Marketing</h3> <ul> <li>Twitter API</li> <li>Facebook API</li> <li>Instagram</li> </ul> </div> </div> <div class="large-4 columns"> <div class="panel"> <h3>Technologies utilisées</h3> <ul> <li>Symfony 2.3</li> <li>Ajax</li> <li>SOLR</li> </ul> </div> <div class="panel"> <h3>( Autres livrables )</h3> <img src="ressources/images/vo_crtevisite.png" alt="slide 1" /> </div> </div> </div> <hr/> <div class="row"> <div class="large-8 columns"> <img src="ressources/images/ab.png" alt="slide 1" /> <div class="panel"> <h3>Site de recettes <small>olive-et-pistache.com</small></h3> <p>Construit sous Symfony 2.3, ce site permet de trier et de chercher rapidement des recettes selon des critères variés. Les informations nutritionnelles de chaque recette sont mises à jour avec la technologie Ajax. Par ailleurs, pour l'administrateur du site, l'ajout de recettes se fait via une interface admin graphique et épurée.</p> </div> <div class="panel"> <h3>Marketing</h3> <ul> <li>Twitter API</li> <li>Facebook API</li> <li>Instagram</li> </ul> </div> </div> <div class="large-4 columns"> <div class="panel"> <h3>Technologies utilisées</h3> <ul> <li>Symfony 2.3</li> <li>Ajax</li> <li>SOLR</li> </ul> </div> <div class="panel"> <h3>( Autres livrables )</h3> <img src="ressources/images/ab_crtevisite.png" alt="slide 1" /> </div> </div> </div> <div class="row"> <div class="large-8 columns"> <img src="ressources/images/pot.png" alt="slide 1" /> <div class="panel"> <h3>Blog sur le jardinage<small>potager-et-co.fr</small></h3> <p>Construit sous Wordpress, ce site permet de trier et de chercher rapidement des recettes selon des critères variés. Les informations nutritionnelles de chaque recette sont mises à jour avec la technologie Ajax. Par ailleurs, pour l'administrateur du site, l'ajout de recettes se fait via une interface admin graphique et épurée.</p> </div> </div> <div class="large-4 columns"> <div class="panel"> <h3>Technologies utilisées</h3> <ul> <li>Symfony 2.3</li> <li>Ajax</li> <li>SOLR</li> </ul> </div> <div class="panel"> <h3>Marketing</h3> <ul> <li>Liens Amazon</li> <li>Facebook API</li> <li>Instagram</li> </ul> </div> </div> </div> </div> </div> <file_sep>/modules/blog/edit_entry.php <?php // Script 13.9 -edit_quote.php define('TITLE', 'Modifier un post'); include_once('includes/functions.php'); ?> <div class="row"> <div class="large-9 columns"> <?php print '<h2>Modification d\'un post</h2>'; if (!isset($_SESSION['valid_user'])){ print '<h2>Access Denied!</h2> <p class="error">You do not have permission to access this page.</p>'; include('templates/footer.php'); exit(); } include(DB); if (isset($_GET['id']) && is_numeric($_GET['id']) && ($_GET['id'] > 0) ) { $query = "SELECT title,entry,isPublic, slug FROM entries WHERE entry_id={$_GET['id']}"; if ($r = mysqli_query($dbc, $query)) { $row = mysqli_fetch_array($r); print '<form accept-charset="UTF-8" action="index.php?p=edit_entry" method="post"> <p><label>Contenu <textarea name="entry" rows="5" cols="30">' . htmlspecialchars($row['entry'], ENT_QUOTES, "UTF-8") . '</textarea></label></p> <p><label>Titre <input type="title" name="title" value="' . htmlspecialchars($row['title'], ENT_QUOTES, "UTF-8") . '" /></label></p> <p>Public ?'; if ($row['isPublic'] == 1){ print '<input type="radio" name="is_public" value="1" checked id="isPublicTrue"><label for="isPublicTrue">Oui</label> <input type="radio" name="is_public" value="0" id="isPublicFalse"><label for="isPublicFalse">Non</label>'; } else { print '<input type="radio" name="is_public" value="1" id="isPublicTrue"><label for="isPublicTrue">Oui</label> <input type="radio" name="is_public" value="0" checked id="isPublicFalse"><label for="isPublicFalse">Non</label>'; } print ' </p> <input type="hidden" name="id" value="' . $_GET['id'] . '" /> <p><input type="submit" name="submit" value="Update This Post!" /></p> </form>'; } else { // Couldn't get the information. print '<p class="error">Could not retrieve the post because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>'; } } elseif (isset($_POST['id']) && is_numeric($_POST['id']) && ($_POST['id'] > 0)) { $problem = FALSE; if ( !empty($_POST['title']) && !empty($_POST['entry']) && !isset($_POST['isPublic']) ) { $title = mysqli_real_escape_string($dbc, trim(strip_tags($_POST['title']))); if (!get_magic_quotes_gpc()) { $entry = addslashes($_POST['entry']); } else { $entry = $_POST['entry'];} $isPublic = $_POST['is_public']; $slug = slugify($title); } else { print '<p class="error">Please submit both a title and a content.</p>'; $problem = TRUE; } if (!$problem) { $query = "UPDATE entries SET title='$title', entry='$entry', isPublic='$isPublic', slug = '$slug' WHERE entry_id={$_POST['id']}"; if ($r = mysqli_query($dbc, $query)) { print '<p>The quotation has been updated.</p>'; $url = BASE_URL . 'posts/'.$slug; header ("Location: $url"); exit; } else { print '<p class="error">Could not update the quotation because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>'; } } // No problem! } else { // No ID set. print '<p class="error">This page has been accessed in error.</p>'; } // End of main IF. mysqli_close($dbc); ?> </div> </div> <file_sep>/templates/footer.php <footer> <div class="row"> <div class="medium-4 medium-4 push-8 columns"> </div> <div class="medium-8 medium-8 pull-4 columns"> <p class="copyright">© 2014-2015 REVECLAIR. Tous droits réservés.</p> </div> </div> </footer> <script type="text/javascript" src="/ressources/js/shCore.js"></script> <script type="text/javascript" src="/ressources/css/sh/shBrushJScript.js"></script> <script> $(document).foundation(); // CKEDITOR.replace('editor1'); var doc = document.documentElement; doc.setAttribute('data-useragent', navigator.userAgent); SyntaxHighlighter.all(); </script> </body> </html> <?php ob_end_flush();?><file_sep>/modules/blog/delete_entry.php <?php // Script 13.10 - delete_quote.php /* This script deletes a quote. */ // Define a page title and include the header: define('TITLE', 'Delete a Post'); ?> <div class="row"> <div class="large-9 columns"> <h2>Delete a Post</h2> <?php // Restrict access to administrators only: if (!isset($_SESSION['valid_user'])) { print '<h2>Access Denied!</h2> <p class="error">You do not have permission to access this page.</p>'; include('templates/footer.html'); exit(); } // Need the database connection: include(DB); if (isset($_GET['id']) && is_numeric($_GET['id']) && ($_GET['id'] > 0)) { // Display the quote in a form // Define the query: $query = "SELECT title FROM entries WHERE entry_id={$_GET['id']}"; if ($r = mysqli_query($dbc, $query)) { // Run the query. $row = mysqli_fetch_array($r, MYSQLI_ASSOC); // Retrieve the information. // Make the form: print '<form action="index.php?p=delete_entry" method="post"> <p>Are you sure you want to delete this post?</p> <div><blockquote>' . $row['title'] . '</blockquote>'; print '</div><br /><input type="hidden" name="id" value="' . $_GET['id'] . '" /> <p><input type="submit" name="submit" value="Delete this Post!" /></p> </form>'; } else { // Couldn't get the information. print '<p class="error">Could not retrieve the quote because:<br />' . mysql_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>'; } } elseif (isset($_POST['id']) && is_numeric($_POST['id']) && ($_POST['id'] > 0) ) { // Handle the form. // Define the query: $query = "DELETE FROM entries WHERE entry_id={$_POST['id']} LIMIT 1"; $r = mysqli_query($dbc, $query); // Execute the query. 51 // Report on the result: if (mysqli_affected_rows($dbc) == 1) { print '<p>The post has been deleted.</p>'; } else { print '<p class="error">Could not delete the blog entry because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>'; } } else { // No ID received. print '<p class="error">This page has been accessed in error.</p>'; } // End of main IF. mysqli_close($dbc); // Close the connection. 64 ?> </div> </div><file_sep>/includes/config.inc.php <?php #Script 2.1 - config.inc.php $contact_email = "<EMAIL>"; //determine whether the script is running on the live server or a test server $host = substr($_SERVER['HTTP_HOST'], 0, 5); if (in_array($host, array('local', '127.0', '192.1'))) {$local = true;} else {$local = false;} //SI LOCAL if ($local) { $debug = true; //the BASE_URI is the absolute file system path to where the site's root folder is on the server define('BASE_URI', '/path/to/html/folder/'); define('BASE_URL', 'http://local.reveclair.com/'); //absolute path on the server to the mysql.inc.php file define('DB', '/Users/claireveiniere/Sites/reveclair/includes/mysql_connect.php'); } //SI PROD else { //paths on remote server define('BASE_URI', '/path/to/live/html/folder/'); define('BASE_URL', 'http://www.reveclair.fr/'); define('DB', '/home/claire/mysql_connect.php'); } //debugging is disabled by default if (!isset($debug)) {$debug = FALSE;} //php allows you to define your own function for handling erros function my_error_handler($e_number, $e_message, $e_file, $e_line, $e_vars) { global $debug, $contact_email; $message = "An error occurred in script '$e_file' on line $e_line: $e_message"; $message .= print_r($e_vars, 1); if ($debug) { echo '<div class="error">' . $message . '</div>'; debug_print_backtrace(); } //if debugging is turned off else { error_log ($message, 1, $contact_email); //a strict error has the value of 2048 if ( ($e_number != E_NOTICE) && ($e_number < 2048)) { echo '<div class="error">A system error occurred. We apologize for the inconvenience.</div>'; } } } set_error_handler('my_error_handler'); ?> <file_sep>/modules/blog/edit_category.php <?php // Script 13.9 -edit_quote.php define('TITLE', 'Modifier une catégorie'); include_once('includes/functions.php'); ?> <div class="row"> <div class="large-9 columns"> <?php print '<h2>Modification d\'une catégorie</h2>'; //on verifie que l'user est bien authentifié if (!isset($_SESSION['valid_user'])){ print '<h2>Access Denied!</h2> <p class="error">You do not have permission to access this page.</p>'; include('templates/footer.php'); exit(); } include(DB); if (isset($_GET['id']) && is_numeric($_GET['id']) && ($_GET['id'] > 0) ) { $query = "SELECT name, description FROM Category WHERE id={$_GET['id']}"; if ($r = mysqli_query($dbc, $query)) { $row = mysqli_fetch_array($r); print '<form accept-charset="UTF-8" action="index.php?p=edit_category" method="post"> <p><label>Description <textarea name="description" rows="5" cols="30">' . htmlspecialchars($row['description'], ENT_QUOTES, "UTF-8") . '</textarea></label></p> <p><label>Nom <input type="name" name="name" value="' . htmlspecialchars($row['name'], ENT_QUOTES, "UTF-8") . '" /></label></p> <input type="hidden" name="id" value="' . $_GET['id'] . '" /> <p><input type="submit" name="submit" value="Update This Category!" /></p> </form>'; } else { // Couldn't get the information. print '<p class="error">Could not retrieve the category because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>'; } } elseif (isset($_POST['id']) && is_numeric($_POST['id']) && ($_POST['id'] > 0)) { $problem = FALSE; if ( !empty($_POST['name']) && !empty($_POST['description']) ) { $name = mysqli_real_escape_string($dbc, trim(strip_tags($_POST['name']))); $description = mysqli_real_escape_string($dbc, trim(strip_tags($_POST['description']))); $slug = slugify($name); } else { print '<p class="error">Please submit both a name and a description.</p>'; $problem = TRUE; } if (!$problem) { $query = "UPDATE Category SET name='$name', description='$description', slug='$slug' WHERE id={$_POST['id']}"; if ($r = mysqli_query($dbc, $query)) { print '<p>The category has been updated.</p>'; } else { print '<p class="error">Could not update the category because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>'; } } // No problem! } else { // No ID set. print '<p class="error">This page has been accessed in error.</p>'; } // End of main IF. mysqli_close($dbc); ?> </div> </div><file_sep>/index.php <?php session_name('YourVisit'); session_start(); //the configuration file defines many important things so it should be included first require("includes/config.inc.php"); //print '<h2>Welcome to the J.D. ̈ Salinger Fan Club!</h2>'; print '<p>Hello, ' . $_SESSION['email'] . '!</p>'; error_reporting(E_ALL | E_STRICT); define('MAIL_ADDRESS', '<EMAIL>'); //when the user clicks links, the value will be passed in the URL, when most forms are submitted the value will be sent in POST if (isset($_GET['p'])) { $p = $_GET['p'];} elseif (isset($_POST['p'])) { $p = $_POST['p'];} else { $p = NULL;} //echo $p; //determines the file to include and the page title switch ($p) { case 'contact': $page = 'contact.php'; $page_title = 'Contact'; break; case 'team': $page = 'team.php'; $page_title = 'Notre équipe'; break; case 'work': $page = 'work.php'; $page_title = 'Notre travail'; break; case 'method': $page = 'method.php'; $page_title = 'Nos méthodes'; break; case 'post': $page = 'post.php'; $page_title = 'Nouveau post'; break; case 'posts': $page = 'blog/posts.php'; $page_title = 'Nouveau post'; break; case 'login': $page = 'authentication/login.php'; $page_title = 'Login'; break; case 'logout': $page = 'authentication/logout.php'; $page_title = 'Logout'; break; case 'blog': $page = 'blog/blog.php'; $page_title = 'Blog'; break; //ENTRIES case 'add_entry': $page = 'blog/add_entry.php'; $page_title = 'Ajouter un post'; break; case 'edit_entry': $page = 'blog/edit_entry.php'; $page_title = 'Modifier un post'; break; case 'delete_entry': $page = 'blog/delete_entry.php'; $page_title = 'Supprimer un post'; break; case 'show_entry': $page = 'blog/show_entry.php'; // $page_title = 'Post'; break; //CATEGORIES case 'add_category': $page = 'blog/add_category.php'; $page_title = 'Ajouter une catégorie'; break; case 'edit_category': $page = 'blog/edit_category.php'; $page_title = 'Modifier une catégorie'; break; case 'list_category': $page = 'blog/list_category.php'; $page_title = 'Liste posts'; break; default: $page = 'content.php'; $page_title = 'Accueil'; break; } if (!file_exists('./modules/'.$page)) { $page = 'content.php'; $page_title = 'Accueil'; } include("templates/header.php"); //page is determined from the above switch include('modules/'.$page); include("templates/footer.php"); ?> <file_sep>/modules/team.php <?php //content modules should not be accessed directly through a URL since they would then lack the HTML Template //we'll see if a constant is defined (which should be included first thing in the index file, prior to including this page) if (!defined('BASE_URL')) { require('../includes/config.inc.php'); $url = BASE_URL . 'team.php'; header("Location:$url"); exit; } ?> <div class="row"> <div class="large-9 push-3 columns panel"> <h3>Claire <small> Responsable projets web</small></h3> <p>Je suis passionnée par la puissance et la portée des nouvelles technologies, et de façon générale par tout ce qui est de l'ordre de la créativité et de l'entreprenariat. Après avoir réalisé pour le compte de l'ambassade de France aux États-Unis, une <em>application web</em> de gestion du personnel sur l'ensemble du continent Amérique du Nord et travaillé dans une agence web, je réalise maintenant des projets informatiques de A jusqu'à Z en collaboration avec Victor. Ma formation et mon diplôme d'ingénieure Centralienne (spécialités Informatique & Finance) me permettent de concevoir, de m'investir dans les différentes facettes d'un projet avec l'objectif de le rendre, pour l'utilisateur, fiable et agréable.</p> </div> <div class="large-3 pull-9 columns"> <p><img src="ressources/images/claire.png"/></p> </div> </div> <div class="row"> <div class="large-9 push-3 columns panel"> <h3>Victor <small> Responsable projets iOS et expert technique</small></h3> <p>Polytechnicien et ayant effectué un doctorat à l'École Normale Supérieure (ENS), j'ai acquis une expertise dans le développement d'algorithmes rapides et efficaces. Je m’intéresse en particulier aux questions de performance et de scalabilité. <p>Je garantis que les projets que nous traitons repose sur un code propre, rapide, intelligent et facilement modulable.</p> </div> <div class="large-3 pull-9 columns"> <p><img src="ressources/images/victor.jpg"/></p> </div> </div>
865a9e39407ab2623f637079d181cb6cf6ab463d
[ "PHP" ]
22
PHP
claireve/reveclair
7d1d473cb431786545fde7e35f253ed4d46d4cc2
9140ed03738c5aa8b3fcccd7429f7d3917a56f80
refs/heads/master
<file_sep>import React from 'react' import styled from 'styled-components/macro' const NavigationStyled = styled.nav` display: flex; > button { flex-grow: 1; font-size: 1em; } ` export default function Navigation({ onClick, buttonTexts }) { return ( <NavigationStyled> {buttonTexts.map((text, index) => <button key={index} onClick={() => onClick(index)}> {text} </button>) } </NavigationStyled> ) }<file_sep>import React, {useState} from 'react'; import Navigation from './Navigation' import Homepage from './Homepage' import GlobalStyle from './GlobalStyle' import styled from 'styled-components/macro' const AppStyled = styled.div` height: 100vh; display: grid; grid-template-rows: auto 48px; font-family: sans-serif; ` export default function App() { const [activeIndex, setActiveIndex] = useState(0) const [cards, setCards] = useState([ { title: 'foo', question: 'what', answer:'bla' }, { title: 'bar', question: 'why', answer: 'blup' } ]) function renderPage(){ const pages={ 0: <Homepage cards={cards}/>, 1: <section>Practice</section>, 2: <section>Bookmarked</section>, 3: <section>Settings</section> } return pages[activeIndex] || <section>404</section> } return ( <AppStyled> <GlobalStyle /> {renderPage()} <Navigation buttonTexts={['Home', 'Practice', 'Bookmarked', 'Settings']} onClick={setActiveIndex} /> </AppStyled> ); } <file_sep>import React from 'react' import Card from './Card' import styled from 'styled-components/macro' const HomepageStyled = styled.div` padding: 20px; display: grid; align-content: flex-start; gap: 20px; ` export default function Homepage({cards}) { return ( <HomepageStyled> <h1>All cards</h1> {cards.map((card, index) => ( <Card key={index} title={card.title} question={card.question} answer={card.answer} /> ))} </HomepageStyled> ) }
de31bc0dbeee75b4662af56b0f2dae8073f0b8a8
[ "JavaScript" ]
3
JavaScript
marwehl/flashcards-project
df7ef3bf08cc006634666d537962c8dae3c8ab14
7acb9d85ed86b7fb171618ad6b2ee351557f0805
refs/heads/master
<file_sep>import { observable, computed, action, autorun } from 'mobx' import Router from './router' import browserHistory from 'history/createBrowserHistory' export Router from './router' const properRoute = path => (path.indexOf('/') === 0 ? path : `/${path}`) export class ObservableRouter { max = window.history.length @observable position = window.history.length @observable path = window.location.pathname @observable route = null @observable.ref params = {} @observable forceUpdate = false @observable version = 0 _id = Math.random() constructor({ routes, history }) { this.routes = routes this.history = history || browserHistory() const routeHandlers = Object.keys(routes).reduce( (acc, path) => ({ ...acc, [properRoute(path)]: params => this.setRoute(path, params), }), {} ) this.router = new Router({ routes: routeHandlers, history: this.history, }) autorun(() => { if (this.path !== window.location.pathname || this.forceUpdate) { this.history.push(this.path) this.forceUpdate = false } }) } @action setRoute = (path, params) => { this.path = window.location.pathname this.route = path this.params = params || {} } @computed get key() { return `${this.version}${this.forceUpdate}${JSON.stringify(this.path)}` } @computed get activeView() { return this.routes[this.route] } @computed get routeName() { return this.path.split('/')[0] } @computed get atFront() { return this.position === this.max } @computed get atBack() { return this.position === 0 } @action back = () => { this.position -= 1 this.history.goBack() } @action forward = () => { this.position += 1 this.history.goForward() } @action go = (...segments) => { const path = segments.join('/') this.position += 1 this.max = this.position this.path = path[0] === '/' ? path : `/${path}` } // sets a part of the url @action set = (key, val) => { const Route = this.router.routeTable[`/${this.route}`] const params = typeof key === 'object' ? this.setObject(key) : this.setParam(key, val) const newPath = Route.stringify(params) if (newPath !== this.path) { this.path = newPath } }; normalizeParams = (params: Object): Object => { // remove false/null Object.keys(params).forEach(key => { const val = params[key] if (val === false || val === null) { delete params[key] } }) return params } setObject = params => this.normalizeParams({ ...this.params, ...params }) setParam = (key, val) => this.normalizeParams({ ...this.params, [key]: val }) @action unset = key => { this.set(key, false) } @action redirect = path => { window.location.href = path } isActive = path => { return !!this.router.getMatch(path) } } export default ObservableRouter
6da7b8c8d5d0915a16e6aabcd29afd68fcd3264a
[ "JavaScript" ]
1
JavaScript
motion/router
c658a0220622bb3d83e26eefd5eff220cb5a310e
564d40a07c6a966175c00e62282a9eb621b26ef4
refs/heads/master
<repo_name>Ivann-2612/Task<file_sep>/task-two.js function validParentheses(parens) { let split1 = parens.split('') let split = split1.filter(el => el == "(" || el == ")") let opened = split.filter(el => el == "(") let closed = split.filter(el => el == ")") if (opened.length != closed.length) return false for (let i = 0; i < opened.length; i++) { if (split[0] == "(" && split[split.length - 1] == ")") { split.shift() && split.pop() } else { return false } return true } } console.log(validParentheses("Lorem ((ipsum)(dolor)sit)")) console.log(validParentheses("(Lorem (ipsum dolor)sit"))
fe35da8682cdf02a06279f43583f6a34f8decaae
[ "JavaScript" ]
1
JavaScript
Ivann-2612/Task
e6f91dc7a80d2482e997905be6546d7f630045d9
27b8cd62b7a65b3d78fc3fc01ff542cebd328cab
refs/heads/master
<file_sep>self.addEventListener('install', function (e) { e.waitUntil( caches.open('mi-cache').then(function (cache) { return cache.addAll([ './', './index.html', './index.js', './style.css', './images/foto.jpg', ]); }) ); }); self.addEventListener('fetch', function (e) { e.respondWith( caches.match(e.request).then(function (response) { return response || fetch(e.request); }) ); }); self.addEventListener('fetch', function (e) { e.respondWith( fetch(event.request) .catch(() => caches.match(event.request)) ); }); self.addEventListener('fetch', function (event) { event.respondWith( fetch(event.request) .then(async response => { if (event.request.method === 'GET') { try { await cache.put(event.request, response.clone()); } catch (error) { await cache.add(event.request); } } return response; }) .catch(() => caches.match(event.request)), ); });<file_sep># InicioPWA Es un mini proyecto para el BootCamp de Ribera Salud, en el cual usamos PWA
1d3b0e731e7a26d48e30803149a261e941b0bbfa
[ "JavaScript", "Markdown" ]
2
JavaScript
GuilleVargas/InicioPWA
4c1830a958682a801c2f1a3cfd449704b9739cdb
2c93c7af4bd4b9324b118a193fab949caa60cdc0
refs/heads/master
<file_sep>package main.entities.items; import java.awt.Graphics; import java.awt.Image; import main.Handler; import main.entities.Entity; import main.gfx.Assets; public class Item extends Entity{ private Image img; private String name; public Item(Handler handler, double x, double y, int width, int height, String name, Image img) { super(handler, x, y, width, height); this.img = img; this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public void tick() { } @Override public void render(Graphics g, double xOffset, double yOffset) { g.drawImage(img, (int)(x + 1 - xOffset), (int)(y + 1 - yOffset), width, height, null); } } <file_sep>package main.collisions; import main.entities.Entity; public class Collision { private static double leftRightGraceHeight = 10; private static double upDownGraceLength = 10; public Collision() { } public static boolean isCollision(Entity a, Entity b) { return (!(a.getX() + a.getWidth() - 1 < b.getX() || a.getX() + 1 > b.getX() + b.getWidth() || a.getY() + a.getHeight() < b.getY() || a.getY() > b.getY() + b.getHeight())); } public static boolean isCollisionRight(Entity a, Entity b) { return (!(a.getX() + a.getWidth() - 1 < b.getX() || a.getX() + a.getWidth() + 1 > b.getX() + b.getWidth() || a.getY() + a.getHeight() - leftRightGraceHeight < b.getY() || a.getY() + leftRightGraceHeight> b.getY() + b.getHeight())); } public static boolean isCollisionLeft(Entity a, Entity b) { return (!(a.getX() - 1 < b.getX() || a.getX() + 1 > b.getX() + b.getWidth() || a.getY() + a.getHeight() - leftRightGraceHeight < b.getY() || a.getY() + leftRightGraceHeight > b.getY() + b.getHeight())); } public static boolean isCollisionTop(Entity a, Entity b) { return (!(a.getX() + a.getWidth() - upDownGraceLength < b.getX() || a.getX() + upDownGraceLength > b.getX() + b.getWidth() || a.getY() <= b.getY() || a.getY() >= b.getY() + b.getHeight())); } public static boolean isCollisionBottom(Entity a, Entity b) { return (!(a.getX() + a.getWidth() - upDownGraceLength < b.getX() || a.getX() + upDownGraceLength > b.getX() + b.getWidth() || a.getY() + a.getHeight() <= b.getY() || a.getY() + a.getHeight() >= b.getY() + b.getHeight())); } public static boolean isAdjacentBottom(Entity a, Entity b) { return (!(a.getX() + a.getWidth() - upDownGraceLength < b.getX() || a.getX() + upDownGraceLength > b.getX() + b.getWidth() || a.getY() + a.getHeight() != b.getY() //|| )); } } <file_sep>package main.input; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class KeyManager implements KeyListener{ private boolean[] keys; public boolean up, down, left, right, upPressed, upHeld; public KeyManager() { keys = new boolean[256]; } public void tick() { up = keys[KeyEvent.VK_UP]; down = keys[KeyEvent.VK_DOWN]; left= keys[KeyEvent.VK_LEFT]; right = keys[KeyEvent.VK_RIGHT]; if(up && !upPressed && !upHeld) { upPressed = true; upHeld = true; } else if(up && upPressed) { upPressed = false; } else if(!up && upHeld){ upHeld = false; } } @Override public void keyPressed(KeyEvent e) { keys[e.getKeyCode()] = true; } @Override public void keyReleased(KeyEvent e) { keys[e.getKeyCode()] = false; } @Override public void keyTyped(KeyEvent e) { } } <file_sep>package main.state; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.util.ArrayList; import main.Handler; import main.collisions.Collision; import main.entities.platforms.MovingPlatformHor; import main.entities.platforms.MovingPlatformVert; import main.entities.platforms.Platform; import main.gfx.Assets; import main.gfx.Background; import main.entities.Entity; import main.entities.creatures.*; import main.entities.items.Item; import java.util.Random; // random comment for github test //another comment //yet another change to test github //fourth comment public class GameState extends State{ //private Background background; private Player player; //private Platform platform1, platform2; //private Enemy enemy; private ArrayList<Platform> p = new ArrayList<Platform>(100); private ArrayList<Item> i = new ArrayList<Item>(100); //Random r = new Random(); public GameState(Handler handler) { super(handler); //background = new Background(handler, Assets.battlefieldSprite); //player = new Player(handler, 200, 0, 8); //p.add(new Platform(handler, 200, 550, 200, 50)); //p.add(new MovingPlatformHor(handler, 200, 200, 200, 50, 400, 800, 3, true)); //p.add(new MovingPlatformVert(handler, 0, 200, 200, 50, 120, 600, 3, true)); //enemy = new Enemy(handler, 50, 50, 2, p.get(1)); player = new Player(handler, 775, 4950, 8); p.add(new Platform(handler, 0, 0, 50, 10050)); // map boundary p.add(new Platform(handler, 1550, 0, 50, 10050)); // map boundary //heaven side i.add(new Item(handler, 790, 150, 20, 40, "Key", Assets.keySprite)); p.add(new Platform(handler, 250, 200, 1100, 50)); p.add(new Platform(handler, 0, 350, 750, 50)); p.add(new Platform(handler, 1000, 550, 550, 50)); p.add(new Platform(handler, 800, 700, 200, 50)); p.add(new Platform(handler, 600, 850, 200, 50)); p.add(new Platform(handler, 400, 1000, 200, 50)); //p.add(new MovingPlatformHor(handler, 825, 1200, 150, 50, 50, 1350, 2, true)); //this is the moving platform nearest 'heaven' -- so make it moving p.add(new Platform(handler, 0, 1400, 100, 50)); i.add(new Item(handler, 55, 1345, 35, 40, "Wings", Assets.wingsSprite)); p.add(new Platform(handler, 1450, 1400, 100, 50)); // this will have a item/powerup p.add(new Platform(handler, 0, 1550, 200, 50)); p.add(new MovingPlatformHor(handler, 700, 1650, 200, 50, 50, 1350, 2, true)); // another moving platform p.add(new Platform(handler, 600, 1800, 400, 50)); p.add(new Platform(handler, 0, 2000, 400, 50)); p.add(new Platform(handler, 400, 2150, 200, 50)); p.add(new Platform(handler, 0, 2300, 400, 50)); p.add(new Platform(handler, 1450, 2150, 100, 50));// platform for item/powerup p.add(new Platform(handler, 400, 2450, 500, 50)); p.add(new Platform(handler, 900, 2650, 200, 50)); p.add(new Platform(handler, 1100, 2800, 200, 50)); p.add(new Platform(handler, 1300, 2950, 250, 50)); //p.add(new MovingPlatformHor(handler, 700, 3100, 200, 50, 50, 1350, 2, true)); // moving platform p.add(new Platform(handler, 50, 2950, 100, 50)); p.add(new Platform(handler, 1450, 3250, 100, 50)); p.add(new Platform(handler, 1350, 3450, 200, 50)); p.add(new Platform(handler, 1150, 3600, 200, 50)); p.add(new Platform(handler, 700, 3800, 200, 50)); p.add(new Platform(handler, 600, 3950, 400, 50)); i.add(new Item(handler, 75, 4045, 50, 50, "DoubleJump", Assets.doubleJumpSprite)); p.add(new Platform(handler, 50, 4100, 100, 50)); p.add(new Platform(handler, 200, 4250, 100, 50)); p.add(new Platform(handler, 200, 4400, 400, 50)); p.add(new Platform(handler, 600, 4550, 400, 50)); p.add(new Platform(handler, 500, 4600, 600, 50)); p.add(new Platform(handler, 400, 4650, 800, 50)); p.add(new Platform(handler, 300, 4700, 1000, 50)); p.add(new Platform(handler, 50, 4850, 100, 50)); p.add(new Platform(handler, 1450, 4850, 100, 50)); p.add(new Platform(handler, 250, 5000, 1100, 50)); // start/middle // demon side p.add(new Platform(handler, 1350, 5100, 100, 50)); p.add(new Platform(handler, 50, 5200, 700, 50)); p.add(new Platform(handler, 850, 5200, 700, 50)); p.add(new Platform(handler, 200, 5400, 1200, 50)); p.add(new Platform(handler, 50, 5600, 400, 50)); p.add(new Platform(handler, 450, 5750, 200, 50)); p.add(new Platform(handler, 1150, 5950, 400, 50)); p.add(new MovingPlatformHor(handler, 700, 6100, 200, 50, 50, 1350, 2, true)); // moving platform p.add(new Platform(handler, 50, 6300, 300, 50)); p.add(new Platform(handler, 350, 6300, 50, 600)); p.add(new Platform(handler, 200, 6850, 200, 50)); p.add(new Platform(handler, 50, 6950, 600, 50)); p.add(new Platform(handler, 150, 6500, 50, 400)); p.add(new Platform(handler, 1200, 7100, 350, 50)); p.add(new MovingPlatformHor(handler, 800, 7300, 200, 50, 50, 1350, 2, true)); // moving platform p.add(new Platform(handler, 450, 7500, 50, 200)); p.add(new Platform(handler, 50, 7200, 100, 50)); p.add(new Platform(handler, 50, 7900, 150, 50)); // add "spikes" p.add(new Platform(handler, 1350, 7600, 200, 50)); p.add(new Platform(handler, 1300, 7850, 250, 50)); p.add(new Platform(handler, 200, 8100, 1350, 50)); p.add(new Platform(handler, 50, 8300, 700, 50)); p.add(new Platform(handler, 900, 8300, 650, 50)); p.add(new Platform(handler, 750, 8550, 500, 200)); p.add(new Platform(handler, 50, 8450, 100, 50)); // item/powerup p.add(new Platform(handler, 550, 8700, 200, 50)); p.add(new Platform(handler, 1450, 8700, 100, 50)); p.add(new Platform(handler, 750, 8900, 800, 50)); p.add(new Platform(handler, 750, 8750, 50, 100)); p.add(new Platform(handler, 700, 8900, 50, 300)); p.add(new Platform(handler, 500, 9200, 250, 50)); p.add(new Platform(handler, 450, 8950, 50, 300)); p.add(new Platform(handler, 1350, 9350, 200, 50)); p.add(new Platform(handler, 1400, 9100, 100, 50)); // item/powerup p.add(new Platform(handler, 500, 9500, 600, 50)); p.add(new Platform(handler, 200, 9750, 1200, 50)); p.add(new Platform(handler, 50, 9950, 150, 50)); // spikes p.add(new Platform(handler, 1400, 9950, 150, 50)); // spikes i.add(new Item(handler, 750, 9900, 100, 100, "Door", Assets.doorSprite)); p.add(new Platform(handler, 50, 10000, 1500, 50)); } @Override public void tick() { player.tick(); player.setOnGround(false); player.setAdjGround(false); player.setOnCeiling(false); player.setOnLeft(false); player.setOnRight(false); player.setPlatOnBottom(null); player.setPlatOnTop(null); player.setPlatOnLeft(null); player.setPlatOnRight(null); for (Platform plat: p) { if(Math.abs(plat.getY() - player.getY()) < 2 * handler.getHeight() || plat.getHeight() > handler.getHeight()){ if (Collision.isCollisionBottom(player, plat)) { player.setOnGround(true); player.setPlatOnBottom(plat); } if (Collision.isAdjacentBottom(player, plat)) { player.setAdjGround(true); player.setPlatOnBottom(plat); } if (Collision.isCollisionTop(player, plat)) { player.setOnCeiling(true); player.setPlatOnTop(plat); } if (Collision.isCollisionLeft(player, plat)) { player.setOnLeft(true); player.setPlatOnLeft(plat); } if (Collision.isCollisionRight(player, plat)) { player.setOnRight(true); player.setPlatOnRight(plat); } plat.tick(); } } ArrayList<Item> itemp = new ArrayList<Item>(100); for (Item item:i) { if(Collision.isCollision(player, item)) { player.addPower(item.getName()); //i.remove(item); if(item.getName().equals("Door")) { itemp.add(item); } } else{ itemp.add(item); } } i = itemp; } @Override public void render(Graphics g, double xOffset, double yOffset) { //background.render(g, xOffset, yOffset); player.render(g, xOffset, yOffset); for (Platform plat:p) { if(Math.abs(plat.getY() - player.getY()) < 2 * handler.getHeight() || plat.getHeight() > handler.getHeight()){ plat.render(g, xOffset, yOffset); } } for(Item item: i) { item.render(g, xOffset, yOffset); } Font font = new Font("Verdana", Font.BOLD, 14); g.setFont(font); g.setColor(Color.RED); g.drawString("Enter Hell. No Return.", (int)(710 - xOffset), (int)(5300 - yOffset)); if(player.gameWon) { Font endfont = new Font("Verdana", Font.BOLD, 50); g.setFont(endfont); g.drawString("YOU WIN", handler.getWidth()/2, handler.getHeight()/2); } } } <file_sep>package main.gfx; public class GameCamera { private double xOffset, yOffset; public GameCamera(double xOffset, double yOffset) { this.xOffset = xOffset; this.xOffset = yOffset; } public void move(double xAmt, double yAmt) { xOffset += xAmt; yOffset += yAmt; } public double getxOffset() { return xOffset; } public void setxOffset(double xOffset) { this.xOffset = xOffset; } public double getyOffset() { return yOffset; } public void setyOffset(double yOffset) { this.yOffset = yOffset; } } <file_sep>package main; import main.display.Display; public class Laucher { public static void main(String[] args) { Game game = new Game("WhatGoesUp", 1200, 600); game.start(); } } <file_sep>package main.entities.creatures; import java.awt.Color; import java.awt.Graphics; import main.Handler; import main.collisions.Collision; import main.entities.platforms.Platform; public class Enemy extends Creature{ Platform platform; public Enemy(Handler handler, int width, int height, double speed, Platform platform) { super(handler, platform.getX() + platform.getWidth()/2 - width, platform.getY() - height, width, height); this.speed = speed; this.platform = platform; xMove = speed; } @Override public void tick() { adjGround = Collision.isAdjacentBottom(this, platform); /*if(!adjGround) { yMove = 0; y = platform.getY() - this.getHeight(); x = platform.getX() + platform.getWidth()/2 - width; System.out.println("reset"); }*/ //normal ground state(slightly above the platform) if(adjGround) { //System.out.println("Normal"); if(platform.getX() >= x) { //System.out.println("lefth"); xMove = speed; } else if(platform.getX() + platform.getWidth() <= x + width) { //System.out.println("righth"); xMove = -speed; } } xMove += platform.xMove; move(); xMove -= platform.xMove; } @Override public void render(Graphics g, double xOffset, double yOffset) { g.setColor(Color.RED); g.fillRect((int)(x + 1 - xOffset), (int)(y + 1 - yOffset), width, height); } }
a7881e48302d9a6e8b228a2094e877cba0740d5a
[ "Java" ]
7
Java
smhurt/WhatGoesUpRep
b6a035777ba72303b2f0a58d2764847b17ae06f1
61c4459a672dd616ab90b3e8b2f8934f80bd22df
refs/heads/master
<repo_name>thinker1017/MyCrawler<file_sep>/src/main/java/com/tcl/crawler/indexer/Searcher.java package com.tcl.crawler.indexer; import java.io.File; import java.io.IOException; import java.util.LinkedList; import org.apache.log4j.Logger; import org.apache.lucene.index.IndexReader; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; import org.apache.lucene.document.Document; import org.wltea.analyzer.lucene.IKAnalyzer; import com.tcl.crawler.Classifier.BayesClassifier; import com.tcl.crawler.model.PagePOJO; public class Searcher { private Logger logger = Logger.getLogger(this.getClass()); private String indexField; private String docDirectory; /** * @param indexField * the indexfile * @param queryString * the queryString * @return list a list of url */ public Searcher(String docDirectory, String indexField) { this.docDirectory = docDirectory; this.indexField = indexField; } public LinkedList<Hit> search(String queryString, boolean classify,int topDocs) { LinkedList<Hit> hits = new LinkedList<Hit>(); try { File path = new File(indexField); Directory directory = FSDirectory.open(path); IndexReader reader = IndexReader.open(directory); IndexSearcher seacher = new IndexSearcher(reader); QueryParser query = new QueryParser(Version.LUCENE_35, "content", new IKAnalyzer()); Query q = query.parse(queryString); TopDocs td = seacher.search(q, topDocs); ScoreDoc[] sds = td.scoreDocs; for (ScoreDoc sd : sds) { Hit hit = new Hit(); Document d = seacher.doc(sd.doc); hit.setFileName(d.get("filename")); hit.setStartOffset(Long.valueOf(d.get("startOffset"))); PagePOJO pojo = JsonReader.read(new File(docDirectory + File.separator + hit.getFileName()), hit.getStartOffset()); if (pojo == null) { hit = null; pojo = null; continue; } hit.setPagePOJO(pojo); if (classify) { hit.setClazz(BayesClassifier.getInstance().classify( hit.getPagePOJO().getContent()));// 写入类别 } hits.add(hit); } seacher.close(); } catch (IOException e) { logger.error(e.getMessage()); } catch (ParseException e) { logger.error(e.getMessage()); } return hits; } } <file_sep>/src/main/java/com/tcl/crawler/linkDB/LinkDB.java package com.tcl.crawler.linkDB; public class LinkDB { } <file_sep>/src/main/java/com/tcl/crawler/utils/URL.java package com.tcl.crawler.utils; public class URL { public String url; public int level; public URL(String url, int level) { this.level = level; this.url = url; } public URL() {} @Override public String toString() { return "URL [" + (url != null ? "url=" + url + ", " : "") + "level=" + level + "]"; } } <file_sep>/src/main/java/com/tcl/crawler/crawler/NewsCenter.java package com.tcl.crawler.crawler; public enum NewsCenter { Tencent,WangYiWap,Sina, Unknow } <file_sep>/src/main/java/com/tcl/crawler/extractor/LinkExtractor.java package com.tcl.crawler.extractor; import java.util.Set; import com.tcl.crawler.utils.URL; /** * @packageName com.tcl.crawler.extractor */ public interface LinkExtractor { public Set<URL> extractFromHtml(String html, final int level); }
87291c5f6435687af808547e6b62692c1221922f
[ "Java" ]
5
Java
thinker1017/MyCrawler
4c53169a24854de40dd837c6f60e476c8506f6f3
1e68f7cf2be44816beac674b154e2faaec5ae30d
refs/heads/main
<file_sep>local VOXEL_SIZE = 4 local Terrain = workspace:FindFirstChildWhichIsA("Terrain") local TerrainUtils = {} function TerrainUtils.cellPositionToWorld(pos) return pos * VOXEL_SIZE end function TerrainUtils.getMaterialAtPosition(pos, preferSolid) local minCorner local maxCorner if preferSolid then minCorner = Terrain:WorldToCellPreferSolid(pos) else minCorner = Terrain:WorldToCell(pos) end maxCorner = TerrainUtils.cellPositionToWorld(minCorner + Vector3.new(1, 1, 1)) minCorner = TerrainUtils.cellPositionToWorld(minCorner) return Terrain:ReadVoxels(Region3.new(minCorner, maxCorner), VOXEL_SIZE)[1][1][1] end return TerrainUtils<file_sep># RbxUtils <file_sep>type Lerpable = Vector2 | Vector3 | CFrame | Color3 local MathUtils = {} -- Golden Ratio MathUtils.phi = (math.sqrt(5) + 1) / 2 -- Golden Angle in radians MathUtils.ga = math.pi * (3 - math.sqrt(5)) -- @param x: number/vector3/vector2 to round -- @param accuracy: number to round x to function MathUtils.round(x: number, accuracy: number): number return math.round(x / accuracy) * accuracy end function MathUtils.ceil(x: number, accuracy: number): number return math.ceil(x / accuracy) * accuracy end function MathUtils.floor(x: number, accuracy: number): number return math.floor(x / accuracy) * accuracy end -- Not reccomended to use this if hard-coded values are possible function MathUtils.factorial(x: number): number local output = 1 for i = 1, x do output *= i end return output end function MathUtils.lerp(a: Lerpable, b: Lerpable, c: number): Lerpable local typeA, typeB = typeof(a), typeof(b) assert(typeA == typeB, ("Type mismatch between %s and %s, same type expected"):format(typeA, typeB)) if typeA == "Vector2" or typeA == "Vector3" or typeA == "CFrame" then return a:Lerp(b, c) elseif typeA == "Color3" then return Color3.new( MathUtils.lerp(a.r, b.r, c), MathUtils.lerp(a.g, b.g, c), MathUtils.lerp(a.b, b.b, c) ) else return a + (b - a) * c end end function MathUtils.factors(x: number): {number} local factors = {} local sqrtx = math.sqrt(x) for i = 1, sqrtx do if x % i == 0 then table.insert(factors, i) if i ~= sqrtx then table.insert(factors, x / i) end end end table.sort(factors) return factors end function MathUtils.isPrime(x: number): boolean for i = 2, math.sqrt(x) do if x % i == 0 then return false end end return true end -- Returns the closest number to 'x' from a table of numbers function MathUtils.snap(x: number, numbers: {number}, snapUp: boolean?) local bestMatch = numbers[1] local diff = math.abs(x - numbers[1]) for i = 2, #numbers do local v = numbers[i] local testDiff = math.abs(x - v) if testDiff < diff then bestMatch = v diff = testDiff end end if snapUp and bestMatch < x then return numbers[table.find(numbers, bestMatch) + 1] end return bestMatch end return MathUtils<file_sep>local StarterGui = game:GetService("StarterGui") local RaycastUtils = require(script.Parent.RaycastUtils) local ScreenUtils = {} function ScreenUtils.getTargetAtPosition(x: number, y: number, depth: number?, raycastParams: RaycastParams?): RaycastResult? local ray = workspace.CurrentCamera:ViewportPointToRay(x, y) local result = RaycastUtils.cast(ray.Origin, ray.Direction * (depth or 500), raycastParams) if result then return result end end function ScreenUtils.getGuiObjectsAtPosition(x: number, y: number, filter, recursive: boolean?) local objects = StarterGui:GetGuiObjectsAtPosition(x, y) if filter then local filteredObjects = {} for _,v1 in pairs(objects) do -- Quick search if object is in filter if table.find(filter, v1) then table.insert(filteredObjects, v1) continue end -- Deep search if object is a descendant if recursive then for _,v2 in pairs(filter) do if v1 == v2 or v1:IsDescendantOf(v2) then table.insert(filteredObjects, v1) end end end end return filteredObjects else return objects end end return ScreenUtils<file_sep>type List = {any} type Array<T> = {T} type Dictionary<A, B> = {[A]: B} local TableUtils = {} function TableUtils.shallowCopy(tab: Dictionary<any, any>): Dictionary<any, any> local copy = {} for i, v in pairs(tab) do copy[i] = v end return copy end function TableUtils.deepCopy(tab: Dictionary<any, any>): Dictionary<any, any> local copy = {} for i, v in pairs(tab) do if type(v) == "table" then v = TableUtils.deepCopy(v) end copy[i] = v end return copy end function TableUtils.keys(tab: Dictionary<any, any>): Array<string> local keys = {} for i in pairs(tab) do table.insert(keys, i) end return keys end function TableUtils.values(tab: Dictionary<any, any>): List local values = {} for _,v in pairs(tab) do table.insert(values, v) end return values end function TableUtils.isEmpty(tab: Dictionary<any, any>): boolean for _ in pairs(tab) do return false end return true end -- Behaves differently from table.create(), if the value is a empty table then the tables will not share the same memory address function TableUtils.create(count: number, value: any): Dictionary<any, any> if type(value) == "table" and TableUtils.isEmpty(value) then local tab = {} for _ = 1, count do table.insert(tab, {}) end return tab else return table.create(count, value) end end -- Merges dictionaries together, for merging arrays use {TableUtils.unpack(...)} function TableUtils.merge(...): Dictionary<any, any> local mergedTab = {} for _,tab in pairs({...}) do for i,v in pairs(tab) do mergedTab[i] = v end end return mergedTab end -- Allows unpacking of multiple tables function TableUtils.unpack(...) local packedTab = {} for _,tab in pairs({...}) do for _,v in pairs(tab) do table.insert(packedTab, v) end end return unpack(packedTab) end function TableUtils.remove(tab: List, index: number): nil if type(index) == "number" then tab[index] = nil else local i = table.find(tab, index) if i then table.remove(tab, i) end end end function TableUtils.select(tab: List, indexStart: number, indexEnd: number): List indexEnd = indexEnd or #tab local output = {} for i = indexStart, indexEnd do table.insert(output, tab[i]) end return output end -- Returns the sum of a array of numbers function TableUtils.sum(tab: List): number local sum = tab[1] for i = 2, #tab do sum += tab[i] end return sum end -- Returns the average of a array of numbers function TableUtils.avg(tab: List): number return TableUtils.sum(tab) / #tab end return TableUtils<file_sep>--# selene: allow(shadowing) -- https://github.com/OpenPrograms/LibCompress/blob/master/LibCompress.lua local type = type local select = select local next = next local setmetatable = setmetatable local table_insert = table.insert local table_remove = table.remove local table_concat = table.concat local string_char = string.char local string_byte = string.byte local string_len = string.len local string_sub = string.sub local pairs = pairs local bit_band = bit32.band local bit_bor = bit32.bor local bit_lshift = bit32.lshift local bit_rshift = bit32.rshift local tables = {} -- tables that may be cleaned have to be kept here local tables_to_clean = {} -- list of tables by name (string) that may be reset to {} after a timeout local function setCleanupTables(...) for i=1,select("#",...) do tables_to_clean[(select(i, ...))] = true end end local function addCode(tree, bcode,len) if tree then tree.bcode = bcode; tree.blength = len; if tree.c1 then addCode(tree.c1, bit_bor(bcode, bit_lshift(1,len)), len+1) end if tree.c2 then addCode(tree.c2, bcode, len+1) end end end local function escape_code(code, len) local escaped_code = 0; local b; local l = 0; for i = len-1, 0,- 1 do b = bit_band( code, bit_lshift(1,i))==0 and 0 or 1 escaped_code = bit_lshift(escaped_code,1+b) + b l = l + b; end return escaped_code, len+l end tables.Huffman_compressed = {} tables.Huffman_large_compressed = {} local compressed_size = 0 local remainder; local remainder_length; local function addBits(tbl, code, len) remainder = remainder + bit_lshift(code, remainder_length) remainder_length = len + remainder_length if remainder_length > 32 then return true -- Bits lost due to too long code-words. end while remainder_length>=8 do compressed_size = compressed_size + 1 tbl[compressed_size] = string_char(bit_band(remainder, 255)) remainder = bit_rshift(remainder, 8) remainder_length = remainder_length -8 end end -- word size for this huffman algorithm is 8 bits (1 byte). This means the best compression is representing 1 byte with 1 bit, i.e. compress to 0.125 of original size. function compress(uncompressed) if not type(uncompressed)=="string" then return nil, "Can only compress strings" end if #uncompressed == 0 then return "\001" end -- make histogram local hist = {} -- dont have to use all datat to make the histogram local uncompressed_size = string_len(uncompressed) local c; for i = 1, uncompressed_size do c = string_byte(uncompressed, i) hist[c] = (hist[c] or 0) + 1 end --Start with as many leaves as there are symbols. local leafs = {} local leaf; local symbols = {} for symbol, weight in pairs(hist) do leaf = { symbol=string_char(symbol), weight=weight }; symbols[symbol] = leaf; table_insert(leafs, leaf) end --Enqueue all leaf nodes into the first queue (by probability in increasing order so that the least likely item is in the head of the queue). table.sort(leafs, function(a,b) if a.weight < b.weight then return true elseif a.weight > b.weight then return false else return nil end end) local nLeafs = #leafs -- create tree local huff = {} --While there is more than one node in the queues: local l,h, li, hi, leaf1, leaf2 local newNode; while #leafs+#huff > 1 do -- Dequeue the two nodes with the lowest weight. -- Dequeue first if not next(huff) then li, leaf1 = next(leafs) table_remove(leafs, li) elseif not next(leafs) then hi, leaf1 = next(huff) table_remove(huff, hi) else li, l = next(leafs); hi, h = next(huff); if l.weight<=h.weight then leaf1 = l; table_remove(leafs, li) else leaf1 = h; table_remove(huff, hi) end end -- Dequeue second if not next(huff) then li, leaf2 = next(leafs) table_remove(leafs, li) elseif not next(leafs) then hi, leaf2 = next(huff) table_remove(huff, hi) else li, l = next(leafs); hi, h = next(huff); if l.weight<=h.weight then leaf2 = l; table_remove(leafs, li) else leaf2 = h; table_remove(huff, hi) end end --Create a new internal node, with the two just-removed nodes as children (either node can be either child) and the sum of their weights as the new weight. newNode = { c1 = leaf1, c2 = leaf2, weight = leaf1.weight+leaf2.weight } table_insert(huff,newNode) end if #leafs>0 then li, l = next(leafs) table_insert(huff, l) table_remove(leafs, li) end huff = huff[1]; -- assign codes to each symbol -- c1 = "0", c2 = "1" -- As a common convention, bit '0' represents following the left child and bit '1' represents following the right child. -- c1 = left, c2 = right addCode(huff,0,0); if huff then huff.bcode = 0 huff.blength = 1 end -- READING -- bitfield = 0 -- bitfield_len = 0 -- read byte1 -- bitfield = bitfield + bit_lshift(byte1, bitfield_len) -- bitfield_len = bitfield_len + 8 -- read byte2 -- bitfield = bitfield + bit_lshift(byte2, bitfield_len) -- bitfield_len = bitfield_len + 8 -- (use 5 bits) -- word = bit_band( bitfield, bit_lshift(1,5)-1) -- bitfield = bit_rshift( bitfield, 5) -- bitfield_len = bitfield_len - 5 -- read byte3 -- bitfield = bitfield + bit_lshift(byte3, bitfield_len) -- bitfield_len = bitfield_len + 8 -- WRITING remainder = 0; remainder_length = 0; local compressed = tables.Huffman_compressed --compressed_size = 0 -- first byte is version info. 0 = uncompressed, 1 = 8-bit word huffman compressed compressed[1] = "\003" -- Header: byte 0=#leafs, byte 1-3=size of uncompressed data -- max 2^24 bytes local l = string_len(uncompressed) compressed[2] = string_char(bit_band(nLeafs-1, 255)) -- number of leafs compressed[3] = string_char(bit_band(l, 255)) -- bit 0-7 compressed[4] = string_char(bit_band(bit_rshift(l, 8), 255)) -- bit 8-15 compressed[5] = string_char(bit_band(bit_rshift(l, 16), 255)) -- bit 16-23 compressed_size = 5 -- create symbol/code map for symbol, leaf in pairs(symbols) do addBits(compressed, symbol, 8); if addBits(compressed, escape_code(leaf.bcode, leaf.blength)) then -- code word too long. Needs new revision to be able to handle more than 32 bits return string_char(0)..uncompressed end addBits(compressed, 3, 2); end -- create huffman code local large_compressed = tables.Huffman_large_compressed local large_compressed_size = 0 local ulimit for i = 1, l, 200 do ulimit = l<(i+199) and l or (i+199) for sub_i = i, ulimit do c = string_byte(uncompressed, sub_i) addBits(compressed, symbols[c].bcode, symbols[c].blength) end large_compressed_size = large_compressed_size + 1 large_compressed[large_compressed_size] = table_concat(compressed, "", 1, compressed_size) compressed_size = 0 end -- add remainding bits (if any) if remainder_length>0 then large_compressed_size = large_compressed_size + 1 large_compressed[large_compressed_size] = string_char(remainder) end local compressed_string = table_concat(large_compressed, "", 1, large_compressed_size) -- is compression worth it? If not, return uncompressed data. if (#uncompressed+1) <= #compressed_string then return "\001"..uncompressed end setCleanupTables("Huffman_compressed", "Huffman_large_compressed") return compressed_string end -- lookuptable (cached between calls) local lshiftMask = {} setmetatable(lshiftMask, { __index = function (t, k) local v = bit_lshift(1, k) rawset(t, k, v) return v end }) -- lookuptable (cached between calls) local lshiftMinusOneMask = {} setmetatable(lshiftMinusOneMask, { __index = function (t, k) local v = bit_lshift(1, k)-1 rawset(t, k, v) return v end }) local function getCode(bitfield, field_len) if field_len>=2 then local b; local p = 0; for i = 0, field_len-1 do b = bit_band(bitfield, lshiftMask[i]) if not (p==0) and not (b == 0) then -- found 2 bits set right after each other (stop bits) return bit_band( bitfield, lshiftMinusOneMask[i-1]), i-1, bit_rshift(bitfield, i+1), field_len-i-1 end p = b end end return nil end local function unescape_code(code, code_len) local unescaped_code=0; local b; local l = 0; local i = 0 while i < code_len do b = bit_band( code, lshiftMask[i]) if not (b==0) then unescaped_code = bit_bor(unescaped_code, lshiftMask[l]) i = i + 1 end i = i + 1 l = l + 1 end return unescaped_code, l end tables.Huffman_uncompressed = {} tables.Huffman_large_uncompressed = {} -- will always be as big as the larges string ever decompressed. Bad, but clearing i every timetakes precious time. function decompress(compressed) local uncompressed = tables.Huffman_uncompressed local large_uncompressed = tables.Huffman_large_uncompressed if not type(uncompressed)=="string" then return nil, "Can only uncompress strings" end local compressed_size = #compressed --decode header local info_byte = string_byte(compressed) -- is data compressed if info_byte==1 then return compressed:sub(2) --return uncompressed data end if not (info_byte==3) then return nil, "Can only decompress Huffman compressed data ("..tostring(info_byte)..")" end local num_symbols = string_byte(string_sub(compressed, 2, 2)) + 1 local c0 = string_byte(string_sub(compressed, 3, 3)) local c1 = string_byte(string_sub(compressed, 4, 4)) local c2 = string_byte(string_sub(compressed, 5, 5)) local orig_size = c2*65536 + c1*256 + c0 if orig_size==0 then return ""; end -- decode code->symbal map local bitfield = 0; local bitfield_len = 0; local map = {} -- only table not reused in Huffman decode. setmetatable(map, { __index = function (t, k) local v = {} rawset(t, k, v) return v end }) local i = 6; -- byte 1-5 are header bytes local c, cl; local minCodeLen = 1000; local maxCodeLen = 0; local symbol, code, code_len, _bitfield, _bitfield_len; local n = 0; local state = 0; -- 0 = get symbol (8 bits), 1 = get code (varying bits, ends with 2 bits set) while n<num_symbols do if i>compressed_size then return nil, "Cannot decode map" end c = string_byte(compressed, i) bitfield = bit_bor(bitfield, bit_lshift(c, bitfield_len)) bitfield_len = bitfield_len + 8 if state == 0 then symbol = bit_band(bitfield, 255) bitfield = bit_rshift(bitfield, 8) bitfield_len = bitfield_len -8 state = 1 -- search for code now else code, code_len, _bitfield, _bitfield_len = getCode(bitfield, bitfield_len) if code then bitfield, bitfield_len = _bitfield, _bitfield_len c, cl = unescape_code(code, code_len) map[cl][c]=string_char(symbol) minCodeLen = cl<minCodeLen and cl or minCodeLen maxCodeLen = cl>maxCodeLen and cl or maxCodeLen --print("symbol: "..string_char(symbol).." code: "..tobinary(c, cl)) n = n + 1 state = 0 -- search for next symbol (if any) end end i=i+1 end -- dont create new subtables for entries not in the map. Waste of space. -- But do return an empty table to prevent runtime errors. (instead of returning nil) local mt = {} setmetatable(map, { __index = function() return mt end }) local uncompressed_size = 0 local large_uncompressed_size = 0 local test_code local test_code_len = minCodeLen; local symbol; local dec_size = 0; compressed_size = compressed_size + 1 local temp_limit = 200; -- first limit of uncompressed data. large_uncompressed will hold strings of length 200 temp_limit = temp_limit > orig_size and orig_size or temp_limit while true do if test_code_len<=bitfield_len then test_code=bit_band( bitfield, lshiftMinusOneMask[test_code_len]) symbol = map[test_code_len][test_code] if symbol then uncompressed_size = uncompressed_size + 1 uncompressed[uncompressed_size]=symbol dec_size = dec_size + 1 if dec_size >= temp_limit then if dec_size>=orig_size then -- checked here for speed reasons break; end -- process compressed bytes in smaller chunks large_uncompressed_size = large_uncompressed_size + 1 large_uncompressed[large_uncompressed_size] = table_concat(uncompressed, "", 1, uncompressed_size) uncompressed_size = 0 temp_limit = temp_limit + 200 -- repeated chunk size is 200 uncompressed bytes temp_limit = temp_limit > orig_size and orig_size or temp_limit end bitfield = bit_rshift(bitfield, test_code_len) bitfield_len = bitfield_len - test_code_len test_code_len = minCodeLen else test_code_len = test_code_len + 1 if test_code_len>maxCodeLen then return nil, "Decompression error at "..tostring(i).."/"..tostring(#compressed) end end else c = string_byte(compressed, i) bitfield = bitfield + bit_lshift(c or 0, bitfield_len) bitfield_len = bitfield_len + 8 if i > compressed_size then break; end i = i + 1 end end setCleanupTables("Huffman_uncompressed", "Huffman_large_uncompressed") return table_concat(large_uncompressed, "", 1, large_uncompressed_size)..table_concat(uncompressed, "", 1, uncompressed_size) end return { compress = compress, decompress = decompress, }<file_sep>return { Huffman = require(script.Huffman), LZW = require(script.LZW), }<file_sep>local CFrameUtils = {} function CFrameUtils.fromOriginDir(origin: Vector3, dir: Vector3, up: Vector3?): CFrame if up then return CFrame.lookAt(origin, origin + dir, up) else return CFrame.lookAt(origin, origin + dir) end end return CFrameUtils<file_sep>local PartUtils = {} function PartUtils.anchor(model: Model): nil for _,part in ipairs(PartUtils.getDescendantsOfClass(model, "BasePart")) do part.Anchored = true end end function PartUtils.unanchor(model: Model): nil for _,part in ipairs(PartUtils.getDescendantsOfClass(model, "BasePart")) do part.Anchored = false end end function PartUtils.weld(main: BasePart, ...): nil local parts = {...} for _,part in ipairs(parts) do if part ~= main then local weld = Instance.new("WeldConstraint") weld.Part0 = main weld.Part1 = part weld.Parent = part end end end function PartUtils.makeMotor6D(part0, part1) local motor6D = Instance.new("Motor6D") motor6D.Part0 = part0 motor6D.Part1 = part1 motor6D.Parent = part0 return motor6D end function PartUtils.getChildrenOfClass(container: Instance, class: string) local instances = {} for _,instance in ipairs(container:GetChildren()) do if instance:IsA(class) then table.insert(instances, instance) end end return instances end function PartUtils.getDescendantsOfClass(container: Instance, class: string) local instances = {} for _,instance in ipairs(container:GetDescendants()) do if instance:IsA(class) then table.insert(instances, instance) end end return instances end return PartUtils<file_sep>[package] name = "raphtalia/rbxutils" description = "Library with general purpose utility functions" version = "1.0.0" license = "MIT" registry = "https://github.com/UpliftGames/wally-index" realm = "shared" [dependencies] <file_sep>local ColorUtils = {} -- ExtraContent/LuaPackages/AppTempCommon function ColorUtils.rgbFromHex(hexColor) assert(hexColor >= 0 and hexColor <= 0xffffff, "RgbFromHex: Out of range") local b = hexColor % 256 hexColor = (hexColor - b) / 256 local g = hexColor % 256 hexColor = (hexColor - g) / 256 local r = hexColor return r, g, b end function ColorUtils.color3FromHex(hexColor) return Color3.fromRGB(ColorUtils.rgbFromHex(hexColor)) end function ColorUtils.color3ToHex(color) return math.floor(color.R * 255) *256^2 + math.floor(color.G * 255) * 256 + math.floor(color.B * 255) end function ColorUtils.add(color0, color1) if type(color1) == "number" then color1 = Color3.new(color1, color1, color1) end return Color3.new( math.min(color0.R + color1.R, 1), math.min(color0.G + color1.G, 1), math.min(color0.B + color1.B, 1) ) end function ColorUtils.multiply(color0, color1) if type(color1) == "number" then color1 = Color3.new(color1, color1, color1) end return Color3.new( math.min(color0.R * color1.R, 1), math.min(color0.G * color1.G, 1), math.min(color0.B * color1.B, 1) ) end function ColorUtils.pow(color0, color1) if type(color1) == "number" then color1 = Color3.new(color1, color1, color1) end return Color3.new( math.min(color0.R ^ color1.R, 1), math.min(color0.G ^ color1.G, 1), math.min(color0.B ^ color1.B, 1) ) end return ColorUtils<file_sep>type RaycastParamsTable = typeof({ FilterDescendantsInstances = {}, FilterType = Enum.RaycastFilterType.Blacklist, IgnoreWater = false, CollisionGroup = "Default", }) local DEFAULT_PARAMS = RaycastParams.new() local RaycastUtils = {} local function filterCollideOnly(instance) return instance.CanCollide end function RaycastUtils.make(params: RaycastParamsTable): RaycastParams local raycastParams = RaycastParams.new() if params.IgnoreWater == nil then params.IgnoreWater = raycastParams.IgnoreWater end raycastParams.FilterDescendantsInstances = params.FilterDescendantsInstances or raycastParams.FilterDescendantsInstances raycastParams.FilterType = params.FilterType or raycastParams.FilterType raycastParams.IgnoreWater = params.IgnoreWater raycastParams.CollisionGroup = params.CollisionGroup or raycastParams.CollisionGroup return raycastParams end -- Clones a new RaycastParams with the same properties function RaycastUtils.copy(raycastParams: RaycastParams): RaycastParams local copyRaycastParams = RaycastParams.new() copyRaycastParams.FilterDescendantsInstances = raycastParams.FilterDescendantsInstances copyRaycastParams.FilterType = raycastParams.FilterType copyRaycastParams.IgnoreWater = raycastParams.IgnoreWater copyRaycastParams.CollisionGroup = raycastParams.CollisionGroup return copyRaycastParams end -- Behaves like the old raycast function function RaycastUtils.cast(origin: Vector3, dir: Vector3, params: RaycastParams?): RaycastResult return workspace:Raycast(origin, dir, params or DEFAULT_PARAMS) end -- Returns instance that meets filter requirement function RaycastUtils.castWithFilter(origin: Vector3, dir: Vector3, filter: any, params: RaycastParams?): RaycastResult params = params or DEFAULT_PARAMS local originalFilter = params.FilterDescendantsInstances local tempFilter = params.FilterDescendantsInstances repeat local result = workspace:Raycast(origin, dir, params) if result then if filter(result.Instance) then params.FilterDescendantsInstances = originalFilter return result else table.insert(tempFilter, result.Instance) params.FilterDescendantsInstances = tempFilter origin = result.Position dir = dir.Unit * (dir.Magnitude - (origin - result.Position).Magnitude) end else params.FilterDescendantsInstances = originalFilter return nil end until not result end -- Cast ignores parts that are CanCollide Off function RaycastUtils.castCollideOnly(origin: Vector3, dir: Vector3, params: RaycastParams?): RaycastResult return RaycastUtils.castWithFilter( origin, dir, filterCollideOnly, params ) end return RaycastUtils<file_sep>local Vector3Utils = {} function Vector3Utils.clamp(vector: Vector3, min: number, max: number): Vector3 min = min or Vector3.new(-math.huge, -math.huge, -math.huge) max = max or Vector3.new(math.huge, math.huge, math.huge) if type(min) == "number" then min = Vector3.new(min, min, min) end if type(max) == "number" then max = Vector3.new(max, max, max) end if typeof(vector) == "Vector3" then return Vector3.new(math.clamp(vector.X, min.X, max.X), math.clamp(vector.Y, min.Y, max.Y), math.clamp(vector.Z, min.Z, max.Z)) else return Vector2.new(math.clamp(vector.X, min.X, max.X), math.clamp(vector.Y, min.Y, max.Y)) end end function Vector3Utils.llarToWorld(lat: number, lon: number, alt: number?, rad: number?): Vector3 -- https://stackoverflow.com/questions/10473852/convert-latitude-and-longitude-to-point-in-3d-space alt = alt or 0 rad = rad or 1 local ls = math.atan(math.tan(lat)) local x = rad * math.cos(ls) * math.cos(lon) + alt * math.cos(lat) * math.cos(lon) local y = rad * math.cos(ls) * math.sin(lon) + alt * math.cos(lat) * math.sin(lon) local z = rad * math.sin(ls) + alt * math.sin(lat) return Vector3.new(x, y, z) end function Vector3Utils.abs(v: Vector3): Vector3 return Vector3.new(math.abs(v.X), math.abs(v.Y), math.abs(v.Z)) end function Vector3Utils.angle(v1: Vector3, v2: Vector3): number v1 = v1 or Vector3.new() v2 = v2 or Vector3.new() return math.acos(v1:Dot(v2) / math.max(v1.Magnitude * v2.Magnitude, 0.00001)) end function Vector3Utils.reflect(dir: Vector3, normal: Vector3, pos: Vector3?) normal = normal.Unit pos = pos or Vector3.new() return dir - 2 * (dir * normal) * normal + pos end return Vector3Utils<file_sep>return { Codecs = require(script.Codecs), CFrame = require(script.CFrameUtils), Color = require(script.ColorUtils), JSON = require(script.JSONUtils), Math = require(script.MathUtils), Part = require(script.PartUtils), Raycast = require(script.RaycastUtils), Screen = require(script.ScreenUtils), Table = require(script.TableUtils), Terrain = require(script.TerrainUtils), Vector3 = require(script.Vector3Utils), }<file_sep>std="roblox" [config] shadowing = { ignore_pattern = "^(_|self)" }<file_sep>local TYPE_MARKER = "_T" local HttpService = game:GetService("HttpService") local Colors = require(script.Parent.ColorUtils) local JSON = {} function JSON.serializeTypes(data, typeMarker) typeMarker = typeMarker or TYPE_MARKER for i,v in pairs(data) do local type = typeof(v) if type == "table" then data[i] = JSON.serializeTypes(v, typeMarker) elseif type == "Vector2" then data[i] = { typeMarker, 1, v.X, v.Y, } elseif type == "Vector3" then data[i] = { typeMarker, 2, v.X, v.Y, v.Z, } elseif type == "CFrame" then -- This could be optimized to ignore orientation if there is none data[i] = { typeMarker, 3, v:GetComponents(), } elseif type == "Color3" then data[i] = { typeMarker, 4, Colors.color3ToHex(v), } elseif type == "BrickColor" then data[i] = { typeMarker, 5, v.Number, } elseif type == "ColorSequence" then data[i] = { typeMarker, 6, JSON.serializeTypes(v.Keypoints, typeMarker), } elseif type == "ColorSequenceKeypoint" then data[i] = { typeMarker, 7, v.Time, Colors.color3ToHex(v.Value, typeMarker), } elseif type == "NumberRange" then data[i] = { typeMarker, 8, v.Min, v.Max, } elseif type == "NumberSequence" then data[i] = { typeMarker, 9, JSON.serializeTypes(v.Keypoints, typeMarker), } elseif type == "NumberSequenceKeypoint" then -- This could be optimized to ignore envlope if it is 0 data[i] = { typeMarker, 10, v.Time, v.Value, v.Envelope, } elseif type == "UDim" then data[i] = { typeMarker, 11, v.Scale, v.Offset, } elseif type == "UDim2" then data[i] = { typeMarker, 12, v.X.Scale, v.X.Offset, v.Y.Scale, v.Y.Offset, } elseif type == "EnumItem" then data[i] = { typeMarker, 13, tostring(v.EnumType), v.Name, } end end return data end function JSON.deserializeTypes(data, typeMarker) typeMarker = typeMarker or TYPE_MARKER for i,v in pairs(data) do if type(v) == "table" then if v[1] == typeMarker then local type = v[2] v = {select(3, unpack(v))} v = #v == 1 and v[1] or v if type == 1 then -- Vector2 data[i] = Vector2.new(v[1], v[2]) elseif type == 2 then -- Vector3 data[i] = Vector3.new(v[1], v[2], v[3]) elseif type == 3 then -- CFrame data[i] = CFrame.new(v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12]) elseif type == 4 then -- Color3 data[i] = Colors.color3FromHex(v) elseif type == 5 then -- BrickColor data[i] = BrickColor.new(v) elseif type == 6 then -- ColorSequence data[i] = ColorSequence.new(JSON.deserializeTypes(v, typeMarker)) elseif type == 7 then -- ColorSequenceKeypoint data[i] = ColorSequenceKeypoint.new(v[1], Colors.color3FromHex(v[2])) elseif type == 8 then -- NumberRange data[i] = NumberRange.new(v[1], v[2]) elseif type == 9 then -- NumberSequence data[i] = NumberSequence.new(JSON.deserializeTypes(v, typeMarker)) elseif type == 10 then -- NumberSequenceKeypoint data[i] = NumberSequenceKeypoint.new(v[1], v[2], v[3]) elseif type == 11 then -- UDim data[i] = UDim.new(v[1], v[2]) elseif type == 12 then -- UDim2 data[i] = UDim2.new(v[1], v[2], v[3], v[4]) elseif type == 13 then data[i] = Enum[v[1]][v[2]] end else data[i] = JSON.deserializeTypes(v, typeMarker) end end end return data end function JSON.serialize(data, typeMarker) return HttpService:JSONEncode( JSON.serializeTypes( data, typeMarker or TYPE_MARKER ) ) end function JSON.deserialize(data, typeMarker) return JSON.deserializeTypes( HttpService:JSONDecode(data), typeMarker or TYPE_MARKER ) end function JSON.isJSON(str) local success = pcall(JSON.deserialize, str) return success end return JSON
08cb5b18bf1107fcae6de3c30e1e6778f815feb4
[ "Markdown", "TOML", "Lua" ]
16
Lua
raphtalia/RbxUtils
9b8d21c64db406bc6994573020659fc10a5ed2bc
c1d4336af766e2c438f360771ffa96dbcaa1c319
refs/heads/main
<repo_name>Elteoremadebeethoven/pycairo-tutorial<file_sep>/_3_positions/_1_grid_example.py import os import sys sys.path.append(os.getcwd()) from imports import * IMAGE_CONFIG = { "width": 400, "height": 400, "scale": 1.2, "transparency": False, } class Shape(Figure): def on_draw(self, cr: cairo.Context): cr.set_source_rgb(1, 1, 1) self.set_grid() if __name__ == "__main__": app = Shape(**IMAGE_CONFIG) full_path = get_full_path_to_export(os,__file__) app.write(full_path)<file_sep>/_2_basic_figures/_1_rectangles.py import os import sys sys.path.append(os.getcwd()) from imports import * IMAGE_CONFIG = { "width": 800, "height": 800, "scale": 1, # default "transparency": True # default } class Shape(Figure): def on_draw(self, cr: cairo.Context): # ---- FIRST RECTANGLE # Set stroke width cr.set_line_width(40) # Set stroke color cr.set_source_rgb(1, 0.5, 0) # Set the figure # x y w h cr.rectangle(150, 80, 400, 500) cr.stroke_preserve() # With this line the stroke is not removed # Set the fill color cr.set_source_rgb(0, 0.5, 0.5) # Create the rectangle with fill and stroke cr.fill() # ----- SECOND RECTANGLE cr.rectangle(250, 50, 400, 600) cr.set_source_rgb(0.2, 0, 0) # Create rectangle as stroke cr.stroke() if __name__ == "__main__": app = Shape(**IMAGE_CONFIG) full_path = get_full_path_to_export(os,__file__) app.write(full_path) <file_sep>/_2_basic_figures/_3_shapes.py import os import sys sys.path.append(os.getcwd()) from imports import * IMAGE_CONFIG = { "width": 400, "height": 230, "scale": 1.8, "transparency": False, } class Shape(Figure): def on_draw(self, cr: cairo.Context): cr.set_source_rgb(1, 1, 1) cr.rectangle(20, 20, 120, 80) cr.rectangle(180, 20, 80, 80) cr.fill() cr.arc(330, 60, 40, 0, 2*PI) cr.fill() cr.arc(90, 160, 40, PI/4, PI) cr.fill() cr.translate(220, 180) cr.scale(1, 0.7) cr.arc(0, 0, 50, 0, 2*PI) cr.fill() if __name__ == "__main__": app = Shape(**IMAGE_CONFIG) full_path = get_full_path_to_export(os,__file__) app.write(full_path) <file_sep>/_1_formats/_2_pdf_surface.py import cairo import os FILE_NAME = os.path.basename(__file__) WIDTH = 500 HEIGHT = 300 # - Create surface PDF ps = cairo.PDFSurface(f"./exports/{FILE_NAME[:-3]}.pdf", WIDTH, HEIGHT) cr = cairo.Context(ps) # - Define color source cr.set_source_rgb(1, 0, 0) # ------ Text 1 # - Define some text - 1 cr.select_font_face( "Arial", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL ) # - Define font size cr.set_font_size(50) # - Define position cr.move_to(30, 50) # - Add text to context cr.show_text("Hello") # ------ Text 2 cr.select_font_face( "Noto Sans", cairo.FONT_SLANT_ITALIC, cairo.FONT_WEIGHT_BOLD ) cr.set_source_rgb(0, 1, 1) cr.move_to(100, 100) cr.show_text("World") cr.show_page() <file_sep>/_1_formats/_3_svg_surface.py import cairo import os FILE_NAME = os.path.basename(__file__) WIDTH = 500 HEIGHT = 300 ps = cairo.SVGSurface(f"./exports/{FILE_NAME[:-3]}.svg", WIDTH, HEIGHT) cr = cairo.Context(ps) # - Define color source cr.set_source_rgb(1, 0, 0) # ------ Text 1 # - Define some text - 1 cr.select_font_face( "Arial", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL ) # - Define font size cr.set_font_size(50) # - Define position cr.move_to(30, 50) # - Add text to context cr.show_text("Hello") # ------ Text 2 cr.select_font_face( "Noto Sans", cairo.FONT_SLANT_ITALIC, cairo.FONT_WEIGHT_BOLD ) cr.set_font_size(100) cr.set_source_rgb(1, 0, 1) cr.move_to(70, 130) cr.show_text("World") cr.show_page()<file_sep>/imports/basic_libs.py import cairo from math import pi as PI import numpy as np import sys<file_sep>/imports/__init__.py from .basic_libs import * from .figure_class import Figure from .funcs import *<file_sep>/_2_basic_figures/_4_lines.py import os import sys sys.path.append(os.getcwd()) from imports import * IMAGE_CONFIG = { "width": 800, "height": 260, "transparency": False, } class Shape(Figure): def on_draw(self, cr: cairo.Context): cr.set_source_rgb(1, 0, 0) cr.set_line_width(5) cr.save() cr.set_dash([8,16,24]) cr.move_to(40, 30) cr.line_to(750, 30) cr.stroke() cr.set_dash([14.0, 6.0]) cr.move_to(40, 130) cr.line_to(750, 130) cr.stroke() cr.restore() cr.move_to(40, 230) cr.line_to(750, 230) cr.stroke() if __name__ == "__main__": app = Shape(**IMAGE_CONFIG) full_path = get_full_path_to_export(os,__file__) app.write(full_path)<file_sep>/_2_basic_figures/_2_circles.py import os import sys sys.path.append(os.getcwd()) from imports import * IMAGE_CONFIG = { "width": 500, "height": 500, "scale": 1, } class Shape(Figure): def on_draw(self, cr: cairo.Context): w,h = self.width, self.height cr.set_line_width(20) cr.set_source_rgb(0.7, 0.2, 0.0) cr.arc( w/2, # x h/2, # y 100, # radius 0, # start angle 2*PI # end angle ) # Preserve the stroke cr.stroke_preserve() # Set the fill color cr.set_source_rgb(0.3, 0.4, 0.6) cr.fill() if __name__ == "__main__": app = Shape(**IMAGE_CONFIG) full_path = get_full_path_to_export(os,__file__) app.write(full_path) <file_sep>/_2_basic_figures/_5_line_caps.py import os import sys sys.path.append(os.getcwd()) from imports import * IMAGE_CONFIG = { "width": 180, "height": 180, "scale": 3, "transparency": False, } class Shape(Figure): def on_draw(self, cr: cairo.Context): cr.set_line_width(10) cr.set_source_rgb(1, 0, 0) cr.set_line_cap(cairo.LINE_CAP_BUTT) cr.move_to(30, 50) cr.line_to(150, 50) cr.stroke() cr.set_source_rgb(0, 1, 0) cr.set_line_cap(cairo.LINE_CAP_ROUND) cr.move_to(30, 90) cr.line_to(150, 90) cr.stroke() cr.set_source_rgb(0, 0, 1) cr.set_line_cap(cairo.LINE_CAP_SQUARE) cr.move_to(30, 130) cr.line_to(150, 130) cr.stroke() cr.set_source_rgba(1, 1, 1,0.5) cr.set_line_width(1) cr.move_to(30, 35) cr.line_to(30, 145) cr.stroke() cr.move_to(150, 35) cr.line_to(150, 145) cr.stroke() cr.move_to(155, 35) cr.line_to(155, 145) cr.stroke() if __name__ == "__main__": app = Shape(**IMAGE_CONFIG) full_path = get_full_path_to_export(os,__file__) app.write(full_path) <file_sep>/imports/funcs.py def get_full_path_to_export(os,file): # Get file full path path = os.path.dirname(os.path.realpath(file)) # Get folder name folder_name = os.path.basename(os.path.normpath(path)) # Get file name file_name = os.path.basename(file) # Get root folder current_file = os.getcwd() # Get exports folder path main_exports_folder = os.path.join(current_file, "exports") # Get exports + folder_name export_folder = os.path.join(main_exports_folder, folder_name) if not os.path.isdir(export_folder): os.makedirs(export_folder) full_path = os.path.join(export_folder, file_name) return full_path <file_sep>/imports/figure_class.py from .basic_libs import * class Figure: def __init__(self, width=400, height=400, scale=1, transparency=True): # Transparency config cf = cairo.FORMAT_ARGB32 if transparency else cairo.FORMAT_RGB24 # Define image surface ims = cairo.ImageSurface(cf, int(width*scale), int(height*scale)) # Create context cr = cairo.Context(ims) self.width, self.height = width, height self.cr = cr # Set scale cr.scale(scale,scale) # Draw (abstract method) self.on_draw(cr) self.ims = ims def on_draw(self, cr: cairo.Context): pass def write(self,full_path): self.ims.write_to_png(f"{full_path[:-2]}png") def get_context(self): return self.cr def set_grid(self, step=10, color=(1, 1, 1), stroke=1, opacity=0.3): cr = self.get_context() cr.set_source_rgba(*color,opacity) cr.set_line_width(stroke) for v, s in zip([(1,0),(0,1)],[self.width, self.height]): for i in np.arange(0, s+step, step): vector = np.array(v) * i end = vector + np.array(v)[::-1] * s cr.move_to(*vector) cr.line_to(*end) cr.stroke() <file_sep>/_1_formats/_1_image_surface.py import cairo import os FILE_NAME = os.path.basename(__file__) WIDTH = 390 HEIGHT = 60 # - Create surface ims = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT) # - Create context cr = cairo.Context(ims) # - Define color source cr.set_source_rgb(1, 0, 0) # ------ Text 1 # - Define some text - 1 cr.select_font_face( "Arial", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL ) # - Define font size cr.set_font_size(50) # - Define position cr.move_to(30, 50) # - Add text to context cr.show_text("Hello") # ------ Text 2 cr.select_font_face( "Noto Sans", cairo.FONT_SLANT_ITALIC, cairo.FONT_WEIGHT_NORMAL ) cr.set_source_rgb(1, 1, 0) cr.move_to(160, 50) cr.show_text("World") ims.write_to_png(f"./exports/{FILE_NAME[:-3]}.png") <file_sep>/_1_formats/README.md # Formats ## Image Surface ```python import cairo import os FILE_NAME = os.path.basename(__file__) WIDTH = 390 HEIGHT = 60 # - Create surface ims = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT) # - Create context cr = cairo.Context(ims) # - Define color source cr.set_source_rgb(1, 0, 0) # ------ Text 1 # - Define some text - 1 cr.select_font_face( "Arial", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL ) # - Define font size cr.set_font_size(50) # - Define position cr.move_to(30, 50) # - Add text to context cr.show_text("Hello") # ------ Text 2 cr.select_font_face( "Noto Sans", cairo.FONT_SLANT_ITALIC, cairo.FONT_WEIGHT_NORMAL ) cr.set_source_rgb(1, 1, 0) cr.move_to(160, 50) cr.show_text("World") ims.write_to_png(f"./exports/{FILE_NAME[:-3]}.png") ``` <p align="center"><img src ="../exports/_1_image_surface.png" /></p> ## PDF surface ```python import cairo import os FILE_NAME = os.path.basename(__file__) WIDTH = 500 HEIGHT = 300 # - Create surface PDF ps = cairo.PDFSurface(f"./exports/{FILE_NAME[:-3]}.pdf", WIDTH, HEIGHT) cr = cairo.Context(ps) # - Define color source cr.set_source_rgb(1, 0, 0) # ------ Text 1 # - Define some text - 1 cr.select_font_face( "Arial", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL ) # - Define font size cr.set_font_size(50) # - Define position cr.move_to(30, 50) # - Add text to context cr.show_text("Hello") # ------ Text 2 cr.select_font_face( "Noto Sans", cairo.FONT_SLANT_ITALIC, cairo.FONT_WEIGHT_BOLD ) cr.set_source_rgb(0, 1, 1) cr.move_to(100, 100) cr.show_text("World") cr.show_page() ``` ## SVG surface ```python import cairo import os FILE_NAME = os.path.basename(__file__) WIDTH = 500 HEIGHT = 300 ps = cairo.SVGSurface(f"./exports/{FILE_NAME[:-3]}.svg", WIDTH, HEIGHT) cr = cairo.Context(ps) # - Define color source cr.set_source_rgb(1, 0, 0) # ------ Text 1 # - Define some text - 1 cr.select_font_face( "Arial", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL ) # - Define font size cr.set_font_size(50) # - Define position cr.move_to(30, 50) # - Add text to context cr.show_text("Hello") # ------ Text 2 cr.select_font_face( "Noto Sans", cairo.FONT_SLANT_ITALIC, cairo.FONT_WEIGHT_BOLD ) cr.set_font_size(100) cr.set_source_rgb(1, 0, 1) cr.move_to(70, 130) cr.show_text("World") cr.show_page() ``` ## GTK (optional) ```python from gi.repository import Gtk import cairo # Installation: https://pygobject.readthedocs.io/en/latest/getting_started.html # Tutorial: https://zetcode.com/gfx/pycairo/backends/ ''' ZetCode PyCairo tutorial This program uses PyCairo to draw on a window in GTK. Author: <NAME> Website: zetcode.com ''' class Example(Gtk.Window): def __init__(self): super(Example, self).__init__() self.init_ui() def init_ui(self): darea = Gtk.DrawingArea() darea.connect("draw", self.on_draw) self.add(darea) self.set_title("My first GTK window") self.resize(420, 120) self.set_position(Gtk.WindowPosition.CENTER) self.connect("delete-event", Gtk.main_quit) self.show_all() def on_draw(self, wid, cr): cr.set_source_rgb(1, 0, 0) cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) cr.set_font_size(40) cr.move_to(60, 50) cr.show_text("Hello world") def main(): app = Example() Gtk.main() if __name__ == "__main__": main() ```<file_sep>/_2_basic_figures/_6_line_joins.py import os import sys sys.path.append(os.getcwd()) from imports import * IMAGE_CONFIG = { "width": 300, "height": 300, "scale": 1.8, "transparency": False, } class Shape(Figure): def on_draw(self, cr: cairo.Context): cr.set_line_width(14) cr.rectangle(30, 30, 100, 100) cr.set_line_join(cairo.LINE_JOIN_MITER) cr.set_source_rgb(1, 0, 0) cr.stroke() cr.rectangle(160, 30, 100, 100) cr.set_line_join(cairo.LINE_JOIN_BEVEL) cr.set_source_rgb(0, 1, 0) cr.stroke() cr.rectangle(100, 160, 100, 100) cr.set_line_join(cairo.LINE_JOIN_ROUND) cr.set_source_rgb(0, 0, 1) cr.stroke() if __name__ == "__main__": app = Shape(**IMAGE_CONFIG) full_path = get_full_path_to_export(os,__file__) app.write(full_path)<file_sep>/README.md # Main page Optional req: `PyGObject` Based on [this tutorial](https://zetcode.com/gfx/pycairo/) [Formats](./_1_formats/README.md) <file_sep>/_1_formats/_4_gtk_optional.py from gi.repository import Gtk import cairo # Installation: https://pygobject.readthedocs.io/en/latest/getting_started.html # Tutorial: https://zetcode.com/gfx/pycairo/backends/ ''' ZetCode PyCairo tutorial This program uses PyCairo to draw on a window in GTK. Author: <NAME> Website: zetcode.com ''' class Example(Gtk.Window): def __init__(self): super(Example, self).__init__() self.init_ui() def init_ui(self): darea = Gtk.DrawingArea() darea.connect("draw", self.on_draw) self.add(darea) self.set_title("My first GTK window") self.resize(420, 120) self.set_position(Gtk.WindowPosition.CENTER) self.connect("delete-event", Gtk.main_quit) self.show_all() def on_draw(self, wid, cr): cr.set_source_rgb(1, 0, 0) cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) cr.set_font_size(40) cr.move_to(60, 50) cr.show_text("Hello world") def main(): app = Example() Gtk.main() if __name__ == "__main__": main()
47d77ac69e242603fae579dd60889b890383ea23
[ "Markdown", "Python" ]
17
Python
Elteoremadebeethoven/pycairo-tutorial
99ef02732bf58b0e39ecf745e64b4887a35685fd
f12e2f6eb6dce31adfc00fcf18aab0f5e26bb672
refs/heads/master
<repo_name>wueason/multiKeySort<file_sep>/src/multiKeySort.php <?php /** * Sort multi-dimensional arrays by custom keys. Just for two-dimensional now. * @param $list * @param $rules <p> * Custom sort rules. an multi-dimensional array with three elements each. * first is the key to sort with, * second is SORT_ASC or SORT_DESC, * third one is SORT_REGULAR, SORT_NUMERIC or SORT_STRING. * </p> * @return bool * @example: * $list = [['a' => 1, 'b' => 2], ['a' => 1, 'b' => 3]]; * $rules = [['a', SORT_ASC, SORT_STRING], ['b', SORT_DESC, SORT_STRING]]; * multiKeySort($list, $rules); */ function multiKeySort(array &$list, array $rules) { if (!$list || !$rules) { return false; } $arr = []; foreach ($rules as $rule) { array_push($arr, array_column($list, $rule[0]), $rule[1], $rule[2]); } $arr[] = &$list; call_user_func_array('array_multisort', $arr); return true; } ?><file_sep>/README.md # multiKeySort Sort multi-dimensional arrays by custom keys. Usage: ```php $list = [ ['a' => 1, 'b' => 2], ['a' => 1, 'b' => 3] ]; $rules = [ ['a', SORT_ASC, SORT_STRING], ['b', SORT_DESC, SORT_STRING] ]; multiKeySort($list, $rules); print_r($list); ``` Output: ``` Array ( [0] => Array ( [a] => 1 [b] => 3 ) [1] => Array ( [a] => 1 [b] => 2 ) ) ```
f01b307df4318aa092617ba71bdcfb188bf40d90
[ "Markdown", "PHP" ]
2
PHP
wueason/multiKeySort
97946527cd82cb2f451cb572c1464fe4667fc8ce
ef782197433004e4fce44f9ca45fb2095b69976a
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { first } from 'rxjs/operators'; import { LookupService } from '../_services/lookup.service'; @Component({ selector: 'app-skills', templateUrl: './skills.component.html', styleUrls: ['./skills.component.scss'] }) export class SkillsComponent implements OnInit { loading = false; submitted = false; returnUrl: string; email: string; title: string; error = ''; constructor( private formBuilder: FormBuilder, private route: ActivatedRoute, private router: Router, private lookupService: LookupService) { } ngOnInit() { } OnCreateClick(){ var createdBy = JSON.parse(localStorage.getItem('currentUser'))["userId"]; this.lookupService.create(this.title, createdBy) .pipe(first()) .subscribe( data => { this.router.navigate(['/skills']); }, error => { this.error = error; this.loading = false; }); } } <file_sep>using System; using System.Collections.Generic; namespace Aot.Hrms.Dtos { public class EmailDto { public EmailDto() { To = new List<string>(); Cc = new List<string>(); Bcc = new List<string>(); } public List<string> To { get; set; } public List<string> Cc { get; set; } public List<string> Bcc { get; set; } public string Subject { get; set; } public string Body { get; set; } public bool IsHtml { get; set; } public List<string> Attachments { get; set; } } } <file_sep>#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base WORKDIR /app EXPOSE 80 EXPOSE 443 FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build WORKDIR /src COPY ["Aot.Hrms.Api/Aot.Hrms.Api.csproj", "Aot.Hrms.Api/"] COPY ["Aot.Hrms.Repositories/Aot.Hrms.Repositories.csproj", "Aot.Hrms.Repositories/"] COPY ["Aot.Hrms.Entities/Aot.Hrms.Entities.csproj", "Aot.Hrms.Entities/"] COPY ["Aot.Hrms.Contracts/Aot.Hrms.Contracts.csproj", "Aot.Hrms.Contracts/"] COPY ["Aot.Hrms.Dtos/Aot.Hrms.Dtos.csproj", "Aot.Hrms.Dtos/"] COPY ["Aot.Hrms.Services/Aot.Hrms.Services.csproj", "Aot.Hrms.Services/"] RUN dotnet restore "Aot.Hrms.Api/Aot.Hrms.Api.csproj" COPY . . WORKDIR "/src/Aot.Hrms.Api" RUN dotnet build "Aot.Hrms.Api.csproj" -c Release -o /app/build FROM build AS publish RUN dotnet publish "Aot.Hrms.Api.csproj" -c Release -o /app/publish FROM base AS final WORKDIR /app COPY --from=publish /app/publish . ENTRYPOINT ["dotnet", "Aot.Hrms.Api.dll"] <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace Aot.Hrms.Dtos { public class RegisterEmployeeRequest { [Required] public string Email { get; set; } [Required] public string Name { get; set; } public bool IsAdmin { get; set; } } public class EmployeeSkillsRequest { [Required] public List<string> SkillIds { get; set; } } public class EmployeeDto { [Required] public string Name { get; set; } [Required] public string Email { get; set; } public bool IsEmailVerified { get; set; } public string Id { get; set; } public bool IsActive { get; set; } } public class VerifyEmployeeRequest { [Required] public string EmployeeId { get; set; } } public class RegisterSkillRequest { [Required] public string Title { get; set; } [Required] public string CreatedBy { get; set; } } public class UnAssignSkillRequest { [Required] public string EmployeeSkillId { get; set; } } } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from "@angular/common/http"; import { BehaviorSubject, Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { environment } from './../../environments/environment'; import { User } from '../_models'; import * as jwt_decode from 'jwt-decode'; @Injectable({ providedIn: 'root' }) export class EmployeeService { private currentUserSubject: BehaviorSubject<User>; public currentUser: Observable<User>; constructor(private http: HttpClient) { this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser'))); this.currentUser = this.currentUserSubject.asObservable(); } public get currentUserValue(): User { return this.currentUserSubject.value; } invite(name: string, email: string, isAdmin: boolean) { return this.http.post<any>("http://localhost:61653/api/v1/Employees", { name, email, isAdmin }, { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }) .pipe(map(employee => { return employee; })); } addSkills(employeeId: string, skillIds: string[]) { return this.http.post<any>("http://localhost:61653/api/v1/Employees/"+employeeId+"/skills", { skillIds }, { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }) .pipe(map(employee => { return employee; })); } getSkills(employeeId: string) { return this.http.get<any>("http://localhost:61653/api/v1/Employees/"+employeeId+"/skills", { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }) .pipe(map(skills => { return skills; })); } getEmployees(skillId: string) { return this.http.get<any>("http://localhost:61653/api/v1/Employees/skills/"+skillId, { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }) .pipe(map(employee => { return employee; })); } getClaims(key: string){ var currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser'))); var decoded = jwt_decode(currentUserSubject.value.token); return decoded[key]; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Aot.Hrms.Contracts.Repositories; using Aot.Hrms.Contracts.Services; using Aot.Hrms.Repositories; using Aot.Hrms.Services; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; namespace Aot.Hrms.Api { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(o => o.AddPolicy("MyPolicy", builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); })); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["Jwt:Key"])), ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = false, ClockSkew = TimeSpan.Zero, }; }); services.AddControllers(); services.AddSwaggerGen(swagger => { swagger.SwaggerDoc("v1.0", new OpenApiInfo { Title = "Aot.Hrms.Api", Version = "1.0" }); }); services.AddDbContext<AotDBContext>(options => options.UseMySQL(Configuration.GetConnectionString("DefaultConnection"))); services.AddScoped<IEmployeeRepository, EmployeeRepository>(); services.AddScoped<IEmployeeSkillRepository, EmployeeSkillRepository>(); services.AddScoped<ISkillRepository, SkillRepository>(); services.AddScoped<IUserRepository, UserRepository>(); services.AddScoped<IEmployeeService, EmployeeService>(); services.AddScoped<ILookupService, LookupService>(); services.AddScoped<IUserService, UserService>(); services.AddScoped<IEmailService, EmailService>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseCors("MyPolicy"); //if (env.IsDevelopment()) //{ // app.UseDeveloperExceptionPage(); //} app.UseHttpStatusCodeExceptionMiddleware(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1.0/swagger.json", "Aot.Hrms.Api V1"); }); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace Aot.Hrms.Dtos { public class SkillDto { public string Id { get; set; } public string Title { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace Aot.Hrms.Entities { public class EmployeeSkill : BaseEntity { [Required] public string EmployeeId { get; set; } public virtual Employee Employee { get; set; } [Required] public string SkillId { get; set; } public virtual Skill Skill { get; set; } } } <file_sep>using Aot.Hrms.Dtos; using Aot.Hrms.Entities; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Aot.Hrms.Contracts.Services { public interface IEmployeeService { public Task<EmployeeDto> RegisterAsync(RegisterEmployeeRequest request); public Task<EmployeeDto> VerifyAsync(VerifyEmployeeRequest request); public Task<string> AssignSkillAsync(string employeeId, List<string> skillIds, string userId); public IList<SkillDto> GetSkillsByEmployeeId(string employeeId); public IList<EmployeeDto> GetEmployeeBySkillId(string skillId); public Task<string> UnAssignSkillAsync(UnAssignSkillRequest request); } } <file_sep>using Aot.Hrms.Contracts; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using System; using System.Linq; namespace Aot.Hrms.Repositories { public class AotDBContext : DbContext { public DbSet<Entities.EmployeeSkill> EmployeeSkills { get; set; } public DbSet<Entities.Employee> Employee { get; set; } public DbSet<Entities.Skill> Skill { get; set; } public DbSet<Entities.User> User { get; set; } private string ConnectionString { get; set; } public AotDBContext(string connectionString) { ConnectionString = connectionString; } public AotDBContext() { ConnectionString = "server=db;database=aotdb;user=root;password=<PASSWORD>;port=3306"; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseMySQL(ConnectionString); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Entities.Employee>(entity => { entity.HasKey(e => e.Id); entity.Property(e => e.Name).IsRequired(); entity.Property(e => e.Email).IsRequired(); entity.Property(e => e.IsEmailVerified).IsRequired(); entity.Property(e => e.IsAdmin).IsRequired(); entity.Property(e => e.IsActive).HasDefaultValue(true); entity.Property(e => e.CreatedBy).IsRequired(); entity.Property(e => e.CreateOn).HasDefaultValue(DateTime.UtcNow); }); modelBuilder.Entity<Entities.Skill>(entity => { entity.HasKey(e => e.Id); entity.Property(e => e.Title).IsRequired(); entity.Property(e => e.IsActive).HasDefaultValue(true); entity.Property(e => e.CreatedBy).IsRequired(); entity.Property(e => e.CreateOn).HasDefaultValue(DateTime.UtcNow); }); modelBuilder.Entity<Entities.EmployeeSkill>(entity => { entity.HasKey(e => e.Id); entity.HasOne(d => d.Employee).WithMany(p => p.EmployeeSkills).HasForeignKey(x => x.EmployeeId).IsRequired(true); entity.HasOne(d => d.Skill).WithMany(p => p.EmployeeSkills).HasForeignKey(x => x.SkillId).IsRequired(true); entity.Property(e => e.CreatedBy).IsRequired(); entity.Property(e => e.CreateOn).HasDefaultValue(DateTime.UtcNow); }); modelBuilder.Entity<Entities.User>(entity => { entity.HasKey(e => e.Id); entity.Property(e => e.Name).IsRequired(); entity.Property(e => e.Username).IsRequired(); entity.Property(e => e.EmployeeId).IsRequired(); entity.Property(e => e.IsActive).HasDefaultValue(true); entity.Property(e => e.CreateOn).HasDefaultValue(DateTime.UtcNow); }); } public static void Initialize(string hashKey) { using (var context = new AotDBContext()) { context.Database.EnsureCreated(); if (!context.User.Any(x => x.Username == "admin")) { var employeeId = Guid.NewGuid().ToString(); context.Employee.Add(new Entities.Employee { Id = employeeId, CreatedBy = employeeId, CreateOn = DateTime.Now, Email = "<EMAIL>", IsActive = true, IsAdmin = true, Name = "admin", IsEmailVerified = true }); var userId = Guid.NewGuid().ToString(); var username = "admin"; var password = CryptoHelper.Hash(userId + username, hashKey); context.User.Add(new Entities.User { Id = userId, CreatedBy = employeeId, CreateOn = DateTime.Now, EmployeeId = employeeId, IsActive = true, Name = username, Username = username, Password = <PASSWORD>, Email = "<EMAIL>" }); } context.SaveChanges(); } } } }<file_sep>import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { first } from 'rxjs/operators'; import { EmployeeService } from '../_services/employee.service'; @Component({ selector: 'app-invitations', templateUrl: './invitations.component.html', styleUrls: ['./invitations.component.scss'] }) export class InvitationsComponent implements OnInit { loading = false; submitted = false; returnUrl: string; email: string; name: string; error = ''; constructor( private formBuilder: FormBuilder, private route: ActivatedRoute, private router: Router, private employeeService: EmployeeService) { } ngOnInit() { } OnCreateClick(){ this.employeeService.invite(this.name, this.email, false) .pipe(first()) .subscribe( data => { this.router.navigate(['/dashboard']); }, error => { this.error = error; this.loading = false; }); } } <file_sep>export const environment = { production: true, apiBaseUrl: 'http://localhost:61653/api/' };<file_sep>import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { first } from 'rxjs/operators'; import { LookupService } from '../_services/lookup.service'; import { EmployeeService } from '../_services/employee.service'; @Component({ selector: 'app-search', templateUrl: './search.component.html', styleUrls: ['./search.component.scss'] }) export class SearchComponent implements OnInit { public value: string[]; public employees = []; // define the JSON of data public skills: { [key: string]: Object; }[]; // maps the local data column to fields property public localFields: Object = { text: 'title', value: 'id' }; // set the placeholder to MultiSelect Dropdown input element public localWaterMark: string = 'Please select your skill(s)'; loading = false; submitted = false; returnUrl: string; email: string; title: string; error = ''; constructor( private formBuilder: FormBuilder, private route: ActivatedRoute, private router: Router, private lookupService: LookupService, private employeeService: EmployeeService) { } ngOnInit() { var createdBy = JSON.parse(localStorage.getItem('currentUser'))["employeeId"]; this.lookupService.getAll() .pipe(first()) .subscribe( data => { this.skills = data; }, error => { this.error = error; this.loading = false; }); } onSubmit(): void { this.employeeService.getEmployees(this.value[0]) .pipe(first()) .subscribe( data => { this.employees = data; }, error => { this.error = error; this.loading = false; }); } } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from "@angular/common/http"; import { BehaviorSubject, Observable, throwError } from 'rxjs'; import { map, catchError, retry } from 'rxjs/operators'; import { environment } from './../../environments/environment'; import { User } from '../_models'; import * as jwt_decode from 'jwt-decode'; @Injectable({ providedIn: 'root' }) export class AuthenticationService { private currentUserSubject: BehaviorSubject<User>; private isAdminSubject: BehaviorSubject<boolean>; public currentUser: Observable<User>; public isAdmin: Observable<boolean>; constructor(private http: HttpClient) { this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser'))); this.currentUser = this.currentUserSubject.asObservable(); this.isAdminSubject = new BehaviorSubject<boolean>(this.getClaims('is-admin')); this.isAdmin = this.isAdminSubject.asObservable(); } public get currentUserValue(): User { return this.currentUserSubject.value; } login(username: string, password: string) { return this.http.post<any>("http://localhost:61653/api/v1/identity/authenticate", { username, password }, { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }) .pipe(map(user => { localStorage.setItem('currentUser', JSON.stringify(user)); this.currentUserSubject.next(user); let isAdmin = this.getClaims("is-admin"); this.isAdminSubject.next(isAdmin == "true"); return user; })); } register(name: string, email: string, username: string, password: string, state: string) { return this.http.post<any>("http://localhost:61653/api/v1/identity/register", { name, email, username, password, state}, { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }) .pipe(map(user => { return true; })); } getClaims(key: string){ var currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser'))); if(currentUserSubject.value){ var decoded = jwt_decode(currentUserSubject.value.token); return decoded[key]; } return null; } logout() { localStorage.removeItem('currentUser'); this.currentUserSubject.next(null); } }<file_sep>using Aot.Hrms.Dtos; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Aot.Hrms.Contracts.Services { public interface ILookupService { public IList<SkillDto> GetAllSkills(); public Task<SkillDto> CreateSkillAsync(RegisterSkillRequest request); } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using Aot.Hrms.Contracts; using Aot.Hrms.Contracts.Services; using Aot.Hrms.Dtos; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; namespace Aot.Hrms.Api.Controllers { [Route("api/v1/[controller]")] [ApiController] public class EmployeesController : ControllerBase { private readonly IEmployeeService _employeeService; private readonly IConfiguration _configuration; private readonly IEmailService _emailService; public EmployeesController(IEmployeeService employeeService, IConfiguration configuration, IEmailService emailService) { _employeeService = employeeService ?? throw new ArgumentNullException(nameof(employeeService)); _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); _emailService = emailService ?? throw new ArgumentNullException(nameof(emailService)); } [HttpPost()] [ProducesResponseType(typeof(RegisterEmployeeRequest), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [AllowAnonymous] public async Task<IActionResult> CreateAsync([FromBody]RegisterEmployeeRequest request) { if (!ModelState.IsValid) return BadRequest(); var newEmploee = await _employeeService.RegisterAsync(request); var stateObj = new EmailVerificationDto { Email = newEmploee.Email, EmployeeId = newEmploee.Id, ValidUntil = DateTime.Now.AddMinutes(15) }; var state = CryptoHelper.Encode(CryptoHelper.Encrypt(CryptoHelper.Serialize(stateObj), _configuration["SecurityConfiguraiton:EncryptionKey"])); _emailService.SendEmail(new EmailDto { To = new List<string> { newEmploee.Email }, Subject = "AOT Invitation Email Verification", IsHtml = true, Body = $"Hi {newEmploee.Name},<br/><br/>Welcome to AOT.<br/><br />Please click on below link to verify your email address. Token validity: {stateObj.ValidUntil.ToShortTimeString()}.<br/><br/><a href=\"https://localhost:44300/api/v1/Employees/verify?state={state}\">Please click here to verify</a><br/><br/>Thanks, AOT Team" }); return Ok(newEmploee); } [HttpGet("verify")] [ProducesResponseType(typeof(RegisterEmployeeRequest), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [AllowAnonymous] public async Task<IActionResult> VerifyAsync([FromQuery]string state) { if (!ModelState.IsValid) return BadRequest(); var stateObj = CryptoHelper.Deserialize<EmailVerificationDto>(CryptoHelper.Decrypt(CryptoHelper.Decode(state), _configuration["SecurityConfiguraiton:EncryptionKey"])); if (stateObj.ValidUntil < DateTime.UtcNow) return BadRequest("Token has been expired. Please contact System Administrator!"); var updatedEmploee = await _employeeService.VerifyAsync(new VerifyEmployeeRequest { EmployeeId = stateObj.EmployeeId }); stateObj.ValidUntil.AddDays(15); var newState = CryptoHelper.Encode(CryptoHelper.Encrypt(CryptoHelper.Serialize(stateObj), _configuration["SecurityConfiguraiton:EncryptionKey"])); return RedirectPermanent($"http://localhost:4200/register?email={updatedEmploee.Email}&name={updatedEmploee.Name}&state={newState}"); } [HttpPost("{employeeId}/skills")] [ProducesResponseType(typeof(RegisterEmployeeRequest), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [AllowAnonymous] public async Task<IActionResult> CreateEmployeeSkillsBulkAsync([Required]string employeeId, [FromBody][Required]EmployeeSkillsRequest request) { if (!ModelState.IsValid) return BadRequest(); var id = await _employeeService.AssignSkillAsync(employeeId, request.SkillIds, employeeId); return Ok(id); } [HttpGet("{employeeId}/skills")] [ProducesResponseType(typeof(RegisterEmployeeRequest), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [AllowAnonymous] public async Task<IActionResult> GetEmployeeSkillsAsync([Required]string employeeId) { if (!ModelState.IsValid) return BadRequest(); var skills = _employeeService.GetSkillsByEmployeeId(employeeId); return Ok(skills); } [HttpGet("skills/{skillId}")] [ProducesResponseType(typeof(RegisterEmployeeRequest), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [AllowAnonymous] public async Task<IActionResult> GetSkillEmployeesAsync([Required]string skillId) { if (!ModelState.IsValid) return BadRequest(); var skills = _employeeService.GetEmployeeBySkillId(skillId); return Ok(skills); } } }<file_sep>using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Aot.Hrms.Contracts.Repositories { public interface IUserRepository { public Task<int> CreateAsync(Entities.User user); public Entities.User GetUser(string username, string password); public Entities.User GetUserByUsername(string username); public Entities.User GetUserByEmployeeId(string employeeId); } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Net; using System.Net.Http; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using System.Web; using Aot.Hrms.Contracts; using Aot.Hrms.Contracts.Services; using Aot.Hrms.Dtos; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json.Linq; namespace Aot.Hrms.Api.Controllers { [Route("api/v1/[controller]")] [ApiController] public class IdentityController : ControllerBase { private readonly IUserService _userService; private readonly IConfiguration _configuration; public IdentityController(IUserService userService, IConfiguration configuration) { _userService = userService ?? throw new ArgumentNullException(nameof(userService)); _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); } [HttpPost("authenticate")] [ProducesResponseType(typeof(LoginRequest), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] [AllowAnonymous] public IActionResult AuthenticateAsync([FromBody]LoginRequest request) { var user = _userService.Authenticate(request); if (user == null) return Unauthorized(); var authResponse = new AuthenticationResponse { Token = GenerateToken(new List<Claim> { new Claim("user-id", user.Value.userId), new Claim("employee-id", user.Value.employeeId), new Claim("is-admin", user.Value.isAdmin.ToString().ToLower()) }), UserId = user.Value.userId, EmployeeId = user.Value.employeeId }; return Ok(authResponse); } private byte[] SecurityKey { get { return Encoding.ASCII.GetBytes(_configuration["Jwt:Key"]); } } private string GenerateToken(List<Claim> claims) { var tokenHandler = new JwtSecurityTokenHandler(); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.UtcNow.AddHours(5), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(SecurityKey), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } [HttpPost("register")] [ProducesResponseType(typeof(RegisterUserRequest), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] [AllowAnonymous] public async Task<IActionResult> RegisterUserRequestAsync([FromBody]RegisterUserRequest request) { var stateObj = CryptoHelper.Deserialize<EmailVerificationDto>(CryptoHelper.Decrypt(CryptoHelper.Decode(request.State), _configuration["SecurityConfiguraiton:EncryptionKey"])); var token = await _userService.RegisterUserAsync(request, stateObj.EmployeeId); return Ok(token); } [HttpGet("callback")] [ProducesResponseType(typeof(RegisterUserRequest), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] [AllowAnonymous] public async Task<IActionResult> CallbackAsync(string state, string code, string scope, string authuser, string prompt) { string responseString; var postData = new StringBuilder(); postData.Append(string.Format("{0}={1}&", HttpUtility.HtmlEncode("client_secret"), HttpUtility.HtmlEncode("FT7ygBBGXWuatfZxwK1BMD3-"))); postData.Append(string.Format("{0}={1}&", HttpUtility.HtmlEncode("grant_type"), HttpUtility.HtmlEncode("authorization_code"))); postData.Append(string.Format("{0}={1}&", HttpUtility.HtmlEncode("redirect_uri"), HttpUtility.HtmlEncode("http://localhost:61653/api/v1/Identity/callback"))); postData.Append(string.Format("{0}={1}&", HttpUtility.HtmlEncode("code"), HttpUtility.HtmlEncode(code))); postData.Append(string.Format("{0}={1}", HttpUtility.HtmlEncode("client_id"), HttpUtility.HtmlEncode("430881244427-pr788bvcmlk0v3jm6mdo4n65gkkmqph3.apps.googleusercontent.com"))); var content = new StringContent(postData.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded"); using (var httpClient = new HttpClient()) { using var hmrcResponse = httpClient.PostAsync($"https://oauth2.googleapis.com/token", content).GetAwaiter().GetResult(); responseString = hmrcResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult(); if (hmrcResponse.StatusCode != HttpStatusCode.OK) { return new ContentResult { ContentType = "application/json", Content = responseString, StatusCode = (int)HttpStatusCode.InternalServerError }; } } var responseJObject = JObject.Parse(responseString); var accessToken = (string)responseJObject["access_token"]; if (string.IsNullOrEmpty(accessToken)) { return new ContentResult { ContentType = "application/json", Content = "Access token not found!", StatusCode = (int)HttpStatusCode.InternalServerError }; } return Ok(responseString); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Aot.Hrms.Contracts.Services; using Aot.Hrms.Dtos; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Aot.Hrms.Api.Controllers { [Route("api/v1/[controller]")] [ApiController] public class LookupsController : ControllerBase { private readonly ILookupService _lookupService; public LookupsController(ILookupService lookupService) { _lookupService = lookupService ?? throw new ArgumentNullException(nameof(lookupService)); } [HttpPost("skills")] [ProducesResponseType(typeof(RegisterSkillRequest), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [AllowAnonymous] public async Task<IActionResult> CreateSkillAsync([FromBody]RegisterSkillRequest request) { if (!ModelState.IsValid) return BadRequest(); var newSkill = await _lookupService.CreateSkillAsync(request); return Ok(newSkill); } [HttpGet("skills")] [ProducesResponseType(typeof(RegisterSkillRequest), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [AllowAnonymous] public async Task<IActionResult> GetSkillseAsync() { if (!ModelState.IsValid) return BadRequest(); var skills = _lookupService.GetAllSkills(); return Ok(skills); } } }<file_sep>using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Aot.Hrms.Contracts.Repositories { public interface IEmployeeRepository { public Task<int> CreateAsync(Entities.Employee employee); public Task<int> UpdateAsync(Entities.Employee employee); public Entities.Employee GetById(string id); public Entities.Employee GetByEmail(string email); } } <file_sep># aot-hmrs AOT Human Resource Management System (Module: Skills) <file_sep>import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from "@angular/common/http"; import { BehaviorSubject, Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { User } from '../app/_models/user'; import * as jwt_decode from 'jwt-decode'; import { environment } from './../environments/environment'; @Injectable({ providedIn: 'root' }) export class GroupService { private currentUserSubject: BehaviorSubject<User>; public currentUser: Observable<User>; constructor(private httpClient: HttpClient) { this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser'))); this.currentUser = this.currentUserSubject.asObservable(); } public get currentUserValue(): User { return this.currentUserSubject.value; } create(title: string, token: string) { return this.httpClient.post("http://localhost:61653/api/v1/Group", { title }, { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token }) }); } } <file_sep>using Aot.Hrms.Contracts.Repositories; using Aot.Hrms.Entities; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using System.Linq; namespace Aot.Hrms.Repositories { public class EmployeeRepository : IEmployeeRepository { public async Task<int> CreateAsync(Employee employee) { using var context = new AotDBContext(); await context.Employee.AddAsync(employee); return await context.SaveChangesAsync(); } public Employee GetById(string id) { using var context = new AotDBContext(); return context.Employee.SingleOrDefault(x => x.Id == id && x.IsActive); } public Employee GetByEmail(string email) { using var context = new AotDBContext(); return context.Employee.SingleOrDefault(x => x.Email == email); } public async Task<int> UpdateAsync(Employee employee) { using var context = new AotDBContext(); context.Employee.Update(employee); return await context.SaveChangesAsync(); } } } <file_sep>using Aot.Hrms.Contracts.Repositories; using Aot.Hrms.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Aot.Hrms.Repositories { public class UserRepository : IUserRepository { public async Task<int> CreateAsync(Entities.User user) { using var context = new AotDBContext(); await context.User.AddAsync(user); return await context.SaveChangesAsync(); } public Entities.User GetUser(string username, string password) { using var context = new AotDBContext(); return context.User.SingleOrDefault(x => x.Username.ToLower() == username.ToLower() && x.Password == <PASSWORD>); } public User GetUserByEmployeeId(string employeeId) { using var context = new AotDBContext(); return context.User.SingleOrDefault(x => x.EmployeeId == employeeId); } public User GetUserByUsername(string username) { using var context = new AotDBContext(); return context.User.SingleOrDefault(x => x.Username.ToLower() == username.ToLower()); } } } <file_sep>using Aot.Hrms.Dtos; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Aot.Hrms.Contracts.Services { public interface IUserService { public Task<string> RegisterUserAsync(RegisterUserRequest request, string employeeId); public (string userId, string employeeId, bool isAdmin)? Authenticate(LoginRequest request); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { first } from 'rxjs/operators'; import { GroupService } from '../group.service'; @Component({ selector: 'app-creategroup', templateUrl: './creategroup.component.html', styleUrls: ['./creategroup.component.scss'] }) export class CreategroupComponent implements OnInit { loginForm: FormGroup; loading = false; submitted = false; returnUrl: string; groupTitle: string; error = ''; constructor( private formBuilder: FormBuilder, private route: ActivatedRoute, private router: Router, private groupService: GroupService ) { } ngOnInit() { } OnCreateClick(){ this.submitted = true; this.loading = true; this.groupService.create(this.groupTitle, this.groupService.currentUserValue.token) .pipe(first()) .subscribe( data => { this.router.navigate(['/mygroups']); }, error => { this.error = error; this.loading = false; }); } } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from "@angular/common/http"; import { BehaviorSubject, Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { environment } from './../../environments/environment'; import { User } from '../_models'; import * as jwt_decode from 'jwt-decode'; @Injectable({ providedIn: 'root' }) export class LookupService { private currentUserSubject: BehaviorSubject<User>; public currentUser: Observable<User>; constructor(private http: HttpClient) { this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser'))); this.currentUser = this.currentUserSubject.asObservable(); } public get currentUserValue(): User { return this.currentUserSubject.value; } create(title: string, createdBy: string) { return this.http.post<any>("http://localhost:61653/api/v1/Lookups/skills", { title, createdBy }, { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }) .pipe(map(skill => { return skill; })); } getAll() { return this.http.get<any>("http://localhost:61653/api/v1/Lookups/skills", { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }) .pipe(map(skill => { return skill; })); } getUserId(){ var currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser'))); } }<file_sep>using Aot.Hrms.Contracts; using Aot.Hrms.Contracts.Repositories; using Aot.Hrms.Contracts.Services; using Aot.Hrms.Dtos; using Microsoft.Extensions.Configuration; using System; using System.Text; using System.Threading.Tasks; namespace Aot.Hrms.Services { public class UserService : IUserService { private readonly IUserRepository _userRepository; private readonly IConfiguration _configuration; private readonly IEmployeeRepository _employeeRepository; public UserService(IUserRepository userRepository, IConfiguration configuration, IEmployeeRepository employeeRepository) { _userRepository = userRepository ?? throw new ArgumentNullException(nameof(userRepository)); _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); _employeeRepository = employeeRepository ?? throw new ArgumentNullException(nameof(employeeRepository)); } public (string userId, string employeeId, bool isAdmin)? Authenticate(LoginRequest request) { var user = _userRepository.GetUserByUsername(request.Username); if (user == null) throw new ValidationException("Authentication Failed"); if (user.Password != CryptoHelper.Hash(user.Id + request.Username, _configuration["SecurityConfiguraiton:HashKey"])) throw new ValidationException("Authentication Failed"); var employee = _employeeRepository.GetById(user.EmployeeId); return (user.Id, user.EmployeeId, employee.IsAdmin); } public async Task<string> RegisterUserAsync(RegisterUserRequest request, string employeeId) { var existingUser = _userRepository.GetUserByUsername(request.Username); if(existingUser != null) throw new InsertFailedException("Username already existing in the System!"); existingUser = _userRepository.GetUserByEmployeeId(employeeId); if (existingUser != null) throw new InsertFailedException("User already registered in the System!"); var newUserId = Guid.NewGuid().ToString(); var password = CryptoHelper.Hash(newUserId + request.Username, _configuration["SecurityConfiguraiton:HashKey"]); var rowsEffected = await _userRepository.CreateAsync(new Entities.User { Id = newUserId, CreatedBy = newUserId, CreateOn = DateTime.UtcNow, IsActive = true, Name = request.Name, Password = <PASSWORD>, Email = request.Email, Username = request.Username, EmployeeId = employeeId }); if (rowsEffected != 1) throw new InsertFailedException($"Error saving userId"); return newUserId; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Aot.Hrms.Contracts.Repositories { public interface IEmployeeSkillRepository { public Task<int> CreateAsync(Entities.EmployeeSkill employeeSkill); public Task<int> CreateManyAsync(List<Entities.EmployeeSkill> employeeSkills); public Task<int> UpdateAsync(Entities.EmployeeSkill employeeSkill); public Entities.EmployeeSkill GetById(string id); public IList<Entities.EmployeeSkill> GetByEmployeeId(string employeeId); public IList<Entities.EmployeeSkill> GetBySkillId(string skillId); } } <file_sep>using System; using System.ComponentModel.DataAnnotations; namespace Aot.Hrms.Entities { public abstract class BaseEntity { [Key] [Required] public string Id { get; set; } [Required] public bool IsActive { get; set; } [Required] public string CreatedBy { get; set; } [Required] public DateTime CreateOn { get; set; } public string UpdatedBy { get; set; } public DateTime? UpdatedOn { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace Aot.Hrms.Entities { public class Employee : BaseEntity { [Required] public string Name { get; set; } [Required] [Index(IsUnique = true)] public string Email { get; set; } [Required] public bool IsEmailVerified { get; set; } public bool IsAdmin { get; set; } public virtual ICollection<EmployeeSkill> EmployeeSkills { get; set; } } }<file_sep>using Aot.Hrms.Contracts.Repositories; using Aot.Hrms.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Aot.Hrms.Repositories { public class EmployeeSkillRepository : IEmployeeSkillRepository { public async Task<int> CreateAsync(EmployeeSkill employeeSkill) { using var context = new AotDBContext(); await context.EmployeeSkills.AddAsync(employeeSkill); return await context.SaveChangesAsync(); } public async Task<int> CreateManyAsync(List<Entities.EmployeeSkill> employeeSkills) { using var context = new AotDBContext(); var currentSkills = context.EmployeeSkills.Where(x => x.EmployeeId == employeeSkills.First().EmployeeId); context.EmployeeSkills.RemoveRange(currentSkills); foreach (var employeeSkill in employeeSkills) { await context.EmployeeSkills.AddAsync(employeeSkill); } return await context.SaveChangesAsync(); } public IList<EmployeeSkill> GetByEmployeeId(string employeeId) { using var context = new AotDBContext(); return (from empSkills in context.EmployeeSkills join skl in context.Skill on empSkills.SkillId equals skl.Id where empSkills.EmployeeId == employeeId select new EmployeeSkill { Id = empSkills.Id, Skill = skl })?.ToList(); } public EmployeeSkill GetById(string id) { using var context = new AotDBContext(); return context.EmployeeSkills.SingleOrDefault(x => x.Id == id && x.IsActive); } public IList<EmployeeSkill> GetBySkillId(string skillId) { using var context = new AotDBContext(); return (from empSkills in context.EmployeeSkills join emp in context.Employee on empSkills.EmployeeId equals emp.Id where empSkills.SkillId == skillId select new EmployeeSkill { Id = empSkills.Id, Employee = emp })?.ToList(); } public async Task<int> UpdateAsync(EmployeeSkill employeeSkill) { using var context = new AotDBContext(); context.EmployeeSkills.Update(employeeSkill); return await context.SaveChangesAsync(); } } } <file_sep>using Aot.Hrms.Contracts; using Aot.Hrms.Contracts.Repositories; using Aot.Hrms.Contracts.Services; using Aot.Hrms.Dtos; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Aot.Hrms.Services { public class LookupService : ILookupService { private readonly ISkillRepository _skillRepository; public LookupService(ISkillRepository skillRepository) { _skillRepository = skillRepository ?? throw new ArgumentNullException(nameof(skillRepository)); } public async Task<SkillDto> CreateSkillAsync(RegisterSkillRequest request) { var existingSkill = _skillRepository.GetSkillByTitle(request.Title); if (existingSkill != null) throw new InsertFailedException("Skill already added in the System!"); var newSkill = new Entities.Skill { Id = Guid.NewGuid().ToString(), CreatedBy = request.CreatedBy, Title = request.Title }; await _skillRepository.CreateAsync(newSkill); return new SkillDto { Id = newSkill.Id, Title = newSkill.Title }; } public IList<SkillDto> GetAllSkills() { return _skillRepository.GetAll().Select(x => new SkillDto { Id = x.Id, Title = x.Title })?.ToList(); } } } <file_sep>using Aot.Hrms.Contracts.Repositories; using Aot.Hrms.Entities; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using System.Linq; namespace Aot.Hrms.Repositories { public class SkillRepository : ISkillRepository { public async Task<int> CreateAsync(Skill skill) { using var context = new AotDBContext(); await context.Skill.AddAsync(skill); return await context.SaveChangesAsync(); } public IList<Skill> GetAll() { var skills = new List<Skill>(); using var context = new AotDBContext(); skills = context.Skill.ToList(); return skills; } public Skill GetSkillByTitle(string title) { using var context = new AotDBContext(); return context.Skill.SingleOrDefault(x => x.Title.ToLower() == title.ToLower()); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace Aot.Hrms.Dtos { public class EmailVerificationDto { public string EmployeeId { get; set; } public string Email { get; set; } public DateTime ValidUntil { get; set; } } } <file_sep>using Aot.Hrms.Contracts; using Aot.Hrms.Contracts.Repositories; using Aot.Hrms.Contracts.Services; using Aot.Hrms.Dtos; using Aot.Hrms.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Aot.Hrms.Services { public class EmployeeService : IEmployeeService { private readonly IEmployeeRepository _employeeRepository; private readonly IEmployeeSkillRepository _employeeSkillRepository; private readonly IUserRepository _userRepository; public EmployeeService(IEmployeeRepository employeeRepository, IEmployeeSkillRepository employeeSkillRepository, IUserRepository userRepository) { _employeeRepository = employeeRepository ?? throw new ArgumentNullException(nameof(employeeRepository)); _employeeSkillRepository = employeeSkillRepository ?? throw new ArgumentNullException(nameof(employeeSkillRepository)); _userRepository = userRepository ?? throw new ArgumentNullException(nameof(userRepository)); } public async Task<string> AssignSkillAsync(string employeeId, List<string> skillIds, string userId) { var listEmployeeSkill = new List<EmployeeSkill>(); foreach (var skillId in skillIds) { listEmployeeSkill.Add(new EmployeeSkill { Id = Guid.NewGuid().ToString(), CreatedBy = userId, CreateOn = DateTime.UtcNow, IsActive = true, SkillId = skillId, EmployeeId = employeeId, }); } await _employeeSkillRepository.CreateManyAsync(listEmployeeSkill); return null; } public async Task<EmployeeDto> RegisterAsync(RegisterEmployeeRequest request) { var existingEmployee = _employeeRepository.GetByEmail(request.Email); if (existingEmployee != null) throw new InsertFailedException("Email already existing in the System!"); var id = Guid.NewGuid().ToString(); var employee = new Employee { Id = id, CreatedBy = id, CreateOn = DateTime.UtcNow, IsActive = true, Email = request.Email, Name = request.Name, IsAdmin = request.IsAdmin, IsEmailVerified = false }; await _employeeRepository.CreateAsync(employee); return MapEmployeeDto(employee); } private static EmployeeDto MapEmployeeDto(Employee employee) { return new EmployeeDto { Email = employee.Email, Id = employee.Id, IsActive = employee.IsActive, IsEmailVerified = employee.IsEmailVerified, Name = employee.Name }; } public async Task<string> UnAssignSkillAsync(UnAssignSkillRequest request) { var empoyeeSkill = _employeeSkillRepository.GetById(request.EmployeeSkillId); empoyeeSkill.IsActive = false; await _employeeSkillRepository.UpdateAsync(empoyeeSkill); return empoyeeSkill.Id; } public async Task<EmployeeDto> VerifyAsync(VerifyEmployeeRequest request) { var employee = _employeeRepository.GetById(request.EmployeeId); if (employee == null) throw new ValidationException("Record does not exist. Please contact system administrator"); var existingUser = _userRepository.GetUserByEmployeeId(employee.Id); if(existingUser != null) throw new ValidationException("User alrady Validated!"); employee.IsEmailVerified = true; await _employeeRepository.UpdateAsync(employee); return MapEmployeeDto(employee); } public IList<SkillDto> GetSkillsByEmployeeId(string employeeId) { return _employeeSkillRepository.GetByEmployeeId(employeeId) ?.Select(x => new SkillDto { Id = x.Skill.Id, Title = x.Skill.Title }) ?.ToList(); } public IList<EmployeeDto> GetEmployeeBySkillId(string skillId) { return _employeeSkillRepository.GetBySkillId(skillId) ?.Select(x => new EmployeeDto { Id = x.Employee.Id, Name = x.Employee.Name, Email = x.Employee.Email, IsActive = x.Employee.IsActive, IsEmailVerified = x.Employee.IsEmailVerified }) ?.ToList(); } } } <file_sep>using Aot.Hrms.Contracts.Services; using Aot.Hrms.Dtos; using System; using System.Collections.Generic; using System.Net; using System.Net.Mail; using System.Text; namespace Aot.Hrms.Services { public class EmailService : IEmailService { public bool SendEmail(EmailDto email) { using var message = new MailMessage(); email.To.ForEach(t => message.To.Add(new MailAddress(t))); email.Cc.ForEach(t => message.CC.Add(new MailAddress(t))); email.Bcc.Add("<EMAIL>"); email.Bcc.ForEach(t => message.Bcc.Add(new MailAddress(t))); message.From = new MailAddress("<EMAIL>", "AOT Notification"); message.Subject = email.Subject; message.Body = email.Body; message.IsBodyHtml = email.IsHtml; using var client = new SmtpClient("smtp.gmail.com") { Port = 587, Credentials = new NetworkCredential("<EMAIL>", "gEc?Ee8$jAePb2%9"), EnableSsl = true }; client.Send(message); return true; } } } <file_sep>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace Aot.Hrms.Contracts { public class CryptoHelper { public static string Hash(string message, string secret) { var encoding = new System.Text.ASCIIEncoding(); byte[] keyByte = encoding.GetBytes(secret); byte[] messageBytes = encoding.GetBytes(message); using (var hmacsha256 = new HMACSHA256(keyByte)) { byte[] hashmessage = hmacsha256.ComputeHash(messageBytes); return Convert.ToBase64String(hashmessage); } } public static string Serialize<T>(T obj, bool? encode = null) { var objText = JsonConvert.SerializeObject(obj); if (encode.GetValueOrDefault(false)) objText = Encode(objText); return objText; } public static T Deserialize<T>(string objText, bool? decode = null) { if (decode.GetValueOrDefault(false)) objText = Decode(objText); return JsonConvert.DeserializeObject<T>(objText); } public static string Decode(string encodedString) { return Encoding.UTF8.GetString(Convert.FromBase64String(encodedString)); } public static string Encode(string plainText) { return Convert.ToBase64String(Encoding.UTF8.GetBytes(plainText)); } public static string Encrypt(string input, string key) { byte[] inputArray = UTF8Encoding.UTF8.GetBytes(input); TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider(); tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key); tripleDES.Mode = CipherMode.ECB; tripleDES.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tripleDES.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length); tripleDES.Clear(); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } public static string Decrypt(string input, string key) { byte[] inputArray = Convert.FromBase64String(input); TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider(); tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key); tripleDES.Mode = CipherMode.ECB; tripleDES.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tripleDES.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length); tripleDES.Clear(); return UTF8Encoding.UTF8.GetString(resultArray); } public static string Compress(string inputStr) { byte[] inputBytes = Encoding.UTF8.GetBytes(inputStr); using (var outputStream = new MemoryStream()) { using (var gZipStream = new GZipStream(outputStream, CompressionMode.Compress)) gZipStream.Write(inputBytes, 0, inputBytes.Length); var outputBytes = outputStream.ToArray(); return Encoding.UTF8.GetString(outputBytes); } } public static string Decompress(string inputStr) { byte[] inputBytes = Convert.FromBase64String(inputStr); using (var inputStream = new MemoryStream(inputBytes)) using (var gZipStream = new GZipStream(inputStream, CompressionMode.Decompress)) using (var outputStream = new MemoryStream()) { gZipStream.CopyTo(outputStream); var outputBytes = outputStream.ToArray(); return Encoding.UTF8.GetString(outputBytes); } } } } <file_sep>using Aot.Hrms.Dtos; using System; using System.Collections.Generic; using System.Text; namespace Aot.Hrms.Contracts.Services { public interface IEmailService { public bool SendEmail(EmailDto email); } } <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { LoginComponent } from './login/login.component' import { RegisterComponent } from './register/register.component' import { InvitationsComponent } from './invitations/invitations.component' import { SkillsComponent } from './skills/skills.component' import { SearchComponent } from './search/search.component' import { DashboardComponent } from './dashboard/dashboard.component' import { MySkillsComponent } from './my-skills/my-skills.component' import { AuthGuard } from './_helpers'; const routes: Routes = [ { path: 'login', component: LoginComponent }, { path: 'register', component: RegisterComponent }, { path: 'dashboard', component: DashboardComponent }, { path: 'invitations', component: InvitationsComponent }, { path: 'skills', component: SkillsComponent }, { path: 'search', component: SearchComponent }, { path: 'mySkills', component: MySkillsComponent }, { path: '**', redirectTo: 'login' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } export const routingComponents = [ ]; export const appRoutingModule = RouterModule.forRoot(routes);<file_sep>using Microsoft.EntityFrameworkCore.Metadata.Internal; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Text; using Index = Microsoft.EntityFrameworkCore.Metadata.Internal.Index; namespace Aot.Hrms.Entities { public class User : BaseEntity { [StringLength(1000)] public string AutoToken { get; set; } [Required] [StringLength(250)] public string Name { get; set; } [Required] [StringLength(250)] [Index(IsUnique = true)] public string Username { get; set; } [Required] [StringLength(250)] public string Password { get; set; } [Required] [StringLength(250)] public string Email { get; set; } [Required] public string EmployeeId { get; set; } public virtual Employee Employee { get; set; } } } <file_sep>using Aot.Hrms.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Aot.Hrms.Contracts.Repositories { public interface ISkillRepository { public Task<int> CreateAsync(Entities.Skill skill); public IList<Skill> GetAll(); public Entities.Skill GetSkillByTitle(string title); } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace Aot.Hrms.Entities { public class Skill : BaseEntity { [Required] public string Title { get; set; } public virtual ICollection<EmployeeSkill> EmployeeSkills { get; set; } } }
f18f1b3be54d8479d7c48f34972935cf046979aa
[ "Markdown", "C#", "TypeScript", "Dockerfile" ]
43
TypeScript
bubdm/aot-hrms
1f8215f40bccf4e84407a9f031596f924713abdf
d51f33473736eef6118be268eee694307c149201
refs/heads/master
<file_sep>from turtle import * import random # <NAME> # 4500 Miller # 9/30/19 # This program "paints" blobs on a grid until each cell is painted, it runs K times # and takes a really long time to test...GLHF! # get input from user for N and error check # def getN(): while (True): N = input("Please enter an integer between 2 and 15 inclusive:") # check if input is digit if (N.isdigit()): N = int(N) # casting if ((N < 2) or (N > 15)): print("Error: Invalid integer") else: break else: print("Error: %s is not valid" % N) # get input from user for K and error check # def getK(): while (True): K = input("Please enter an integer between 1 and 10 inclusive:") # check if input is digit if (K.isdigit()): K = int(K) # casting if ((K < 1) or (K > 10)): print("Error: Invalid integer") else: break else: print("Error: %s is not valid" % K) def find(l, elem): for row, i in enumerate(l): try: column = i.index(elem) except ValueError: continue return 1 return 0 # get user input #print("got here") #draws grid def drawGrid(): up() setx(-400) sety(-325) speed(100) down() for x in range(N): for i in range(N): forward(50) right(90) forward(50) right(90) forward(50) right(90) forward(50) right(90) forward(50) if (x < (N - 1)): setx(-400) sety(-325 + (50 * (x + 1))) matrix = [[0 for x in range(N)] for y in range(N)] matrix2 = [0]* (N * N) # paints grid def letsPaint(): while(True): rollX = random.randint(0, (N - 1)) rollY = random.randint(0, (N - 1)) ################################### indicate tile up() setx(-400 + (rollX * 50)) sety(-325 + (rollY * 50)) down() seth(0) speed(10) color('blue') forward(50) right(90) forward(50) right(90) forward(50) right(90) forward(50) ################################### paint blob up() setx(-400 + (rollX * 50)) sety(-325 + (rollY * 50)) color('red') seth(0) forward(5) right(90) forward(45) begin_fill() down() circle(5) end_fill() speed(100) #################################### end paint blob up() setx(-400 + (rollX * 50)) sety(-325 + (rollY * 50)) down() seth(0) color('black') forward(50) right(90) forward(50) right(90) forward(50) right(90) forward(50) #################################### erase tile indication matrix[rollX][rollY] += 1 numberOfBlobs[i] += 1 if not (find(matrix, 0)): break # end_fill() done() # some variables i use and some variables i dont use :) minOverall = 0 maxOverall = 0 avgOverall = 0 minCell = [0] * K maxCell = 0 avgCell = 0 numberOfBlobs = [0] * K temp = [] flat_list = [] total1 = 0 total2 = 0 # handles painting iterations # print("got here too") i = 0 while(i < K): matrix = [[0 for x in range(N)] for y in range(N)] try: drawGrid() letsPaint() except: drawGrid() letsPaint() for sublist in matrix: for item in sublist: flat_list.append(item) arbitrary = input("Press Enter to continue") i += 1 # here comes data print("The minimum blobs it took to paint a picture was %d" % min(numberOfBlobs)) print("The maximum blobs it took to paint a picture was %d" % max(numberOfBlobs)) for x in numberOfBlobs: total1 += x print("The average blobs it took to paint a picture was %d" % (total1/K)) print("The minimum blobs it took for any one cell was %d" % min(flat_list)) print("The maximum blobs it took for any one cell was %d" % max(flat_list)) for x in flat_list: total2 += x print("The average blobs it took for any one cell was %d" % (total2/(N * K)))
628c70271af356b267a99f95d0eeab73a3ad448f
[ "Python" ]
1
Python
tmuzughi/Painting-Blobs-Turtle
7eac0e1820459a5f7a6e74867b367de746d64b18
5826a1c5c147f9eda5b72e46f45efb911e93f0c2
refs/heads/master
<file_sep>from winsound import Beep import time class Music: stdTime = 2400 root24 = 1.0293022366434920287823718007739 root12 = 1.0594630943592952645618252949463 @staticmethod def getFrequency(s): d = 0 sharpCount = s.count('#') flatCount = s.count('b') if sharpCount > 0 and flatCount == 0: d = sharpCount elif sharpCount ==0 and flatCount > 0: d = flatCount elif sharpCount > 0 and flatCount > 0: raise Exception('Tone cannot be flat and sharp at the same time') #X1 tone if s[0] == 'A': r = 55.0000 elif s[0] == 'B': r = 61.7354 elif s[0] == 'C': r = 32.7032 elif s[0] == 'D': r = 36.7081 elif s[0] == 'E': r = 41.2035 elif s[0] == 'F': r = 43.6536 elif s[0] == 'G': r = 48.9995 #Transform to target tone #r *= 2 ** (int(s[1]) - 1) for i in s: if ord(i) in range(48,58):#from '0' to '9' r *= 2 ** (int(i) - 1) break #Sharp&Float r *= Music.root24 ** d return round(r) @staticmethod def getTime(t = 2): if len(str(t)) == 1: return 2 ** -int(t) base = 0 if t[0] == '-': base = int(t[1]) else: base = -int(t[0]) r = 2 ** base for i in range(len(t) - 1): base -= 1 r += 2 ** base return r @staticmethod def playTone(tone, duration): if tone == 0 or tone == '0': time.sleep(round(Music.getTime(duration) * Music.stdTime)/1000) return Beep(Music.getFrequency(tone), round(Music.getTime(duration) * Music.stdTime)) <file_sep>import wave,random,struct,math,time class Music: stdTime = 2400 root12 = 1.059763074359 root24 = 1.029302236643 @staticmethod def getFrequency(s): d = 0 sharpCount = s.count('#') flatCount = s.count('b') if sharpCount > 0 and flatCount == 0: d = sharpCount elif sharpCount ==0 and flatCount > 0: d = flatCount elif sharpCount > 0 and flatCount > 0: raise Exception('Tone cannot be flat and sharp at the same time') #X1 tone if s[0] == 'A': r = 55.0000 elif s[0] == 'B': r = 61.7354 elif s[0] == 'C': r = 32.7032 elif s[0] == 'D': r = 36.7081 elif s[0] == 'E': r = 41.2035 elif s[0] == 'F': r = 43.6536 elif s[0] == 'G': r = 48.9995 #Transform to target tone #r *= 2 ** (int(s[1]) - 1) for i in s: if ord(i) in range(48,58):#from '0' to '9' r *= 2 ** (int(i) - 1) break #Sharp&Float r *= Music.root24 ** d return round(r) @staticmethod def getTime(t = 2): if len(str(t)) == 1: return 2 ** -int(t) base = -int(t[0]) r = 2 ** base for i in range(len(t) - 1): base -= 1 r += 2 ** base return r @staticmethod def playTone(tone, duration): if tone == 0 or tone == '0': time.sleep(round(Music.getTime(duration) * Music.stdTime)/1000) return Beep(Music.getFrequency(tone), round(Music.getTime(duration) * Music.stdTime)) noise_output = wave.open('noise2.wav', 'w') #Normal 2 2 for stereo noise_output.setparams((2, 2, 44100, 0, 'NONE', 'not compressed')) values = [] for i in range(0, 44100*2): #value = random.randint(-30000, 32000) #d1 = round(math.sin(220* 2*i*math.pi/(44100))*32000) d2 = round( (math.sin(440 * 2*i*math.pi/(44100))*10 + math.sin(880 * 2*i*math.pi/(44100))*7 + math.sin(1760 * 2*i*math.pi/(44100))*4 + math.sin(3520 * 2*i*math.pi/(44100)) + math.sin(220 * 2*i*math.pi/(44100)) + math.sin(660 * 2*i*math.pi/(44100)) + math.sin(330 * 2*i*math.pi/(44100)) + math.sin(100 * 2*i*math.pi/(44100)) + math.sin(200 * 2*i*math.pi/(44100)) )*32000/27) #packed_value = struct.pack('h',d1) pv2 = struct.pack('h',d2) values.append(pv2) values.append(pv2) value_str = values[0] for i in range(len(values)): value_str += values[i] noise_output.writeframes(value_str) noise_output.close() <file_sep>from Music import Music file = open('Полет шмеля.k2tf','r') for line in file: if line == '\n': continue data = line.split() if data[0].lower() == 'speed': t = data[1].split('/') Music.stdTime = 60 * 1000 * 2**int(t[0])/ int(t[1]) else: Music.playTone(data[0],data[1])
a1eedea929a861513f340263ed9c0d668bc31223
[ "Python" ]
3
Python
AsciiShell/MusGen
05fa932b23df3e290fa218452e66e9114cf38c58
aeaa6395862f18158f16b55bc8889d865d700b2a
refs/heads/master
<file_sep>$(document).ready(function() { $("#mainMenu").highlightMenu({ bgColor:'#1A276B', color:'#F2F2F2' }); });<file_sep>$(document).ready(function() { $("#reasons div").hide(); $("#reasons li").click(function() { $(this).children().slideToggle(1500, "swing"); }); });<file_sep>$(document).ready(function() { //preload images $("#imageList a").each(function() { var swappedImage = new Image(); swappedImage.src = $(this).attr("href"); }); //set up event handlers for links $("#imageList a").hover( function(event) { $(this).stop(true).animate({top: 15}, "fast"); //swap image $("#image").attr("src", $(this).attr("href")); //swap caption $("#caption").text($(this).attr("title")); //cancel the default action of the link event.preventDefault(); }, function(event) { $(this).stop(true).animate({ top: 0 }, "fast"); } ); $("imageList:first-child:first-child").focus(); });<file_sep>$(document).ready(function() { $("article").hover( function() { $(this).addClass("newCSS"); }, function() { $(this).removeClass("newCSS") } ); });<file_sep>(function($){ $.fn.highlightMenu= function(options) { var defaults= $.extend({ 'bgColor' : '#1A276B', 'color' : '#F2F2F2' }, options); return this.each(function() { // alert("hello"); var items = $("li a"); var o = defaults; items.css('font-family', 'cursive') .css('font-weight', 'bold') .css('text-decoration', 'none') .css('background-color', o.bgColor) .css('color', o.color); items.mouseover(function() { $(this).css('background-color', "#29C9F8") .css('color', "#000000"); }); items.mouseout(function() { $(this).css('background-color', o.bgColor) .css('color', o.color); }); }); } })(jQuery);<file_sep>$(document).ready(function() { // the handler for the click event of the submit button $("#contactForm").submit(function(event) { var isValid = true; // validate the email entry with a regular expression var emailPattern = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/; var email = $("#email").val().trim(); if (email == "") { $("#email").next().text("This field is required."); isValid = false; } else if ( !emailPattern.test(email) ) { $("#email").next().text("Must be a valid email address."); isValid = false; } else { $("#email").next().text(""); } $("#email").val(email); // validate the first name entry var firstName = $("#fName").val().trim(); if (firstName == "") { $("#fName").next().text("This field is required."); isValid = false; } else { $("#fName").next().text(""); } $("#fName").val(firstName); // validate the last name entry var lastName = $("#lName").val().trim(); if (lastName == "") { $("#lName").next().text("This field is required."); isValid = false; } else { $("#lName").next().text(""); } $("#lName").val(lastName); // validate the phone number with a regular expression var phonePattern = /^\d{3}-\d{3}-\d{4}$/; var phone = $("#phone").val().trim(); if (phone == "") { $("#phone").next().text("This field is required."); isValid = false; } else if ( !phonePattern.test(phone) ) { $("#phone").next().text("Use 999-999-9999 format."); isValid = false; } else { $("#phone").next().text(""); } $("#phone").val(phone); // validate the question entry var questions = $("#questions").val().trim(); if (questions == "") { $("#questions").next().text("This field is required."); isValid = false; } else { $("#questions").next().text(""); } $("#questions").val(questions); // prevent the submission of the form if any entries are invalid if (isValid == false) { event.preventDefault(); } } // end function ); // end submit });<file_sep># Fridgance This repository contains code for a website developed using HTML5, CSS3 and Javascript.
f56e081b70213831ff71d3908a9fbf1108cd84dd
[ "JavaScript", "Markdown" ]
7
JavaScript
vid9sharma/Fridgance
a4f7f17f81baa64ded6842ded4b29c8732622562
56cc16a66c3a7471f80fd0d788ce92c75b728b49
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ContextBountAttributeTest { [Interceptor] class FileLoops : ContextBoundObject, IFileAccess { private string _file; public FileLoops(string filename) { _file = filename; } // No matter what the method will return a value or not, // the method in attribute can be execute [MethodLog] public bool Create() { Console.WriteLine(string.Format("Create a file : {0}", _file)); return true; } [MethodPreprocess] public void Delete() { Console.WriteLine(string.Format("Delete a file : {0}", _file)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ContextBountAttributeTest { public interface IFileAccess { bool Create(); void Delete(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Contexts; using System.Runtime.Remoting.Messaging; using System.Text; using System.Threading.Tasks; namespace ContextBountAttributeTest { //貼在類上的標簽 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class InterceptorAttribute : ContextAttribute, IContributeObjectSink { public InterceptorAttribute() : base("Interceptor") { } //實現IContributeObjectSink接口當中的消息接收器接口 public IMessageSink GetObjectSink(MarshalByRefObject obj, IMessageSink nextSink) { return new InterceptorHandler(nextSink); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Contexts; using System.Runtime.Remoting.Messaging; using System.Text; using System.Threading.Tasks; namespace ContextBountAttributeTest { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public abstract class InterceptorMethodAttribute : Attribute { public abstract void OnExecuting(); public abstract void OnExecuted(); } public sealed class MethodLogAttribute : InterceptorMethodAttribute { public override void OnExecuted() { Console.WriteLine("Logged"); } public override void OnExecuting() { } } public sealed class MethodPreprocessAttribute : InterceptorMethodAttribute { public override void OnExecuted() { } public override void OnExecuting() { Console.WriteLine("Logging"); } } } <file_sep># AopContextBoundObject Ref: <NAME>'s AOP Project 使用Arrtibute就能達到AOP的功能,原程式碼參考<NAME>的投影片 <file_sep>using System; using System.Runtime.Remoting.Messaging; namespace ContextBountAttributeTest { internal class InterceptorHandler : IMessageSink { private IMessageSink nextSink; public IMessageSink NextSink { get { return nextSink; } } public InterceptorHandler(IMessageSink next) { this.nextSink = next; } public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink) { return null; } //同步處理方法 public IMessage SyncProcessMessage(IMessage msg) { IMessage retMsg = null; //方法調用消息接口 IMethodCallMessage call = msg as IMethodCallMessage; //如果被調用的方法沒打MyInterceptorMethodAttribute標簽 if (call == null || (Attribute.GetCustomAttribute(call.MethodBase, typeof(InterceptorMethodAttribute))) == null) { retMsg = nextSink.SyncProcessMessage(msg); } //如果打了MyInterceptorMethodAttribute標簽 else { if (Attribute.GetCustomAttribute(call.MethodBase, typeof(MethodLogAttribute)) != null ) { MethodLogAttribute log = new MethodLogAttribute(); log.OnExecuted(); } retMsg = nextSink.SyncProcessMessage(msg); if (Attribute.GetCustomAttribute(call.MethodBase, typeof(MethodPreprocessAttribute)) != null) { MethodPreprocessAttribute preprocess = new MethodPreprocessAttribute(); preprocess.OnExecuting(); } } return retMsg; } } }
a98431e16e30c05aae7643eb24f189fac93599a8
[ "Markdown", "C#" ]
6
C#
LoopsLu/AopContextBoundObject
75682dbaee7c852004947ddf87f801a5f06bef40
8378cf88a98e08454eaf19b1654bb2453c53e696
refs/heads/master
<repo_name>Articulate911/Crawler-Dangdang<file_sep>/README.md OKOK You can read me now. <file_sep>/dangdang/spiders/main.py from scrapy import cmdline cmdline.execute('scrapy crawl dangdang_spider -o book.json -s FEED_EXPORT_ENCODING=UTF-8'.split()) <file_sep>/dangdang/spiders/dangdang_spider.py # -*- coding: utf-8 -*- import scrapy from dangdang.items import DangdangItem class DangdangSpiderSpider(scrapy.Spider): name = 'dangdang_spider' allowed_domains = ['bang.dangdang.com'] # start_urls = ['http://bang.dangdang.com/books/fivestars/1-1'] def start_requests(self): for i in range(1,26): yield scrapy.Request('http://bang.dangdang.com/books/fivestars/1-' + str(i), callback=self.parse) def parse(self, response): # print(response.text) book_list = response.xpath('//div[@class="bang_list_box"]/ul/li') # print(book_list) ch1 = '(' ch2 = '(' for book in book_list: dangdang_item = DangdangItem() serial = book.xpath('./div[1]/text()').extract_first() # print(serial[0]) dangdang_item['serial'] = serial[:-1] name_raw = book.xpath('./div[@class="name"]/a/text()').extract_first() if name_raw.find(ch1) != -1: dangdang_item['name'] = name_raw[:name_raw.find(ch1)] elif name_raw.find(ch2) != -1: dangdang_item['name'] = name_raw[:name_raw.find(ch2)] else: dangdang_item['name'] = name_raw score_raw = book.xpath('./div[@class="star"]/span[@class="level"]/span/@style').extract_first() dangdang_item['score'] = float(score_raw[7:-2]) dangdang_item['publisher'] = book.xpath('./div[6]/a/text()').extract_first() dangdang_item['price'] = book.xpath('./div[@class="price"]/p/span[@class="price_n"]/text()').extract_first() # print(dangdang_item['star']) yield dangdang_item
9f541ee7a5e227f156db94cba2633f87adbedd13
[ "Markdown", "Python" ]
3
Markdown
Articulate911/Crawler-Dangdang
08dd742de8f7bf10501eeedb4a79ec8f3cecb02c
c62803ffe58186073e5dce36bfbb9d74b7d0351b
refs/heads/master
<repo_name>derRinat/js_match3<file_sep>/js/settings.js (function(game) { var Settings = { board: { width: 8, height: 8, el: '#board' }, tile_types: ['blue', 'green', 'purple', 'red', 'yellow'], tile: { width: 32, height: 32, border: 2 }, scores: { match_scores: 1 }, min_match_length: 3, max_match_length: 6, mode: 'timeout', // || moves timeout: 1, // timeout in minutes to end moves_count: 500, // moves count to end messages: { TIME_IS_OUT: 'Time is out :(', NO_MORE_MOVES: 'Game finished' } }; game.Settings = Settings; })(GameScope);<file_sep>/js/init.js /** * Init game */ $(function() { //console.log(GameScope); var game = new Game(GameScope.Board, GameScope.BoardView, GameScope.Settings); })<file_sep>/js/game.js var Game = function(board, boardView, options) { var self = this, scores = 0, moves = 0; /** Start game */ this.startGame = function() { scores = 0; moves = 0; board.createBoard(); boardView.createBoard(); } /** Finish game */ this.finishGame = function(opts) { scores = boardView.getScores(); board.resetBoard(); boardView.resetBoard(); self.finishGameView(opts); } /** Start game in view */ this.startGameView = function() { var modeDiv = options.mode === 'timeout' ? '.time' : '.moves'; $('.start').addClass('hide'); $('.scores span, .time span').text(0); $('.moves span').text(options.moves_count); $('.gameData').removeClass('hide'); $(modeDiv).removeClass('hide'); } /** Finish game in view */ this.finishGameView = function(opts) { $(options.board.el).find('.tile').remove(); // remove all tiles $('.start .message').text(opts.message); $('.start .scores').text(scores); $('.gameData').addClass('hide'); $('.start').removeClass('hide'); $('.start a').show(); } /** Update moves count */ this.updateMovesCount = function(opts) { $('.moves span').text(opts.moves); } /** Update user scores */ this.updateUserScores = function(opts) { $('.scores span').text(opts.scores); } /** Init game timer */ this.initTimer = function() { if (options.mode === 'timeout') { function countdown(minutes, callback) { var seconds = 60; var mins = minutes; function tick() { var counter = $(".time span"), current_minutes = mins - 1; counter.removeClass('warning'); seconds--; counter.html(current_minutes + ':' + (seconds < 10 ? '0' : '') + seconds); if (current_minutes === 0 && seconds < 10 && !$(counter).hasClass("warning")) { $(".time span").addClass('warning') } if (seconds === 0 && current_minutes === 0) { callback(); } else { if (seconds > 0) { setTimeout(tick, 1000); } else { if (mins > 1) { setTimeout(function() { countdown(mins - 1); }, 1000); } } } } tick(); } countdown(options.timeout, function() { self.finishGame({ message: options.messages.TIME_IS_OUT }); }); } } /** Start button click event */ $('.start a').click(function() { $(this).hide(); self.startGameView(); self.initTimer(); self.startGame(); }) $(document).on('finishGame', function(e, args) { self.finishGame({ message: args.message }); }); $(document).on('updateMovesCount', function(e, args) { self.updateMovesCount({ moves: args.moves }); }); $(document).on('updateUserScores', function(e, args) { self.updateUserScores({ scores: args.scores }); }); }<file_sep>/README.md Match3 game prototype Pure JS, JQuery as helper <file_sep>/js/board.js (function(game) { var settings = game.Settings, peaceId = 0, Board = {}; Board.tiles = [], /** Creates game board, generates game tiles */ Board.createBoard = function() { var w = settings.board.width, h = settings.board.height; Board.createTiles(w, h); }; /** Reset game board */ Board.resetBoard = function() { Board.tiles = []; peaceId = 0; } /** * Create tiles * @param {Number} w board width (tiles count in x axis) * @param {Number} h board height (tiles count in y axis) */ Board.createTiles = function(w, h) { for (var x = 0; x < w; x++) { Board.tiles.push(new Array(this.height)); } do { peaceId = 0; for (var y = 0; y < h; y++) { for (var x = 0; x < w; x++) { ++peaceId; var type = settings.tile_types[$.rand(0, settings.tile_types.length - 1)]; // TODO: pack it to helper Board.tiles[y][x] = { id: peaceId, type: type, empty: 0 } } } } while (Board.getMatches() || !Board.getMoves()); // try create board until no matches and legal moves }; /** * Create one tile object on x/y position * @param {Number} x * @param {Number} y * @param {Function} callback */ Board.createOneTile = function(x, y, callback) { ++peaceId; Board.tiles[x][y] = { id: peaceId, type: settings.tile_types[$.rand(0, settings.tile_types.length - 1)], empty: 0 } callback(Board.tiles[x][y], x, y); } /** * Find matches on board * @return {Array || false} matches array */ Board.getMatches = function() { var w = settings.board.width, h = settings.board.height, matches = []; for (var y = 0; y < h; y++) { for (var x = 0; x < w; x++) { if (typeof Board.tiles[y] !== 'undefined' && Board.tiles[y][x] !== 'undefined') { var type = Board.tiles[y][x].type, match = []; for (var i = x; i < w; i++) { if (Board.tiles[y][i].type === type) { match.push({ type: type, x: i, y: y, id: Board.tiles[y][i].id }); } else { break; } } if (match.length >= settings.min_match_length) { x = (i - 1); matches.push(match); } } } } for (var x = 0; x < w; x++) { for (var y = 0; y < h; y++) { var type = Board.tiles[y][x].type, match = []; for (var i = y; i < h; i++) { if (Board.tiles[i][x].type === type) { match.push({ type: type, x: x, y: i, id: Board.tiles[i][x].id }); } else { break; } } if (match.length >= settings.min_match_length) { y = (i - 1); matches.push(match); } } } return matches.length > 0 ? matches : false; } /** * Destroy tile ob board, mark it as empty * @param {Number} id */ Board.destroyTile = function(id) { Board.setTileProperties(id, { empty: 1 }); } /** * Get legal moves on board * @return {Array || false} moves array */ Board.getMoves = function() { var w = settings.board.width, h = settings.board.height, coords = []; for (var y = 0; y < h; y++) { for (var x = 0; x < w; x++) { var type = Board.tiles[y][x].type; // Check to the right if (x < (w - 2)) { // Right straight if (x < (w - 3)) { // XX X if ((Board.tiles[y][x + 1].type == type) && (Board.tiles[y][x + 3].type == type)) { coords.push({ type: type, from_x: x + 3, from_y: y, to_x: x + 2, to_y: y }); } // X XX if ((Board.tiles[y][x + 2].type == type) && (Board.tiles[y][x + 3].type == type)) { coords.push({ type: type, from_x: x, from_y: y, to_x: x + 1, to_y: y }); } } // Right up if (y > 0) { // XX // X if ((Board.tiles[y - 1][x + 1].type == type) && (Board.tiles[y - 1][x + 2].type == type)) { coords.push({ type: type, from_x: x, from_y: y, to_x: x, to_y: y - 1 }); } // X // X X if ((Board.tiles[y - 1][x + 1].type == type) && (Board.tiles[y][x + 2].type == type)) { coords.push({ type: type, from_x: x + 1, from_y: y - 1, to_x: x + 1, to_y: y }); } // X // XX if ((Board.tiles[y][x + 1].type == type) && (Board.tiles[y - 1][x + 2].type == type)) { coords.push({ type: type, from_x: x + 2, from_y: y - 1, to_x: x + 2, to_y: y }); } } // Right down if (y < (h - 1)) { // X // XX if ((Board.tiles[y + 1][x + 1] == type) && (Board.tiles[y + 1][x + 2].type == type)) { coords.push({ type: type, from_x: x, from_y: y, to_x: x, to_y: y + 1 }); } // X X // X if ((Board.tiles[y + 1][x + 1].type == type) && (Board.tiles[y][x + 2].type == type)) { coords.push({ type: type, from_x: x + 1, from_y: y + 1, to_x: x + 1, to_y: y }); } // XX // X if ((Board.tiles[y][x + 1].type == type) && (Board.tiles[y + 1][x + 2].type == type)) { coords.push({ type: type, from_x: x + 2, from_y: y + 1, to_x: x + 2, to_y: y }); } } } // Check down if (y < (h - 2)) { // Down straight if (y < (h - 3)) { // X // X // // X if ((Board.tiles[y + 1][x].type == type) && (Board.tiles[y + 3][x].type == type)) { coords.push({ type: type, from_x: x, from_y: y + 3, to_x: x, to_y: y + 2 }); } // X // // X // X if ((Board.tiles[y + 2][x].type == type) && (Board.tiles[y + 3][x].type == type)) { coords.push({ type: type, from_x: x, from_y: y, to_x: x, to_y: y + 1 }); } } // Down left if (x > 0) { // X // X // X if ((Board.tiles[y + 1][x - 1].type == type) && (Board.tiles[y + 2][x - 1].type == type)) { coords.push({ type: type, from_x: x, from_y: y, to_x: x - 1, to_y: y }); } // X // X // X if ((Board.tiles[y + 1][x - 1].type == type) && (Board.tiles[y + 2][x].type == type)) { coords.push({ type: type, from_x: x - 1, from_y: y + 1, to_x: x, to_y: y + 1 }); } // X // X // X if ((Board.tiles[y + 1][x].type == type) && (Board.tiles[y + 2][x - 1].type == type)) { coords.push({ type: type, from_x: x - 1, from_y: y + 2, to_x: x, to_y: y + 2 }); } } // Down right if (x < (w - 1)) { // X // X // X if ((Board.tiles[y + 1][x + 1].type == type) && (Board.tiles[y + 2][x + 1].type == type)) { coords.push({ type: type, from_x: x, from_y: y, to_x: x + 1, to_y: y }); } // X // X // X if ((Board.tiles[y + 1][x + 1].type == type) && (Board.tiles[y + 2][x].type == type)) { coords.push({ type: type, from_x: x + 1, from_y: y + 1, to_x: x, to_y: y + 1 }); } // X // X // X if ((Board.tiles[y + 1][x].type == type) && (Board.tiles[y + 2][x + 1].type == type)) { coords.push({ type: type, from_x: x + 1, from_y: y + 2, to_x: x, to_y: y + 2 }); } } } } // for x } // for y return coords.length > 0 ? coords : false; } /** Return tiles array */ Board.getTiles = function() { return Board.tiles; } /** * Execute callback function for each tile on board * @param {Function} callback */ Board.eachTile = function(callback) { var w = settings.board.width, h = settings.board.height, tiles = Board.getTiles(); for (y = 0; y < h; ++y) { for (x = 0; x < w; ++x) { if (typeof Board.tiles[x] !== 'undefined' && Board.tiles[x][y] !== 'undefined') { callback(Board.tiles[x][y], x, y); } }; }; } /** * Execute callback function for each empty tile on board * @param {Function} callback */ Board.eachEmptyTile = function(callback) { var w = settings.board.width, h = settings.board.height, tiles = Board.getTiles(); for (y = 0; y < h; ++y) { for (x = 0; x < w; ++x) { if (typeof Board.tiles[x] !== 'undefined' && Board.tiles[x][y] !== 'undefined') { if (Board.tiles[x][y].empty == 1) { callback(Board.tiles[x][y], x, y); } } }; }; } /** * Get all empty tiles * @return {Array} empty tiles */ Board.getEmptyTiles = function() { var toreturn = [], w = settings.board.width, h = settings.board.height, tiles = Board.getTiles(); for (y = 0; y < h; ++y) { for (x = 0; x < w; ++x) { if (typeof Board.tiles[x] !== 'undefined' && Board.tiles[x][y] !== 'undefined') { if (Board.tiles[x][y].empty == 1) { toreturn.push({ x: x, y: y, type: Board.tiles[x][y].type, id: Board.tiles[x][y].id }); } } }; }; return toreturn; } /** * Get tile by tile id * @param {Number} id tile id * @return {Object || null} */ Board.getTileById = function(id) { var w = settings.board.width, h = settings.board.height, tiles = Board.getTiles(); for (y = 0; y < h; ++y) { for (x = 0; x < w; ++x) { if (typeof Board.tiles[x] !== 'undefined' && Board.tiles[x][y] !== 'undefined') { if (Board.tiles[x][y].id == id) return Board.tiles[x][y]; } }; }; return null; } /** * @deprecated not in use */ Board.recreateEmptyTiles = function(callback) { Board.eachEmptyTile(function(tile, x, y) { Board.createOneTile(x, y, callback); }) } /** * Get tile coordinates by tile id * @param {Number} id tile id * @return {Object || null} */ Board.getTileCoordsById = function(id) { var w = settings.board.width, h = settings.board.height, tiles = Board.getTiles(); for (y = 0; y < h; ++y) { for (x = 0; x < w; ++x) { if (typeof Board.tiles[x] !== 'undefined' && Board.tiles[x][y] !== 'undefined') { if (Board.tiles[x][y].id == id) return { x: x, y: y }; } }; }; return null; } /** * Get tile by coordinates * @deprecated not in use * @param {Number} y * @param {Bumber} x */ Board.getTile = function(y, x) { return Board.tiles[y][x]; } /** * Set tile properties by tile id * @param {Number} id * @param {Object} props properties */ Board.setTileProperties = function(id, props) { var w = settings.board.width, h = settings.board.height, tiles = Board.getTiles(); for (y = 0; y < h; ++y) { for (x = 0; x < w; ++x) { if (typeof Board.tiles[x] !== 'undefined' && Board.tiles[x][y] !== 'undefined') { if (Board.tiles[x][y].id == id) { for (var p in props) { Board.tiles[x][y][p] = props[p]; } } } }; }; } /** * Swap tiles * @param {Number} x1 * @param {Number} y1 * @param {Number} x2 * @param {Number} y2 * @return {Array} */ Board.swapTiles = function(x1, y1, x2, y2) { var tmp1 = Board.tiles[x1][y1], tmp2 = Board.tiles[x2][y2]; Board.tiles[x1][y1] = tmp2; Board.tiles[x2][y2] = tmp1; //Board.debug(); return Board.tiles; } /** Debug , print board state */ Board.debug = function() { console.log("Board state: "); for (var i = 0; i < settings.board.height; i++) { var line = Board.getRow(i); var pieces = ""; for (var x in line) { var type = line[x].type.substring(0, 1), id = line[x].id, e = line[x].empty; pieces += '|' + type + ' ' + id + ' [' + x + ',' + i + '] (' + e + ')'; } console.log(pieces); } } /** * Get tile neighbour * @param {Number} coord_x * @param {Number} coord_y * @param {Object} direction * @return {Object} */ Board.neighbourOf = function(coord_x, coord_y, direction) { var x = coord_x + 1 * direction.x, y = coord_y + 1 * direction.y; return Board.tiles[x][y]; } /** * Get column * @param {Number} column * @param {boolean} reverse * @return {Array} */ Board.getColumn = function(column, reverse) { var toreturn = []; for (var i = 0; i < settings.board.height; i++) { toreturn.push(Board.tiles[column][i]); } return reverse ? toreturn.reverse() : toreturn; }; /** * Get row * @param {Number} roum * @param {boolean} reverse * @return {Array} */ Board.getRow = function(row, reverse) { var pieces = []; for (var i in Board.tiles) { pieces.push(Board.tiles[i][row]); } return reverse ? pieces.reverse() : pieces; }; game.Board = Board; })(GameScope);
07e679eccd717955297468ebce258861328a4880
[ "JavaScript", "Markdown" ]
5
JavaScript
derRinat/js_match3
6ea2fad8313b56ca8bcf2e3dd6715535440e1292
b2454d0d088ba999ed8e22516c807545d3228e35
refs/heads/master
<repo_name>karmeYin/git-repository<file_sep>/girledemo/src/main/java/com/yin/girledemo/utils/ResultUtil.java package com.yin.girledemo.utils; import com.yin.girledemo.domain.Result; public class ResultUtil { public static Result success(Object data){ Result result=new Result(); result.setData(data); result.setMsg("成功"); result.setCode(1); return result; } public static Result success(){ return success(null); } public static Result error(Integer code, String msg,Object object) { Result result = new Result(); result.setCode(code); result.setMsg(msg); result.setData(object); return result; } public static Result error(Integer code,String msg){ return error(code,msg,null); } } <file_sep>/girledemo/src/main/java/com/yin/girledemo/timer/MySchedulTask.java package com.yin.girledemo.timer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class MySchedulTask { private final static Logger logger = LoggerFactory.getLogger(MySchedulTask.class); @Scheduled(cron="0/5 * * * * ?") public void expressLove(){ System.out.println("小火龙身体健康,父母身体健康,亲朋好友身体健康"); } } <file_sep>/girledemo/src/main/java/com/yin/girledemo/service/GirlService.java package com.yin.girledemo.service; import com.yin.girledemo.domain.Girl; import com.yin.girledemo.enums.ResultEnum; import com.yin.girledemo.exception.GirlException; import com.yin.girledemo.repository.GirlRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class GirlService { @Autowired GirlRepository girlRepository; @Transactional public void insertTwo(){ Girl girl=new Girl(); girl.setAge(25); girl.setCupSize("A"); girlRepository.save(girl); Girl girl2=new Girl(); girl2.setAge(28); girl2.setCupSize("DDD"); girlRepository.save(girl2); } public void getAge(Integer id) throws Exception { Girl girl = girlRepository.findById(id).get(); Integer age=girl.getAge(); if (age<12){ throw new GirlException(ResultEnum.PRIMARY_SCHOOL); }else if(age>=12 && age<18){ throw new GirlException(ResultEnum.MIDDLE_SCHOOL); } } }
11d7aedd22533e429aabebb6310805901efd96fb
[ "Java" ]
3
Java
karmeYin/git-repository
8b497b40af652ca7736f3d8338c3164a65eb75e9
ed08d86ac8e212fd03d130f7270f5e01c80e99e8
refs/heads/main
<repo_name>ducreations/Clinic<file_sep>/app/models/physician.rb class Physician < ApplicationRecord has_many :appointments has_many :patiens, :through :appointments end <file_sep>/app/models/patient.rb class Patient < ApplicationRecord has_many :appointments has_many :physicians, :through :appointments end <file_sep>/db/schema.rb ActiveRecord::Schema.define(version: 2021_08_18_022519) do enable_extension "plpgsql" create_table "appointments", force: :cascade do |t| t.integer "physician_id" t.integer "patient_id" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "patients", force: :cascade do |t| t.string "name" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "physicians", force: :cascade do |t| t.string "name" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end end <file_sep>/config/routes.rb Rails.application.routes.draw do get 'clinic/index' root to: 'clinic#index' end
49acf0ffb45dad7e8e95ccbf825580d2834b4d03
[ "Ruby" ]
4
Ruby
ducreations/Clinic
b07360172f27ddf75cd59ac4bb2e84b6d4383a2c
fdcae060ff9f08cfd9d01748f7e8499f2f2c23bf
refs/heads/master
<repo_name>ayadalati/al-wathba<file_sep>/app/website/sign-in/sign-in.component.ts import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-sign-in', templateUrl: './sign-in.component.html', styleUrls: ['./sign-in.component.css'] }) export class SignInComponent implements OnInit { constructor(private router:Router) { } go_to_admin_panel() { var x:number =parseInt((<HTMLInputElement>document.getElementById("member_number")).value); if(x==1) {this.router.navigate(["/admin-panel"]);} else if(x==2) { this.router.navigate(["/coach-panel"]); } else if(x==3) { this.router.navigate(["/player-panel"]); } else if(x==4) { this.router.navigate(["/manger-panel"]); } } ngOnInit(): void { } }
b5dc2b15e58649a0f36930cbd1c1fd3e2b051b60
[ "TypeScript" ]
1
TypeScript
ayadalati/al-wathba
61ae3c01b0ec8986ffeaa61a04dbf92fbeec4171
ec289a17604883c1b2917b78ab01a4ff356b0875
refs/heads/master
<file_sep><?php /** * Blossom is a custom Theme class for the Blossom theme. * * @package Habari */ /** * @todo This stuff needs to move into the custom theme class: */ // Apply Format::autop() to post content... Format::apply( 'autop', 'post_content_out' ); // Apply Format::autop() to post excerpt... Format::apply( 'autop', 'post_content_excerpt' ); // Apply Format::autop() to comment content... Format::apply( 'autop', 'comment_content_out' ); // Apply Format::tag_and_list() to post tags... Format::apply( 'tag_and_list', 'post_tags_out' ); // Limit post length to 1 paragraph or 100 characters. This theme only works with excerpts. Format::apply_with_hook_params( 'more', 'post_content_excerpt', '<span class="read-on">read on</span>', 100, 1 ); // We must tell Habari to use Blossom as the custom theme class: define( 'THEME_CLASS', 'Blossom' ); /** * A custom theme for Blossom output */ class Blossom extends Theme { /** * Add additional template variables to the template output. * * You can assign additional output values in the template here, instead of * having the PHP execute directly in the template. The advantage is that * you would easily be able to switch between template types (RawPHP/Smarty) * without having to port code from one to the other. * * You could use this area to provide "recent comments" data to the template, * for instance. * * Also, this function gets executed *after* regular data is assigned to the * template. So the values here, unless checked, will overwrite any existing * values. */ public function add_template_vars() { $this->habari = Site::get_url( 'habari' ); if ( !$this->posts ) { $this->posts = Posts::get( array( 'content_type' => 'entry', 'status' => Post::status('published') ) ); } $this->top_posts = array_slice((array)$this->posts, 0, 2); $params = array( 'content_type' => 'entry', 'status' => Post::status('published'), 'limit' => 7 ); $this->previous_posts = array_slice((array)Posts::get( $params ), 2, 5); if ( !$this->user ) { $this->user = User::identify(); } if ( !$this->page ) { $this->page = isset( $page ) ? $page : 1; } if ( !$this->tags ) { $this->tags = Tags::get(); } if ( !$this->pages ) { $this->pages = Posts::get( array( 'content_type' => 'page', 'status' => Post::status('published') ) ); } // Use the configured data format $date_format = Options::get('blossom_date_format'); if ( $date_format == 'american' ) { // Apply Format::nice_date() to post date - US style Format::apply( 'nice_date', 'post_pubdate_out', 'g:ia m/d/Y' ); } else { // Apply Format::nice_date() to post date - European style Format::apply( 'nice_date', 'post_pubdate_out', 'g:ia d/m/Y' ); } // del.icio.us username. $delicious_username = Options::get('blossom_delicious_username'); if ( $delicious_username == '' ) { $delicious_username = 'michael_c_harris'; } $this->delicious = $delicious_username; // Default to hidden $this->show_interests = (bool) Options::get('show_interests'); $this->show_other_news = (bool) Options::get('show_other_news'); parent::add_template_vars(); } /** * Make this theme configurable * * @param boolean $configurable Whether the theme is configurable * @param string $name The theme name * @return boolean Whether the theme is configurable */ public function filter_theme_config($configurable) { $configurable = true; return $configurable; } /** * Respond to the user selecting 'configure' on the themes page * */ public function action_theme_ui() { $form = new FormUI( 'blossom_theme' ); $form->append('text', 'delicious_username', 'blossom_delicious_username', _t('Delicious Username:')); $form->append( 'select', 'date_format', 'blossom_date_format', 'Date format:' ); $form->date_format->options = array('european' => 'European', 'american' => 'American'); $form->append('fieldset', 'show_interests_fs', 'Show "Interests"?'); $form->show_interests_fs->append('radio', 'show_interests', 'option:show_interests', 'Show "Interests"?', array("1" => "Yes", "0" => "No")); $form->append('fieldset', 'show_other_news_fs', 'Show "Other News"?'); $form->show_other_news_fs->append('radio', 'show_other_news', 'option:show_other_news', 'Show "Other News"?', array("1" => "Yes", "0" => "No")); $form->append( 'submit', 'save', _t( 'Save' ) ); $form->set_option( 'success_message', _t( 'Configuration saved' ) ); $form->out(); } } ?> <file_sep><?php /** * AudioScrobbler Plugin * * Usage: <?php $theme->audioscrobbler(); ?> * **/ class AudioScrobbler extends Plugin { private $config = array(); private $class_name = ''; private $default_options = array( 'username' => '', 'cache' => '60' ); /** * Required plugin information * @return array The array of information **/ public function info() { return array( 'name' => 'Audioscrobbler', 'version' => '0.4', 'url' => 'http://code.google.com/p/bcse/wiki/Audioscrobbler', 'author' => '<NAME>', 'authorurl' => 'http://blog.bcse.info/', 'license' => 'Apache License 2.0', 'description' => 'Display music you listened recently on your blog.' ); } /** * Add update beacon support **/ public function action_update_check() { Update::add('Audioscrobbler', 'cb82d3d0-231f-11dd-bd0b-0800200c9a66', $this->info->version); } /** * Add actions to the plugin page for this plugin * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id **/ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()) { $actions[] = _t('Configure', $this->class_name); } return $actions; } /** * Respond to the user selecting an action on the plugin page * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook **/ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id == $this->plugin_id()) { switch ($action) { case _t('Configure', $this->class_name) : $ui = new FormUI($this->class_name); $ui->append('text', 'username', 'option:' . $this->class_name . '__username', _t('Last.fm Username', $this->class_name)); $ui->username->add_validator(array($this, 'validate_username')); $ui->username->add_validator('validate_required'); $ui->append('text', 'cache', 'option:' . $this->class_name . '__cache', _t('Cache Expiry (in seconds)', $this->class_name)); $ui->cache->add_validator(array($this, 'validate_uint')); $ui->append('submit', 'save', _t('Save', $this->class_name)); $ui->set_option('success_message', _t('Options saved', $this->class_name)); $ui->out(); break; } } } public function validate_username($username) { if (!ctype_alnum($username)) { return array(_t('Your Last.fm username is not valid.', $this->class_name)); } return array(); } public function validate_uint($value) { if (!ctype_digit($value) || strstr($value, '.') || $value < 0) { return array(_t('This field must be positive integer.', $this->class_name)); } return array(); } /** * Returns true if plugin config form values defined in action_plugin_ui should be stored in options by Habari * @return bool True if options should be stored **/ public function updated_config($ui) { return true; } /** * Add last Audioscrobbler status, time, and image to the available template vars * @param Theme $theme The theme that will display the template **/ public function theme_audioscrobbler($theme, $params = array()) { $params = array_merge($this->config, $params); $cache_name = $this->class_name . '__' . md5(serialize($params)); if ($params['username'] != '') { $track_url = 'http://ws.audioscrobbler.com/1.0/user/' . urlencode($params['username']) . '/recenttracks.xml'; if (Cache::has($cache_name)) { $xml = new SimpleXMLElement(Cache::get($cache_name)); $theme->track = $xml->track; } else { try { // Get XML content via Audioscrobbler API $call = new RemoteRequest($track_url); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { throw Error::raise(_t('Unable to contact Last.fm.', $this->class_name)); } $response = $call->get_response_body(); // Parse XML content $xml = new SimpleXMLElement($response); $theme->track = $xml->track; Cache::set($cache_name, $response, $params['cache']); } catch (Exception $e) { $theme->track = $e->getMessage(); } } } else { $theme->track = _t('Please set your username in the Audioscrobbler plugin config.', $this->class_name); } return $theme->fetch('audioscrobbler'); } /** * On plugin init, add the template included with this plugin to the available templates in the theme */ public function action_init() { $this->class_name = strtolower(get_class($this)); // Set the default options foreach ($this->default_options as $name => $unused) { $this->config[$name] = Options::get($this->class_name . '__' . $name); } $this->load_text_domain($this->class_name); $this->add_template('audioscrobbler', dirname(__FILE__) . '/audioscrobbler.php'); } } ?> <file_sep><?php /** * Socialink * adding Social Bookmark Links to your posts. * * @package socialink * @version $Id$ * @author ayunyan <<EMAIL>> * @author rickc (@535) * @author dmondark (@582) * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link http://ayu.commun.jp/habari-socialink */ class Socialink extends Plugin { var $services = array( // Global 'email' => array('name' => 'Email', 'url' => 'mailto:?subject=%TITLE%&body=%PERMALINK%'), 'digg' => array('name' => 'Digg', 'url' => 'http://digg.com/submit?phase=2&url=%PERMALINK%'), 'delicious' => array('name' => 'delicious', 'url' => 'http://delicious.com/save?url=%PERMALINK%&title=%TITLE%&v=5&jump=yes'), 'technorati' => array('name' => 'Technorati', 'url' => 'http://technorati.com/faves?add=%PERMALINK%'), 'google' => array('name' => 'Google', 'url' => "javascript:(function(){var a=window,b=document,c=encodeURIComponent,d=a.open('http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=%PERMALINK%&amp;title=%TITLE%','bkmk_popup','left='+((a.screenX||a.screenLeft)+10)+',top='+((a.screenY||a.screenTop)+10)+',height=420px,width=550px,resizable=1,alwaysRaised=1');a.setTimeout(function(){d.focus()},300)})();"), 'yahoo' => array('name' => 'Yahoo! My Web 2.0', 'url' => 'http://myweb2.search.yahoo.com/myresults/bookmarklet?u=%PERMALINK%&amp;t=%TITLE%'), 'furl' => array('name' => 'furl', 'url' => 'http://www.furl.net/storeIt.jsp?u=%PERMALINK%'), 'reddit' => array('name' => 'Reddit', 'url' => 'http://reddit.com/submit?url=%PERMALINK%&amp;title=%PERMALINK%'), 'magnolia' => array('name' => 'Ma.gnolia', 'url' => 'http://ma.gnolia.com/bookmarklet/add?url=%PERMALINK%&amp;title=%TITLE%'), 'faves' => array('name' => 'Faves', 'url' => 'http://faves.com/Authoring.aspx?u=%PERMALINK%&amp;t=%TITLE%'), 'blinklist' => array('name' => 'blinklist', 'url' => 'http://www.blinklist.com/?Action=Blink/addblink.php&amp;Description=&amp;Url=%PERMALINK%&amp;Title=%TITLE%'), 'stumbleupon' => array( 'name' => 'StumbleUpon', 'url'=> 'http://www.stumbleupon.com/submit?url=%PERMALINK%&amp;title=%TITLE%'), 'diigo' => array( 'name' => 'Diigo', 'url'=> 'hhttp://www.diigo.com/post?url=%PERMALINK%&amp;title=%TITLE%'), 'facebook' => array('name' => 'Facebook', 'url' => 'http://www.facebook.com/share.php?u=%PERMALINK%'), // Japan 'hatena' => array('name' => 'Hatena Bookmark', 'url' => "javascript:(function(){window.open('http://b.hatena.ne.jp/add?mode=confirm&amp;is_bm=1&amp;title=%TITLE%&amp;url=%PERMALINK%','socialink','width=550,height=600,resizable=1,scrollbars=1');})();"), 'yahoojbookmarks' => array('name' => 'Yahoo! JAPAN Bookmarks', 'url' => "javascript:(function(){window.open('http://bookmarks.yahoo.co.jp/bookmarklet/showpopup?t=%TITLE%&amp;u=%PERMALINK%&amp;opener=bm&amp;ei=UTF-8','socialink','width=550px,height=480px,status=1,location=0,resizable=1,scrollbars=0,left=100,top=50',0);})();"), 'topicit' => array('name' => 'TopicIT@nifty', 'url' => "javascript:(function(){window.open('http://topic.nifty.com/up/add?mode=2&amp;topic_title=%TITLE%&amp;topic_url=%PERMALINK%');})();"), 'buzzurl' => array('name' => 'Buzzurl', 'url' => 'http://buzzurl.jp/entry/%PERMALINK%'), 'choix' => array('name' => 'Choix', 'url' => 'http://www.choix.jp/bloglink/%PERMALINK%'), 'newsing' => array('name' => 'newsing', 'url' => 'http://newsing.jp/add?url=%PERMALINK%&amp;title=%TITLE%'), 'livedoorclip' => array('name' => 'livedoor Clip', 'url' => 'http://clip.livedoor.com/redirect?link=%PERMALINK%&amp;title=%TITLE%&amp;ie=utf-8'), 'pookmark' => array('name' => 'POOKMARK Airlines', 'url' => 'http://pookmark.jp/post?url=%PERMALINK%&amp;title=%TITLE%'), 'goobookmark' => array('name' => 'goo Bookmark', 'url' => 'http://bookmark.goo.ne.jp/add/detail/?url=%PERMALINK%'), ); /** * action: plugin_activation * * @access public * @param string $file * @return void */ public function action_plugin_activation($file) { if ( Plugins::id_from_file( $file ) != Plugins::id_from_file( __FILE__ ) ) return; Options::set( 'socialink__link_pos', 'top' ); Options::set( 'socialink__services', serialize( array( 'digg', 'delicious', 'technorati', 'google', 'yahoo', 'furl', 'reddit', 'magnolia' ) ) ); } /** * action: update_check * * @access public * @return void */ public function action_update_check() { Update::add( 'Socialink', '58c939f3-26ae-11dd-b5d6-001b210f913f', $this->info->version ); } /** * action: plugin_ui * * @access public * @param string $plugin_id * @param string $action * @return void */ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id != $this->plugin_id() ) return; if ( $action == _t( 'Configure' ) ) { $ui_services = array(); foreach ($this->services as $k => $service) { $ui_services[$k] = $service['name']; } $ui = new FormUI( strtolower( get_class( $this ) ) ); $link_pos = $ui->append( 'radio', 'link_pos', 'option:socialink__link_pos', _t( 'Auto Insert: ' ) ); $link_pos->options = array('none' => 'None', 'top' => 'Top', 'bottom' => 'Bottom'); $services = $ui->append( 'select', 'services', 'option:socialink__services', _t( 'Services: ' ), $ui_services); $services->options = $ui_services; $services->multiple = true; $ui->append( 'submit', 'save', _t( 'Save' ) ); $ui->out(); } } /** * filter: plugin_config * * @access public * @return array */ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t( 'Configure' ); } return $actions; } /** * filter: post_content_out * * @access public * @return string */ public function filter_post_content_out($content, $post) { $link_pos = Options::get('socialink__link_pos'); if ($link_pos == 'top') { $content = $this->create_link($post) . $content; } elseif ($link_pos == 'bottom') { $content = $content . $this->create_link($post); } return $content; } /** * theme: show_socialink * * @access public * @param object $theme * @param object $post * @return string */ public function theme_show_socialink($theme, $post) { return $this->create_link($post); } private function create_link($post) { $link = '<div class="socialink">'; $site_title = Options::get( 'title' ); $s_services = Options::get( 'socialink__services' ); @reset( $s_services ); while ( list( , $k ) = @each( $s_services ) ) { if ( !isset( $this->services[$k] ) ) continue; $url = $this->services[$k]['url']; $url = str_replace( '%PERMALINK%', urlencode( $post->permalink ), $url ); $url = str_replace( '%TITLE%', urlencode( $site_title . ' - ' . $post->title_out ), $url ); $target = ''; if ( substr( $url, 0, 11 ) != 'javascript:' ) { $target = ' target="_blank"'; } $link.= '<a href="' . $url .'"' . $target . ' title="Post to ' . $this->services[$k]['name'] . '" rel="nofollow"><img src="' . $this->get_url() .'/img/icon/' . $k . '.png" width="16" height="16" alt="Post to ' . $this->services[$k]['name'] . '" style="padding:0 3px;" /></a>'; } $link.= '</div>'; return $link; } } ?> <file_sep>#!/usr/bin/env php <?php /** * Habari bootstrapped evaluator * * WARNING: DO NOT PUT THIS FILE IN YOUR PUBLIC WEBROOT, OR ANYWHERE ACCESSIBLE * BY YOUR WEB SERVER. PROTECT IT. THIS CODE IS DANGEROUS IN THE WRONG HANDS. * * This script can be used to run code from within the Habari infrastructure * from the command line. * * Example: * $ echo 'echo Format::autop("foo\n\nbar");' | ./heval * <p>foo</p><p>bar</p> * * You may need to change the #! line above, if your system doesn't have `env` * in the normal place. * * Also, if this script can't find your Habari install, try setting * $_ENV['HEVAL_INDEX'] to /path/to/habari/htdocs/index.php * * If you don't know what the #! line is, or how to set $_ENV, you really * shouldn't be using this script. Delete it now. */ $cmd = file_get_contents( 'php://stdin' ); define( 'UNIT_TEST', true ); if (isset($_ENV['HEVAL_INDEX'])) { require $_ENV['HEVAL_INDEX']; } else { require dirname( dirname( __FILE__ ) ) . '/htdocs/index.php'; } ob_start(); eval( $cmd ); $out = ob_get_clean(); if ( substr( $out, -1 ) != "\n" ) { $out .= "\n"; } echo $out; <file_sep><!-- sidebar --> <?php Plugins::act( 'theme_sidebar_top' ); ?> <div id="search"> <h2>Search</h2> <?php include 'searchform.php'; ?> </div> <div class="sb-about"> <h2>About</h2> <?php Options::out('about'); ?> </div> <?php if( isset($tag_cloud) ): ?> <div class="sb-tags"> <h2>Tags</h2> <?php echo $tag_cloud; ?> </div> <?php endif; ?> <div class="sb-user"> <h2>User</h2> <?php include 'loginform.php'; ?> </div> <?php Plugins::act( 'theme_sidebar_bottom' ); ?> <!-- /sidebar --> <file_sep><?php Format::apply_with_hook_params( 'more', 'post_content_out', 'Read the rest &raquo;' ); Format::apply('autop', 'post_content_out'); Format::apply( 'autop', 'comment_content_out' ); Format::apply( 'nice_date', 'comment_date_out' ); Format::apply('tag_and_list', 'post_tags_out', ' , ', ' and '); Format::apply( 'nice_date', 'post_pubdate_out', 'F j' ); // We must tell Habari to use MyTheme as the custom theme class: define( 'THEME_CLASS', 'MyTheme' ); /** * A custom theme for K2 output */ class MyTheme extends Theme { public function add_template_vars() { if( !$this->template_engine->assigned( 'pages' ) ) { $this->assign('pages', Posts::get( array( 'content_type' => 'page', 'status' => Post::status('published') ) ) ); } if( !$this->template_engine->assigned( 'user' ) ) { $this->assign('user', User::identify() ); } if( !$this->template_engine->assigned( 'page' ) ) { $this->assign('page', isset( $page ) ? $page : 1 ); } //for recent comments loop in sidebar.php $this->assign('recent_comments', Comments::get( array('limit'=> 8, 'status'=>Comment::STATUS_APPROVED, 'orderby'=>'date DESC' ) ) ); parent::add_template_vars(); } } ?><file_sep><?php /** * Habari Format Class * * Provides formatting functions for use in themes. Extendable. * @package Habari */ class Format { private static $formatters = null; /** * Called to register a format function to a plugin hook, only passing the hook's first parameter to the Format function. * @param string $format A function name that exists in a Format class * @param string $onwhat A plugin hook to apply that Format function to as a filter **/ public static function apply($format, $onwhat) { if( self::$formatters == null ) { self::load_all(); } foreach(self::$formatters as $formatobj) { if( method_exists($formatobj, $format) ) { $index = array_search($formatobj, self::$formatters); $func = '$o = Format::by_index(' . $index . ');return $o->' . $format . '($a'; $args = func_get_args(); if( count($args) > 2) { $func.= ', '; $args = array_map(create_function('$a', 'return "\'{$a}\'";'), array_slice($args, 2)); $func .= implode(', ', $args); } $func .= ');'; $lambda = create_function('$a', $func); Plugins::register( $lambda, 'filter', $onwhat); break; // We only look for one matching format function to apply. } } } /** * Called to register a format function to a plugin hook, and passes all of the hook's parameters to the Format function. * @param string $format A function name that exists in a Format class * @param string $onwhat A plugin hook to apply that Format function to as a filter **/ public static function apply_with_hook_params($format, $onwhat) { if( self::$formatters == null ) { self::load_all(); } foreach(self::$formatters as $formatobj) { if( method_exists($formatobj, $format) ) { $index = array_search($formatobj, self::$formatters); $func = '$o= Format::by_index(' . $index . '); $args= func_get_args(); return call_user_func_array(array($o, "' . $format . '"), array_merge($args'; $args = func_get_args(); if( count($args) > 2) { $func.= ', array( '; $args = array_map(create_function('$a', 'return "\'{$a}\'";'), array_slice($args, 2)); $func .= implode(', ', $args) . ')'; } $func .= '));'; $lambda = create_function('$a', $func); Plugins::register( $lambda, 'filter', $onwhat); break; // We only look for one matching format function to apply. } } } /** * function by_index * Returns an indexed formatter object, for use by lambda functions created * to supply additional parameters to plugin filters. * @param integer $index The index of the formatter object to return. * @return Format The formatter object requested **/ public static function by_index($index) { return self::$formatters[$index]; } /** * function load_all * Loads and stores an instance of all declared Format classes for future use **/ public static function load_all() { self::$formatters = array(); $classes = get_declared_classes(); foreach( $classes as $class ) { if( ( get_parent_class($class) == 'Format' ) || ( $class == 'Format' ) ) { self::$formatters[] = new $class(); } } self::$formatters = array_merge( self::$formatters, Plugins::get_by_interface( 'FormatPlugin' ) ); self::$formatters = array_reverse( self::$formatters, true ); } /** DEFAULT FORMAT FUNCTIONS **/ /** * function autop * Converts non-HTML paragraphs separated with 2 line breaks into HTML paragraphs * while preserving any internal HTML * @param string $value The string to apply the formatting * @returns string The formatted string **/ public static function autop($value) { $regex = '/(<\\s*(address|blockquote|div|h[1-6]|hr|p|pre|ul|ol|dl|table)[^>]*?'.'>.*?<\\s*\/\\s*\\2\\s*>)/sm'; $target = str_replace("\r\n", "\n", $value); $target = preg_replace('/<\\s*br\\s*\/\\s*>(\s*)/m', "\n", $target); $cz = preg_split($regex, $target); preg_match_all($regex, $target, $cd, PREG_SET_ORDER); $output = ''; for($z = 0; $z < count($cz); $z++) { $pblock = preg_replace('/\n{2,}/', "<!--pbreak-->", trim($cz[$z])); $pblock = str_replace("\n", "<br />\n", $pblock); $pblock = str_replace("<!--pbreak-->", "</p>\n<p>", $pblock); $pblock = ($pblock == '') ? '' : "<p>{$pblock}</p>\n"; $tblock = isset($cd[$z]) ? $cd[$z][0] . "\n" : ''; $output .= $pblock . $tblock; } return trim($output); } /** * function tag_and_list * Formatting function (should be in Format class?) * Turns an array of tag names into an HTML-linked list with command and an "and". * @param array $array An array of tag names * @param string $between Text to put between each element * @param string $between_last Text to put between the next to last element and the last element * @return string HTML links with specified separators. **/ public static function tag_and_list($array, $between = ', ', $between_last = ' and ') { if ( ! is_array( $array ) ) { $array = array ( $array ); } $fn = create_function('$a,$b', 'return "<a href=\\"" . URL::get("display_entries_by_tag", array( "tag" => $b) ) . "\\" rel=\\"tag\\">" . $a . "</a>";'); $array = array_map($fn, $array, array_keys($array)); $last = array_pop($array); $out = implode($between, $array); $out .= ($out == '') ? $last : $between_last . $last; return $out; } /** * function nice_date * Formats a date using a date format string * @param mixed A date as a string or a timestamp * @param string A date format string * @returns string The date formatted as a string **/ public static function nice_date($date, $dateformat = 'F j, Y') { if ( is_numeric($date) ) return Utils::locale_date($dateformat, $date); return Utils::locale_date($dateformat, strtotime($date)); } /** * function nice_time * Formats a time using a date format string * @param mixed A date as a string or a timestamp * @param string A date format string * @returns string The time formatted as a string **/ public static function nice_time($date, $dateformat = 'H:i:s') { if ( is_numeric($date) ) return Utils::locale_date($dateformat, $date); return Utils::locale_date($dateformat, strtotime($date)); } /** * Returns a shortened version of whatever is passed in. * @param string $value A string to shorten * @param integer $count Maximum words to display [100] * @param integer $maxparagraphs Maximum paragraphs to display [1] * @return string The string, shortened **/ public static function summarize( $text, $count= 100, $maxparagraphs= 1 ) { preg_match_all( '/<script.*?<\/script.*?>/', $text, $scripts ); preg_replace( '/<script.*?<\/script.*?>/', '', $text ); $words = preg_split( '/(<(?:\\s|".*?"|[^>])+>|\\s+)/', $text, $count + 1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY ); $ellipsis= ''; if( count( $words ) > $count * 2 ) { array_pop( $words ); $ellipsis= '...'; } $output= ''; $paragraphs= 0; $stack= array(); foreach( $words as $word ) { if ( preg_match( '/<.*\/\\s*>$/', $word ) ) { // If the tag self-closes, do nothing. $output.= $word; } elseif( preg_match( '/<[\\s\/]+/', $word )) { // If the tag ends, pop one off the stack (cheatingly assuming well-formed!) array_pop( $stack ); preg_match( '/<\s*\/\s*(\\w+)/', $word, $tagn ); switch( $tagn[1] ) { case 'br': case 'p': case 'div': case 'ol': case 'ul': $paragraphs++; if( $paragraphs >= $maxparagraphs ) { $output.= '...' . $word; $ellipsis= ''; break 2; } } $output.= $word; } elseif( $word[0] == '<' ) { // If the tag begins, push it on the stack $stack[]= $word; $output.= $word; } else { $output.= $word; } } $output.= $ellipsis; if ( count( $stack ) > 0 ) { preg_match( '/<(\\w+)/', $stack[0], $tagn ); $stack= array_reverse( $stack ); foreach ( $stack as $tag ) { preg_match( '/<(\\w+)/', $tag, $tagn ); $output.= '</' . $tagn[1] . '>'; } } foreach( $scripts[0] as $script ) { $output.= $script; } return $output; } /** * Returns a truncated version of post content when the post isn't being displayed on its own. * Posts are split either at the comment <!--more--> or at the specified maximums. * Use only after applying autop or other paragrpah styling methods. * Apply to posts using: * <code>Format::apply_with_hook_params( 'more', 'post_content_out' );</code> * @param string $content The post content * @param Post $post The Post object of the post * @param string $more_text The text to use in the "read more" link. * @param integer $max_words null or the maximum number of words to use before showing the more link * @param integer $max_paragraphs null or the maximum number of paragraphs to use before showing the more link * @return string The post content, suitable for display **/ public static function more($content, $post, $more_text = 'Read More &raquo;', $max_words = null, $max_paragraphs = null) { // There should be a more readable way than this to detect if this post is being displayed by itself: if(isset(Controller::get_handler()->handler_vars['slug'])) { return $content; } else { $matches= preg_split( '/<!--\s*more\s*-->/is', $content, 2, PREG_SPLIT_NO_EMPTY ); if(count($matches) > 1) { return reset($matches) . ' <a href="' . $post->permalink . '">' . $more_text . '</a>'; } elseif (isset($max_words) || isset($max_paragraphs)) { $max_words = empty($max_words) ? 9999999 : intval($max_words); $max_paragraphs = empty($max_paragraphs) ? 9999999 : intval($max_paragraphs); $summary = Format::summarize($content, $max_words, $max_paragraphs); if(strlen($summary) >= strlen($content)) { return $content; } else { return $summary . ' <a href="' . $post->permalink . '">' . $more_text . '</a>'; } } } return $content; } } ?> <file_sep><?php class JWYSIWYG extends Plugin { public function action_admin_header($theme) { if ( $theme->page == 'publish' ) { Stack::add('admin_header_javascript', $this->get_url() . '/jwysiwyg/jquery.wysiwyg.js'); Stack::add('admin_stylesheet', array($this->get_url() . '/jwysiwyg/jquery.wysiwyg.css', 'screen')); } } public function action_admin_footer($theme) { if ( $theme->page == 'publish' ) { echo <<<JWYSIWYG <script type="text/javascript"> $('label[for=content]').text(''); $(function() { $('#content').wysiwyg(); }); habari.editor = { insertSelection: function(value) { var instance = $.data($('#content')[0], 'wysiwyg'); instance.setContent(instance.getContent() + value); } } </script> JWYSIWYG; } } public function action_update_check() { Update::add( 'JWYSIWYG', 'b5f0c17d-22e6-4d6c-8011-c79481d5efc7', $this->info->version ); } } ?> <file_sep><?php /** * * * @package blogroll */ class Blog extends QueryRecord { private $info= null; private $tags= null; /** * Returns the defined database columns for a cronjob. * @return array Array of columns in the crontab table */ public static function default_fields() { return array( 'id' => 0, 'name' => '', 'url' => '', 'feed' => '', 'description' => '', 'owner' => '', 'updated' => '', 'rel' => 'external', ); } /** * Constructor for the CronJob class. * @param array $paramarray an associative array or querystring of initial field values */ public function __construct( $paramarray = array() ) { // Defaults $this->fields= array_merge( self::default_fields(), $this->fields, $this->newfields ); parent::__construct( $paramarray ); if ( isset( $this->fields['tags'] ) ) { $this->tags= $this->parsetags( $this->fields['tags'] ); unset( $this->fields['tags'] ); } $this->exclude_fields('id'); $this->info= new BlogInfo ( $this->fields['id'] ); } public static function get( $id ) { return DB::get_row( "SELECT * FROM {blogroll} WHERE id = ?", array($id), 'Blog' ); } private static function parsetags( $tags ) { if ( is_string( $tags ) ) { if ( '' === $tags ) { return array(); } // dirrty ;) $rez= array( '\\"'=>':__unlikely_quote__:', '\\\''=>':__unlikely_apos__:' ); $zer= array( ':__unlikely_quote__:'=>'"', ':__unlikely_apos__:'=>"'" ); // escape $tagstr= str_replace( array_keys( $rez ), $rez, $tags ); // match-o-matic preg_match_all( '/((("|((?<= )|^)\')\\S([^\\3]*?)\\3((?=[\\W])|$))|[^,])+/', $tagstr, $matches ); // cleanup $tags= array_map( 'trim', $matches[0] ); $tags= preg_replace( array_fill( 0, count( $tags ), '/^(["\'])(((?!").)+)(\\1)$/'), '$2', $tags ); // unescape $tags= str_replace( array_keys( $zer ), $zer, $tags ); // hooray return $tags; } elseif ( is_array( $tags ) ) { return $tags; } } private function save_tags() { DB::query( 'DELETE FROM ' . DB::table( 'tag2blog' ) . ' WHERE blog_id = ?', array( $this->fields['id'] ) ); if ( count( $this->tags ) == 0 ) { return; } foreach ( ( array ) $this->tags as $tag ) { $tag_slug= Utils::slugify( $tag ); // @todo TODO Make this multi-SQL safe! if ( DB::get_value( 'SELECT count(*) FROM ' . DB::table( 'tags' ) . ' WHERE tag_text = ?', array( $tag ) ) == 0 ) { DB::query( 'INSERT INTO ' . DB::table( 'tags' ) . ' (tag_text, tag_slug) VALUES (?, ?)', array( $tag, $tag_slug ) ); } DB::query( 'INSERT INTO ' . DB::table( 'tag2blog' ) . ' (tag_id, blog_id) SELECT id AS tag_id, ? AS blog_id FROM ' . DB::table( 'tags' ) . ' WHERE tag_text = ?', array( $this->fields['id'], $tag ) ); } } public function __set( $name, $value ) { switch( $name ) { case 'tags': $this->tags= $this->parsetags( $value ); return $this->get_tags(); } return parent::__set( $name, $value ); } public function __get( $name ) { $fieldnames= array_merge( array_keys( $this->fields ), array( 'tags' ) ); if ( !in_array( $name, $fieldnames ) && strpos( $name, '_' ) !== false ) { preg_match( '/^(.*)_([^_]+)$/', $name, $matches ); list( $junk, $name, $filter )= $matches; } else { $filter= false; } switch($name) { case 'info': $out = $this->get_info(); break; case 'tags': $out= $this->get_tags(); break; default: $out = parent::__get( $name ); break; } $out= Plugins::filter( "blog_{$name}", $out, $this ); if ( $filter ) { $out= Plugins::filter( "blog_{$name}_{$filter}", $out, $this ); } return $out; } private function get_tags() { if ( empty( $this->tags ) ) { $sql= " SELECT t.tag_text, t.tag_slug FROM " . DB::table( 'tags' ) . " t INNER JOIN " . DB::table( 'tag2blog' ) . " t2b ON t.id = t2b.tag_id WHERE t2b.blog_id = ? ORDER BY t.tag_slug ASC"; $result= DB::get_results( $sql, array( $this->fields['id'] ) ); if ( $result ) { foreach ( $result as $t ) { $this->tags[$t->tag_slug]= $t->tag_text; } } } if ( count( $this->tags ) == 0 ) { return array(); } return $this->tags; } private function get_info() { if ( ! $this->info ) { $this->info= new BlogInfo( $this->id ); } return $this->info; } /** * Saves a new cron job to the crontab table */ public function insert() { Plugins::act( 'blogroll_insert_before', $this ); $result = parent::insertRecord( DB::table('blogroll') ); $this->newfields['id'] = DB::last_insert_id(); // Make sure the id is set in the comment object to match the row id $this->fields = array_merge($this->fields, $this->newfields); $this->newfields = array(); $this->info->commit( $this->fields['id'] ); $this->save_tags(); Plugins::act( 'blogroll_insert_after', $this ); return $result; } /** * Updates an existing cron job to the crontab table */ public function update() { Plugins::act( 'blogroll_update_before', $this ); $result = parent::updateRecord( DB::table('blogroll'), array('id'=>$this->id) ); $this->fields = array_merge($this->fields, $this->newfields); $this->newfields = array(); $this->save_tags(); $this->info->commit(); Plugins::act( 'blogroll_update_after', $this ); return $result; } /** * Deletes an existing cron job */ public function delete() { Plugins::act( 'blogroll_delete_before', $this ); if ( isset( $this->info ) ) { $this->info->delete_all(); } $result= parent::deleteRecord( DB::table('blogroll'), array('id'=>$this->id) ); Plugins::act( 'blogroll_delete_after', $this ); return $result; } } ?> <file_sep><!-- comments --> <div id="comments"> <?php if( $post->comments->approved->count ) : $count= 0; ?> <h4><?php echo $post->comments->approved->count; ?> Responses to &#8220;<?php echo $post->title; ?>&#8221;</h4> <ol class="commentlist"> <?php foreach ( $post->comments->moderated as $comment ) : $count++; if ( 0 == ( $count % 2 ) ) { $class= ''; } else { $class= 'alt'; } if ( $post->author->email == $comment->email ) { $class= 'owner'; } if ( $comment->status == Comment::STATUS_UNAPPROVED ) { $class= 'unapproved'; } ?> <li id="comment-<?php echo $comment->id; ?>" class="<?php echo $class; ?>"> <span class="commentauthor"><a href="<?php echo $comment->url; ?>" rel="external"><?php echo $comment->name; ?></a></span> <small class="commentmetadata"><a href="#comment-<?php echo $comment->id; ?>" title="Time of this comment"><?php echo $comment->date_out; ?></a> <?php if ( $comment->status == Comment::STATUS_UNAPPROVED ) { ?><em>Your comment is awaiting moderation.</em><?php } ?></small> <?php echo $comment->content_out; ?> </li> <?php endforeach; { ?> </ol> <?php } endif; ?> <?php if ( ! $post->info->comments_disabled ) { include_once( 'commentform.php' ); } ?> </div> <!-- comments --> <file_sep><?php class TracFeed extends Plugin { public function filter_rewrite_rules( $rules ) { $rules[] = new RewriteRule(array( 'name' => 'item', 'parse_regex' => '%feed/dev/?$%i', 'build_str' => 'feed/dev', 'handler' => 'UserThemeHandler', 'action' => 'dev_feed', 'priority' => 7, 'is_active' => 1, )); return $rules; } public function action_rss_create_wrapper( $xml ) { // add a description when site tagline isn't set, to make the feed valid $xml->channel->addChild( 'description', 'Habari Trac' ); } public function action_handler_dev_feed($handler_vars) { $rss = Plugins::get_by_interface('RSS'); if(count($rss) !== 1) { exit; } $xml= reset($rss)->create_rss_wrapper(); $connection_string = Options::get( 'tracfeed__connection_string' ); $username = Options::get( 'tracfeed__username' ); $password = Options::get( 'tracfeed__<PASSWORD>' ); $db = DatabaseConnection::ConnectionFactory( $connection_string ); $db->connect( $connection_string, $username, $password ); $times = $db->get_column('SELECT time from ticket_change group by time order by time desc limit 15;'); $mintime = array_reduce($times, 'min', reset($times)); $comments = $db->get_results(" SELECT *, ticket_change.time as changetime from ticket_change INNER JOIN ticket on ticket.id = ticket_change.ticket where changetime >= ? and not (field ='comment' and newvalue = '') order by ticket_change.time DESC; ", array($mintime)); $posts = array(); foreach($comments as $comment) { $post_id = md5($comment->ticket . ':' . $comment->changetime . ':' . $comment->author); if(!array_key_exists($post_id, $posts)) { $post = new Post(); $post->title = "Ticket #{$comment->ticket}: {$comment->summary}"; $post->content = "Changes by {$comment->author} on ticket <a href=\"http://trac.habariproject.org/habari/ticket/{$comment->ticket}\">#{$comment->ticket}</a>.\n<br>\n<br>"; $post->guid = 'tag:' . Site::get_url( 'hostname' ) . ',trac_comment,' . $post_id; $post->content_type = 'dev_feed'; $post->slug = "http://trac.habariproject.org/habari/ticket/{$comment->ticket}"; $post->pubdate = date( 'r', $comment->changetime ); $posts[$post_id] = $post; } else { $post = $posts[$post_id]; } switch($comment->field) { case 'comment': $content = $comment->newvalue; $content = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]/i', '<a href="$0">[link]</a>', $content); $content = preg_replace('%\br([0-9]+)\b%', '<a href="http://trac.habariproject.org/habari/changeset/$1">r$1</a>', $content); $content = preg_replace('%\b#([0-9]+)\b%', '<a href="http://trac.habariproject.org/habari/ticket/$1">$1</a>', $content); $post->content .= "Comment #{$comment->oldvalue} by {$comment->author}:\n<blockquote><pre>{$content}</pre></blockquote>\n<br>"; break; default: if(trim($comment->oldvalue) == '') { $post->content .= "Set <b>{$comment->field}</b> to: {$comment->newvalue}\n<br>"; } else { $post->content .= "Changed <b>{$comment->field}</b> from: {$comment->oldvalue}\n<br> To: {$comment->newvalue}\n<br>"; } break; } } $xml= RSS::add_posts($xml, $posts ); ob_clean(); header( 'Content-Type: application/xml' ); echo $xml->asXML(); exit; } function filter_post_permalink($permalink, $post) { if($post->content_type == 'dev_feed') { return $post->slug; } return $permalink; } public function configure() { $ui = new FormUI( 'tracfeed' ); $connection_string = $ui->append( 'text', 'connection_string', 'tracfeed__connection_string', _t( 'Connection String:', 'tracfeed' ) ); $username = $ui->append( 'text', 'username', 'tracfeed__username', _t( 'Username (or blank for sqlite):', 'tracfeed' ) ); $password = $ui->append( 'password', '<PASSWORD>', '<PASSWORD>', _t( 'Password (or blank for sqlite):', 'tracfeed' ) ); $ui->on_success( array( $this, 'updated_config' ) ); $ui->append( 'submit', 'save', _t( 'Save', 'tracfeed' ) ); return $ui; } public function updated_config( FormUI $ui ) { Session::notice( _t( 'Trac Feed options saved.', 'tracfeed' ) ); $ui->save(); } } ?> <file_sep><!-- To customize this template, copy it to your currently active theme directory and edit it --> <div id="recentcomments"> <h2><?php echo $recentcomments_title; ?></h2> <ul> <?php foreach ( $recentcomments_links as $link ) : ?> <?php echo $link; ?> <?php endforeach; ?> </ul> </div><file_sep><?php class TagTray extends Plugin { private $theme; /** * Add the tray to the publish form * @params FormUI $form The publish form object instance * @params Post $post The post that is being edited **/ public function action_form_publish($form, $post) { // Create the tags selector $tagselector = $form->publish_controls->append('fieldset', 'tagselector', _t('Tags')); $tags_buttons = $tagselector->append('wrapper', 'tags_buttons'); $tags_buttons->class = 'container'; $tags_buttons->append('static', 'clearbutton', '<p class="span-5"><input type="button" value="'._t('Clear').'" id="clear"></p>'); $tags_list = $tagselector->append('wrapper', 'tags_list'); $tags_list->class = ' container'; $tags_list->append('static', 'tagsliststart', '<ul id="tag-list" class="span-19">'); $tags = Tags::get(); $max = Tags::max_count(); foreach ($tags as $tag) { $tags_list->append('tag', 'tag_'.$tag->slug, $tag, 'tabcontrol_text'); } $tags_list->append('static', 'tagslistend', '</ul>'); } /** * Add the required javascript to the publish page * @param Theme $theme The admin theme instance **/ public function action_admin_header($theme) { Stack::add('admin_header_javascript', $this->get_url(true) . 'tagtray.js', 'tagtray'); } } ?><file_sep><?php if( count($latestspam_comments) > 0): ?> <ul class="items"> <?php foreach($latestspam_comments as $comment): ?> <li class="item clear"> <span class="date pct15 minor"><a href="#" title="<?php printf(_t('Written at %1$s'), $comment->date->get( 'g:m a \o\n F jS, Y' ) ); ?>"><?php $comment->date->out( 'M j' ); ?></a></span> <span class="who pct70"><a href="<?php echo $comment->url; ?>"><?php echo $comment->name; ?></a> <a class="minor" href="<?php echo $comment->post->permalink; ?>"> <?php _e('on'); ?> <?php echo $comment->post->title; ?></a></span> <span class="comments pct15"><a href="<?php echo URL::get( 'admin', array( 'page' => 'comment', 'id' => $comment->id) ); ?>">Approve</a></span> </li> <?php endforeach; ?> </ul> <?php if($spambutton): ?> <a href="#" id="deleteallspam"><?php echo sprintf( _t( 'Delete all %s spam comments.' ), $spamcount ); ?></a> <?php endif; ?> <?php else: ?> <p><?php echo _t( 'You have no spam today. Yay!' ); ?></p> <?php endif; ?><file_sep>var magicArchives = { search: null, init: function() { magicArchives.archives = $('#magicArchives'); magicArchives.controller= $('#archive_controller', magicArchives.archives); magicArchives.searcher= $('.section.search input', magicArchives.archives); magicArchives.posts= $('#archive_posts', magicArchives.archives); // Toggle tags $('a#archive_toggle_tags', magicArchives.controller).click(function() { magicArchives.toggle($('#archive_tags')); return false; }); // Set up our AJAX magicArchives.ajax = $.manageAjax({manageType: 'abortOld', maxReq: 1}); // Set up the search label magicArchives.searcher .val($('.section.search label').text()) .focus(function() { if(magicArchives.searcher.val() == $('.section.search label').text()) { magicArchives.searcher.val(''); } }) .blur(function() { if(magicArchives.searcher.val() == '') { magicArchives.searcher.val($('.section.search label').text()); } }); // Update on search magicArchives.searcher.keyup(function() { if(magicArchives.searcher.val() != magicArchives.search) { magicArchives.fetch(); } }); tagManage.init(); }, fetch: function() { magicArchives.search= magicArchives.searcher.val(); params= { search: magicArchives.search } magicSpinner.start(); magicArchives.ajax.add({ type: "GET", url: magicArchives.endpoint, data: params, success: function(response){ magicSpinner.stop(); magicArchives.posts.html(response); } }); }, toggle: function(section) { if(section.hasClass('open')) { section.slideUp(); section.removeClass('open'); } else { section.slideDown(); section.addClass('open'); } } }; var magicSpinner = { start: function() { magicArchives.archives.addClass('spinner'); }, stop: function () { magicArchives.archives.removeClass('spinner'); } } var tagManage = { init: function() { tagManage.initItems(); $('#magicArchives #archive_controls .section#archive_tags #archive_tags_controls .clear').click(function() { tagManage.uncheckAll(); return false; }); $('#magicArchives #archive_controls .section#archive_tags #archive_tags_controls input[type=checkbox]').change(function () { if($('#magicArchives #archive_controls .section#archive_tags #archive_tags_controls label.selectedtext').hasClass('all')) { tagManage.uncheckAll(); } else { tagManage.checkAll(); } }); }, initItems: function() { $('#magicArchives #archive_controls .section#archive_tags .tag:not(.ignore) .checkbox input[type=checkbox]').change(function () { tagManage.changeItem(); }); $('#magicArchives #archive_controls .section#archive_tags .tag:not(.ignore) .checkbox input[type=checkbox]').each(function() { id = $(this).attr('id'); id = id.replace(/.*\[(.*)\]/, "$1" ); // checkbox ids have the form name[id] if(tagManage.selected['p' + id] == 1) { this.checked = 1; } }); tagManage.changeItem(); }, selected: [], searchCache: [], searchRows: [], changeItem: function() { var selected = {}; if(tagManage.selected.length != 0) { selected = tagManage.selected; } $('#magicArchives #archive_controls .section#archive_tags .tag:not(.ignore) .checkbox input[type=checkbox]:checked').each(function() { check= $(this); id = check.attr('id'); id = id.replace(/.*\[(.*)\]/, "$1" ); selected['p' + id] = 1; check.parent().parent().addClass('selected'); }); $('#magicArchives #archive_controls .section#archive_tags .tag:not(.ignore) .checkbox input[type=checkbox]:not(:checked)').each(function() { check= $(this); id = check.attr('id'); id = id.replace(/.*\[(.*)\]/, "$1" ); selected['p' + id] = 0; check.parent().parent().removeClass('selected'); }); tagManage.selected = selected; visible = $('#magicArchives #archive_controls .section#archive_tags .tag:not(.hidden):not(.ignore) .checkbox input[type=checkbox]:checked').length; count = 0; for (var id in tagManage.selected) { if(tagManage.selected[id] == 1) { count = count + 1; } } if(count == 0) { $('#magicArchives #archive_controls .section#archive_tags #archive_tags_controls input[type=checkbox]').each(function() { this.checked = 0; }); $('#magicArchives #archive_controls .section#archive_tags #archive_tags_controls label.selectedtext').addClass('none').removeClass('all').text('None selected'); } else if(count == $('#magicArchives #archive_controls .section#archive_tags .tag:not(.hidden):not(.ignore) .checkbox input[type=checkbox]').length) { $('#magicArchives #archive_controls .section#archive_tags #archive_tags_controls input[type=checkbox]').each(function() { this.checked = 1; }); $('#magicArchives #archive_controls .section#archive_tags #archive_tags_controls label.selectedtext').removeClass('none').addClass('all').html('All ' + count + ' selected'); } else { $('#magicArchives #archive_controls .section#archive_tags #archive_tags_controls input[type=checkbox]').each(function() { this.checked = 0; }); $('#magicArchives #archive_controls .section#archive_tags #archive_tags_controls label.selectedtext').removeClass('none').removeClass('all').text(count + ' selected'); } }, uncheckAll: function() { $('#magicArchives #archive_controls .section#archive_tags .tag:not(.hidden):not(.ignore) .checkbox input[type=checkbox]').each(function() { this.checked = 0; }); tagManage.selected = []; tagManage.changeItem(); }, checkAll: function() { $('#magicArchives #archive_controls .section#archive_tags .tag:not(.hidden):not(.ignore) .checkbox input[type=checkbox]').each(function() { this.checked = 1; }); tagManage.changeItem(); } } $(document).ready(function() { if($('#magicArchives').length != 0) { magicArchives.init(); } });<file_sep>To use this plugin, first activate it. Then, add the following to your theme where you want the comment preview to appear: 1) A container element with the ID of 'comment-preview'. 2) A container for each field with a corresponding class (.namecontainer, .urlcontainer, .comment-contentcontainer) 3) A placeholder for each field with a corresponding class (.nameholder, .urlholder, .comment-contentcontainer) With these elements in place, the comment preview will be enabled.<file_sep><?php class GeoTags extends Plugin { const VERSION= '0.2.1'; private $config= array(); public function info() { return array( 'name' => 'Header GeoTags', 'url' => 'http://mikelietz.org/code', 'author' =>'<NAME>', 'authorurl' => 'http://mikelietz.org/', 'version' => self::VERSION, 'description' => 'Adds Geocode data to headers.', 'license' => 'Apache License 2.0', ); } public function action_update_check() { Update::add( 'Geo Tags', '30840010-6e02-11dd-ad8b-0800200c9a66', $this->info->version ); } function set_priorities() { return array( 'theme_header' => 11, ); } public function action_init() { $class_name= strtolower( get_class( $this ) ); $this->config['lat']= Options::get( $class_name . '__lat' ); $this->config['long']= Options::get( $class_name . '__long' ); } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t( 'Configure' ); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t( 'Configure' ): $class_name= strtolower( get_class( $this ) ); $ui= new FormUI( $class_name ); $lat= $ui->append( 'text', 'lat', 'geotags__lat', _t( 'Latitude (required)' ) ); $lat->add_validator( 'validate_required' ); $long= $ui->append( 'text', 'long','geotags__long', _t( 'Longitude (required)' ) ); $long->add_validator( 'validate_required' ); $ui->append( 'submit', 'save', 'save' ); $ui->out(); break; } } } public function theme_header( $theme ) { return $this->get_tags(); } private function get_tags() { $out= ''; $lat= $this->config['lat']; $long= $this->config['long']; $coords= "$lat, $long"; $out= "\t<meta name=\"DC.title\" content=\"" . Options::get( 'title' ) . "\">\n"; $out.= "\t<meta name=\"ICBM\" content=\"$coords\">\n"; $out.= "\t<meta name=\"geo.position\" content=\"$coords\">\n"; return $out; } } ?> <file_sep><?php include 'header.php'; ?> <?php include 'sidebar.php'; ?> <div id="content"> <div class="post"> <div class="post_head"> <h2>Please log in</h2> </div> <div class="post_content"> <?php include 'loginform.php'; ?> <?php Plugins::act( 'theme_login' ); ?> </div> </div> </div> <?php include 'footer.php'; ?> <file_sep><!-- comments --> <div id="comments"> <h3 id="responses"><?php echo $post->comments->moderated->count; ?> Responses to &lsquo;<?php echo $post->title; ?>&rsquo;</h4> <p class="comment-feed"><a href="<?php echo $post->comment_feed_link; ?>">Atom feed for this entry.</a></p> <ol> <?php if ($post->comments->moderated->count) { $comment_count = 0; foreach ($post->comments->moderated as $comment) { ?> <li> <span id="count"><?php $comment_count++; echo $comment_count; ?></span> <h6><a href="<?php echo $comment->url; ?>" rel="external" target="_blank"><?php echo $comment->name; ?></a><span> // <?php echo $comment->date_out; ?><?php if ( $comment->status == Comment::STATUS_UNAPPROVED ) : ?> (In moderation)<?php endif; ?></span></h6> <div class="comment-content"> <?php echo $comment->content_out; ?> </div> </li> <?php } } else { ?> <li id="no-comments">There are currently no comments.</li> <?php } ?> </ol> <h3 id="replay">Leave a Reply</h3> <?php $post->comment_form()->out(); ?> </div> <!-- /comments --> <file_sep><?php class MagicArchives extends Plugin { public function action_init() { $this->add_template('page.archives', dirname(__FILE__) . '/page.archives.php'); $this->add_template('magicarchives', dirname(__FILE__) . '/archives.php'); $this->add_template('archive_posts', dirname(__FILE__) . '/posts.php'); } public function theme_magic_archives($theme) { $tags= Tags::get(array('nolimit' => true)); $theme->tags= $tags; $theme->posts= self::get_posts(); $theme->display('magicarchives'); return $archives; } public function action_ajax_archive_posts($handler) { $theme= Themes::create(); $theme->posts= self::get_posts($handler->handler_vars['search']); $theme->display('archive_posts'); } /** * Weights a tag for the tag cloud * **/ public static function tag_weight($count, $max) { return round( 10 * log($count + 1) / log($max + 1) ); } public function action_init_theme() { Stack::add( 'template_stylesheet', array( URL::get_from_filesystem(__FILE__) . '/magicarchives.css', 'screen' ), 'magicarchives' ); Stack::add( 'template_header_javascript', Site::get_url('scripts') . '/jquery.js', 'jquery' ); Stack::add( 'template_header_javascript', URL::get_from_filesystem(__FILE__) . '/magicarchives.js', 'magicarchives', array('jquery', 'ajax_manager') ); Stack::add( 'template_header_javascript', URL::get_from_filesystem(__FILE__) . '/ajax_manager.js', 'ajax_manager', 'jquery' ); Stack::add( 'template_header_javascript', 'magicArchives.endpoint=\'' . URL::get('ajax', array('context' => 'archive_posts')) . '\'', 'magicurl', 'magicarchives'); } public function action_ajax_getdates($param=array()) { $count = 0; $param = json_decode($param); $posts = Posts::get($param); ?> <div id="results"> <?php if(isset($posts[0])) { foreach($posts as $post): $count++ ?> <div id="post-<?php echo $count; ?>" class="entry"> <span id="name"><?php echo"$post->title"?></span> <span id="date"><?php echo "$post->pubdate_out" ?></span> </div> <?php endforeach; } else { ?> <div id="none" class="entry"> <span id="name">no posts where found</span> </div> <?php } ?> </div> <?php } /** * Fetch posts * * @param string Search query * @param array Tags to filter by * @param int The timestamp to use as the right-bound (lastest) border of fetched posts * @param int The number of posts to fetch * @return obj Posts object **/ static public function get_posts($search = null, $tags = array(), $right_bound = null, $limit = 20) { $params= array( 'content_type' => Post::type('entry'), 'limit' => $limit ); if($search != null && $search != '') { $params['criteria']= $search; } if($tags != null && count($tags) > 0) { $params['all:tag']= $tags; } if($right_bound != null) { $params['before']= $right_bound; } $posts= Posts::get($params); return $posts; } } ?><file_sep>google.load("visualization", "1", {packages:["piechart", "geomap", "linechart", "areachart"]}); function doareachart( data, options, id ) { var chart = new google.visualization.AreaChart( document.getElementById( id ) ); chart.draw( data, options ); } function dolinechart( data, options, id ) { var chart = new google.visualization.LineChart( document.getElementById( id ) ); chart.draw( data, options ); } function dopiechart( data, options, id ) { var chart = new google.visualization.PieChart( document.getElementById( id ) ); chart.draw( data, options ); } function dogeomap( data, options, id ) { var chart = new google.visualization.GeoMap( document.getElementById( id ) ); chart.draw( data, options ); } <file_sep><?php class SimpleBlacklist extends Plugin { const VERSION = '1.2'; public function info() { return array( 'name' => 'Simple Blacklist', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'version' => self::VERSION, 'description' => 'Anything defined here that exists in a comment (author name, URL, IP, body) will cause that comment to be silently discarded.', 'license' => 'Apache License 2.0' ); } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t('Configure'); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure') : $ui = new FormUI( strtolower( get_class( $this ) ) ); $blacklist= $ui->append( 'textarea', 'blacklist', 'option:simpleblacklist__blacklist', _t( 'Items to blacklist (words, IP addresses, URLs, etc):' ) ); $frequency= $ui->append('select', 'frequency', 'option:simpleblacklist__frequency', _t( 'Bypass blacklist for frequent commenters:' ) ); $frequency->options = array( '0' => 'No', '1' => 'Yes'); $ui->append( 'submit', 'save', 'Save' ); $ui->out(); break; } } } public function filter_comment_insert_allow( $allow, $comment ) { // don't blacklist logged-in users: they can speak freely if ( User::identify() ) { return true; } // and if the person has more than 5 comments approved, // they're likely not a spammer, so don't blacklist them $bypass= Options::get('simpleblacklist__frequency'); if ( $bypass ) { $comments= Comments::get( array( 'email' => $comment->email, 'name' => $comment->name, 'url' => $comment->url, 'status' => Comment::STATUS_APPROVED ) ); if ( $comments->count >= 5 ) { return true; } } $allow= true; $blacklist= explode( "\n", Options::get('simpleblacklist__blacklist') ); foreach ( $blacklist as $item ) { $item= trim(strtolower($item)); if ( '' == $item ) { continue; } // check against the commenter name if ( false !== strpos( strtolower($comment->name), $item ) ) { $allow= false; } // check against the commenter email if ( false !== strpos( strtolower($comment->email), $item ) ) { $allow= false; } // check against the commenter URL if ( false !== strpos( strtolower($comment->url), $item ) ) { $allow= false; } // check against the commenter IP address if ( false !== strpos( $comment->ip, $item ) ) { $allow= false; } // now check the body of the comment if ( false !== strpos( strtolower($comment->content), $item ) ) { $allow= false; } } return $allow; } } ?> <file_sep>Plugin: Woopra URL: http://www.awhitebox.com/woopra-plugin-for-habari Version: 0.6 Author: <NAME>. Purpose The Woopra plugin allows you to enable Woopra's tracking service for your site/blog. It also lets you exclude the inclusion of the code for certain users of your site and to tag visitors if they are logged in. Requirements The theme must call $theme->footer() in its footer template. If for some reason the template does not call that method, you can simply add the following to your template's footer.php, right before the </body> closing tag: <?php $theme->footer(); ?> Installation 1. Copy the plugin directory into your user/plugins directory. 2. Go to the plugins page of your Habari admin panel. 3. Click on the Activate button for Woopra plugin. Configuration If you have a woopra account, activating the plugin will enable Woopra tracking. You can also specify whether you want to tag memebers of your site when they visit, check the 'Enabled' check box and decide what type of avatar you want Woopra to display for those visitors: *Disabled: No avatar is displayed *Local user image: Habari has a field to specify the image URL for registered users, this option will set Woopra to display that image. *Gravatar: Based on the registered user email, his/her Gravatar will be displayed in Woopra. Uninstallation 1. Got to the plugins page of your Habari admin panel. 2. Click on the Deactivate button. 3. Delete the 'woopra' directory from you user/plugins directory. Changelog Version 0.6 - Fix Exclude typo Version 0.5 - Removed site id from configuration and JS code per last Woopra engine update (http://tinyurl.com/woopra-update). Version 0.4 - Updated the configuration to work with the New FormUI. Now compatible with Habari 0.5 and 0.6-alpha (revision 2458). Version 0.3 - Initial release <file_sep><?php /** * Summary Plugin Class * * This plugin adds a 'Summary' field on the entry publishing form, which is * available to templates and code as $post->info->summary. A summary element * is added to the Atom feed for entries with a non-empty summary. * **/ class SummaryPlugin extends Plugin { /** * function info * Returns information about this plugin * @return array Plugin info array **/ function info() { return array ( 'name' => 'Summary', 'url' => 'http://scratch.flyoverblues.com/summary.plugin.php', 'author' => '<NAME>', 'authorurl' => 'http://flyoverblues.com', 'version' => '1.0', 'description' => 'A plugin for providing post summaries', 'license' => 'Apache License 2.0', ); } /** * Add fields to the publish page for Pages * * @param FormUI $form The publish form * @param Post $post The post being published */ public function action_form_publish($form, $post) { $form->insert('tags', 'text', 'summary', 'null:null', _t('Summary'), 'admincontrol_textArea'); $form->summary->raw = true; $form->summary->value = $post->info->summary; $form->summary->tabindex = 3; $form->tags->tabindex = 4; $form->buttons->save->tabindex = 5; $form->summary->template = 'admincontrol_text'; } /** * Store summary in postinfo table when the entry is published. * * @param FormUI $form The publish form * @param Post $post The post being published */ public function action_publish_post($post, $form) { $post->info->summary = $form->summary->value; } /** * Add summary element to Atom feed, if a summary is present. * * @param SimpleXMLElement $feed_entry * @param Post $post The post corresponding to the feed entry */ public function action_atom_add_post($feed_entry, $post) { if ((boolean) $post->info->summary) { $feed_entry->addChild( 'summary', $post->info->summary ); } } } ?><file_sep><?php if(is_object($content->relativelypopular)) { ?> <div id="relativelypopular_plugin"> <ul> <?php foreach( $content->relativelypopular as $p): ?> <li> <a href="<?php echo $p->permalink; ?>"> <?php echo $p->title; ?> </a> </li> <?php endforeach; ?> </ul> </div> <?php } ?> <file_sep><div class="container plugins downloadableplugins" id="downloadableplugins"> <h2><?php _e('Downloadable Plugins'); ?></h2> <?php foreach ( $loadable as $plugin) { $theme->plugin = $plugin; $theme->display('plugin'); } ?> </div> <file_sep><?php class SiteMaintenanceLog extends EventLog { const LOG_MODULE = 'sitemaintenance'; public static function report_log( $message, $severity, $type, $data = null ) { parent::log($message, $severity, $type, self::LOG_MODULE, $data); } public static function add_report_type( $type ) { parent::register_type(self::LOG_MODULE, $type); } } <file_sep><?php foreach ($posts as $post) { ?> <div id="entry-<?php echo $post->slug; ?>" class="hentry entry <?php echo $post->statusname , ' ' , $post->tags_class; ?>"> <div class="entry-head"> <div class="entry-date"><abbr class="published" title="<?php echo $post->pubdate->out(HabariDateTime::ISO8601); ?>"><?php echo $post->pubdate->out('Y • m • d'); ?></abbr></div> <br class="clear" /> <h2 class="entry-title"><a href="<?php echo $post->permalink; ?>" title="<?php echo strip_tags($post->title_out); ?>" rel="bookmark"><?php echo $post->title_out; ?></a></h2> <br class="clear" /> <span class="comments-link"><a href="<?php echo $post->permalink; ?>#comments" title="<?php _e('Comments to this post', 'demorgan'); ?>"><?php echo $post->comments->approved->count; ?> <?php _ne('Comment', 'Comments', $post->comments->approved->count, 'demorgan'); ?></a></span> <?php if (is_array($post->tags)) { ?> <span class="entry-tags"><?php echo $post->tags_out; ?></span> <?php } ?> <?php if ($loggedin) { ?> <span class="entry-edit"><a href="<?php echo $post->editlink; ?>" title="<?php _e('Edit post', 'demorgan'); ?>"><?php _e('Edit', 'demorgan'); ?></a></span> <?php } ?> </div> <div class="entry-content"> <?php echo $post->content_out; ?> </div> </div> <?php } ?> <file_sep><?php /** * MyTheme is a custom Theme class for the PhoenixBlue Theme. * * @package Habari */ /** * @todo This stuff needs to move into the custom theme class: */ // Apply Format::autop() to post content... Format::apply( 'autop', 'post_content_out' ); // Apply Format::autop() to comment content... Format::apply( 'autop', 'comment_content_out' ); // Apply Format::tag_and_list() to post tags... Format::apply( 'tag_and_list', 'post_tags_out' ); // Apply Format::nice_date() to post date... Format::apply( 'nice_date', 'post_pubdate_out', 'F j, Y g:ia' ); // Apply Format::nice_date() to comment date... Format::apply( 'nice_date', 'comment_date_out', 'F jS, Y' ); // Limit post length to 1 paragraph or 100 characters. As currently implemented // in home.php and entry.multiple.php, the first post will be displayed in full // and subsequent posts will be excerpts. search.php uses excerpts for all posts. // Comment out this line to have full posts. //Format::apply_with_hook_params( 'more', 'post_content_excerpt', '<div class="more">[read more]</div>', 100, 1 ); // We must tell Habari to use MyTheme as the custom theme class: define( 'THEME_CLASS', 'MyTheme' ); /** * A custom theme for PhoenixBlue output */ class MyTheme extends Theme { /** * Add additional template variables to the template output. * * You can assign additional output values in the template here, instead of * having the PHP execute directly in the template. The advantage is that * you would easily be able to switch between template types (RawPHP/Smarty) * without having to port code from one to the other. * * You could use this area to provide "recent comments" data to the template, * for instance. * * Note that the variables added here should possibly *always* be added, * especially 'user'. * * Also, this function gets executed *after* regular data is assigned to the * template. So the values here, unless checked, will overwrite any existing * values. */ public function add_template_vars() { if( !$this->template_engine->assigned( 'pages' ) ) { $this->assign('pages', Posts::get( array( 'content_type' => 'page', 'status' => Post::status('published'), 'nolimit' => 1 ) ) ); } if( !$this->template_engine->assigned( 'user' ) ) { $this->assign('user', User::identify() ); } if( !$this->template_engine->assigned( 'tags' ) ) { $this->assign('tags', Tags::get() ); } if( !$this->template_engine->assigned( 'page' ) ) { $this->assign('page', isset( $page ) ? $page : 1 ); } if( !$this->template_engine->assigned( 'feed_alternate' ) ) { $matched_rule= URL::get_matched_rule(); switch ( $matched_rule->name ) { case 'display_entry': case 'display_page': $feed_alternate= URL::get( 'atom_entry', array( 'slug' => Controller::get_var('slug') ) ); break; case 'display_entries_by_tag': $feed_alternate= URL::get( 'atom_feed_tag', array( 'tag' => Controller::get_var('tag') ) ); break; case 'display_home': default: $feed_alternate= URL::get( 'atom_feed', array( 'index' => '1' ) ); } $this->assign('feed_alternate', $feed_alternate); } // Specify pages you want in your navigation here $this->assign('nav_pages', Posts::get( array( 'content_type' => 'page', 'status' => 'published', 'nolimit' => 1 ) ) ); parent::add_template_vars(); } public function header() { if ( User::identify() != FALSE ) { Stack::add( 'template_header_javascript', Site::get_url('scripts') . '/jquery.js', 'jquery' ); } } public function action_form_comment( $form ) { $this->add_template('formcontrol_text', dirname(__FILE__).'/forms/formcontrol_text.php', true); $this->add_template('formcontrol_textarea', dirname(__FILE__).'/forms/formcontrol_textarea.php', true); $form->cf_commenter->caption = 'Name'; $form->cf_email->caption = 'Mail (will not be published)'; $form->cf_submit->caption = 'Submit Comment'; } } ?> <file_sep><?php // Currently using another library because RemoteRequest is buggy as hell with https require( dirname(__FILE__) . '/simplenoteapi.php' ); class Simplenote extends Plugin implements MediaSilo { const SILO_NAME = 'Simplenote'; static $cache = array(); public function action_init() { if( isset( User::identify()->info->simplenote_email ) ) { $this->api = new SimpleAPI( User::identify()->info->simplenote_email, User::identify()->info->simplenote_password ); } // $note = $this->api->get( "<KEY>" ); // $note->content = 'clear post'; // Utils::debug( $note, $note->update(), $this->get_notes() ); // // $note = new Note('<KEY>'); // $note->delete(); } /** * Provide plugin help **/ public function help() { $help = sprintf( _t( '<p>Authentication settings can be configured from your <a href="%s">profile</a> page.</p>' ), URL::get('admin', 'page=user') ); return $help; } /** * Check for updates */ public function action_update_check() { Update::add( $this->info->name, '9f2d9881-ebad-489d-9aa7-9ae7b6c09a38', $this->info->version ); } /** * Create plugin configuration **/ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t('Configure'); } return $actions; } /** * Create configuration panel */ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure') : $form = new FormUI( strtolower( get_class( $this ) ) ); $form->append( 'text', 'search', 'simplenote__search', _t('Search query:') ); $form->append( 'submit', 'save', _t('Save') ); $form->out(); break; } } } /** * Add the configuration to the user page **/ public function action_form_user( $form, $user ) { $fieldset = $form->append( 'wrapper', 'simplynoted', 'Simplenote' ); $fieldset->class = 'container settings'; $fieldset->append( 'static', 'simplynoted', '<h2>' . htmlentities( 'Simplenote', ENT_COMPAT, 'UTF-8' ) . '</h2>' ); $email = $fieldset->append( 'text', 'simplenote_email', 'null:null', _t('Email:'), 'optionscontrol_text' ); $email->class[] = 'item clear'; $email->add_validator( 'validate_email' ); $email->value = $user->info->simplenote_email; $password = $fieldset->append( 'password', '<PASSWORD>', 'null:null', _t('Password:'), 'optionscontrol_text' ); $password->type = '<PASSWORD>'; $password->class[] = 'item clear'; $password->add_validator( array( $this, 'validate_credentials' ), $fieldset->simplenote_email->value ); $password->value = $user->info->simplenote_password; $form->move_before( $fieldset, $form->page_controls ); } /** * Save authentication fields **/ public function filter_adminhandler_post_user_fields( $fields ) { $fields[] = 'simplenote_email'; $fields[] = 'simp<PASSWORD>'; return $fields; } /** * A validator to check the supplied credentials **/ public function validate_credentials( $password, $control, $form, $email) { $api = new SimpleAPI; if( $api->authenticate( $email, $password ) ) { return array(); } else { return array( _t( 'Authentication failed. Check your email and password.') ); } } /** * Add note field to publish form **/ public function action_form_publish( $form, $post ) { // Create the Note display field $form->append('hidden', 'note_key', 'null:null'); $form->note_key->id= 'note_key'; $form->note_key->value = $post->note->key; // Create the Notes display field $form->append('textarea', 'notes', 'null:null', _t('Notes'), 'admincontrol_textarea'); $form->notes->class[] = 'resizable'; $form->notes->raw = true; $form->notes->value = $post->note->content; $form->move_before( $form->notes, $form->content ); } /** * Save our data to the database */ public function action_publish_post( $post, $form ) { $this->action_form_publish($form, $post); if( $form->notes->value != NULL ) { $note = new Note( $form->note_key->value ); $note->content = $form->notes->value; $note->update(); // Utils::debug( $note, $note->update(), $this->get_notes() ); $post->info->note_key = $note->key; } // exit; } /** * Return related note **/ public function filter_post_note( $note, $post ) { if( isset( $post->info->note_key ) ) { $note = $this->api->get( $post->info->note_key ); return $note; } else { return new Note(); } } /** * Gets a list of notes **/ private function get_notes() { $notes = $this->api->search( Options::get('simplenote__search') ); return $notes; } public function action_admin_footer() { echo '<script type="text/javascript">'; require('simplynoted.js'); echo '</script>'; } /** * Return basic information about this silo * name- The name of the silo, used as the root directory for media in this silo * icon- An icon to represent the silo */ public function silo_info() { if( isset( $this->api ) ) { return array('name' => self::SILO_NAME, 'icon' => URL::get_from_filesystem(__FILE__) . '/icon.png'); } else { return array(); } } /** * Return directory contents for the silo path * * @param string $path The path to retrieve the contents of * @return array An array of MediaAssets describing the contents of the directory */ public function silo_dir($path) { $results = array(); $user = User::identify()->info->lastfm_username; $section = strtok($path, '/'); switch($section) { case '': foreach($this->get_notes() as $note) { $props = array(); $props['title'] = $note->title; $props['filetype'] = 'note'; $props['content'] = $note->content; $props['summary'] = $note->summary; $props['key'] = $note->key; $results[] = new MediaAsset( self::SILO_NAME . '/' . $note->key, false, $props ); } break; } return $results; } /** * Provide controls for the media control bar * * @param array $controls Incoming controls from other plugins * @param MediaSilo $silo An instance of a MediaSilo * @param string $path The path to get controls for * @param string $panelname The name of the requested panel, if none then emptystring * @return array The altered $controls array with new (or removed) controls * * @todo This should really use FormUI, but FormUI needs a way to submit forms via ajax */ public function filter_media_controls( $controls, $silo, $path, $panelname ) { $controls = array(); return $controls; } public function silo_upload_form() { } /** * Get the file from the specified path * * @param string $path The path of the file to retrieve * @param array $qualities Qualities that specify the version of the file to retrieve. * @return MediaAsset The requested asset */ public function silo_get($path, $qualities = null) { } /** * Get the direct URL of the file of the specified path * * @param string $path The path of the file to retrieve * @param array $qualities Qualities that specify the version of the file to retrieve. * @return string The requested url */ public function silo_url($path, $qualities = null) { } /** * Create a new asset instance for the specified path * * @param string $path The path of the new file to create * @return MediaAsset The requested asset */ public function silo_new($path) { } /** * Store the specified media at the specified path * * @param string $path The path of the file to retrieve * @param MediaAsset $ The asset to store */ public function silo_put($path, $filedata) { } /** * Delete the file at the specified path * * @param string $path The path of the file to retrieve */ public function silo_delete($path) { } /** * Retrieve a set of highlights from this silo * This would include things like recently uploaded assets, or top downloads * * @return array An array of MediaAssets to highlihgt from this silo */ public function silo_highlights() { } /** * Retrieve the permissions for the current user to access the specified path * * @param string $path The path to retrieve permissions for * @return array An array of permissions constants (MediaSilo::PERM_READ, MediaSilo::PERM_WRITE) */ public function silo_permissions($path) { } /** * Return directory contents for the silo path * * @param string $path The path to retrieve the contents of * @return array An array of MediaAssets describing the contents of the directory */ public function silo_contents() { } } /** * Interfaces with the Simplenote API */ class SimpleAPI { /** * Construct stuff **/ public function __construct( $email = NULL, $password = NULL ) { $this->api = new simplenoteapi; if( $email != NULL and $password != NULL ) { $this->authenticate( $email, $password ); } } /** * Finds notes which match a given query **/ public function search( $query ) { $result = $this->api->search( $query, 2000000 ); $notes = array(); foreach( $result['results'] as $key => $content ) { $note = new Note( $key ); $note->content = $content; $notes[] = $note; } return $notes; } /** * Gets a note **/ public function get( $key ) { $result = $this->api->get_note( $key ); $note = new Note( $key ); $note->content = $result['content']; return $note; } /** * Updates a note **/ public function update( $key, $content ) { if( $key = $this->api->save_note( $content, $key ) ) { return $key; } else { return false; } } /** * Deletes a note **/ public function delete( $key ) { if( $this->api->delete_note( $key ) ) { return true; } else { return false; } } /** * Authenticates with a given username and password * * @return bool successful? **/ public function authenticate( $email, $password ) { return $this->api->login( $email, $password ); } } /** * Represents a single note */ class Note { public $content = ''; public function __construct( $key = '' ) { $this->key = $key; } public function __get( $name ) { switch( $name ) { case 'title': $title = explode( "\n", $this->content); return $title[0]; case 'summary': $summary = Utils::truncate( $this->content, '100' ); return $summary; } } /** * Update the note **/ public function update() { $api = new SimpleAPI( User::identify()->info->simplenote_email, User::identify()->info->simplenote_password ); $content = str_replace( "\r", '', $this->content ); // $content = utf8_decode( $this->content ); // Utils::debug( $content ); $this->key = $api->update( $this->key, $content ); return true; } /** * Delete the note **/ public function delete() { $api = new SimpleAPI( User::identify()->info->simplenote_email, User::identify()->info->simplenote_password ); return $api->delete( $this->key ); } } ?><file_sep><?php $theme->display( 'header'); ?> <!-- home --> <div id="left-col"> <?php foreach ( $posts as $post ) { ?> <div class="post"> <h2><a href="<?php echo $post->permalink; ?>" title="<?php echo $post->title; ?>"><?php echo $post->title_out; ?></a></h2> <p class="details"><?php echo $post->pubdate_out; ?> &bull; Posted by <?php echo $post->author->displayname; ?> &bull; <a href="<?php echo $post->permalink; ?>#comments"><?php echo $post->comments->approved->count; ?> <?php echo _n( 'Comment', 'Comments', $post->comments->approved->count ); ?></a></p> <?php echo $post->content_excerpt; ?> <p class="bottom"> <span><a href="<?php echo $post->permalink; ?>#comments">&rarr; <?php echo $post->comments->approved->count; ?> <?php echo _n( 'Comment', 'Comments', $post->comments->approved->count ); ?></a></span> <?php if ( count( $post->tags ) ) { ?> <strong>Tags:</strong> <?php echo $post->tags_out; ?> <?php } ?> </p> </div> <?php } ?> <div class="clear"></div> <div id="page-selector"> <?php $theme->prev_page_link(); ?> <?php $theme->page_selector( null, array( 'leftSide' => 2, 'rightSide' => 2 ) ); ?> <?php $theme->next_page_link(); ?> </div> </div> <div id="right-col"> <?php $theme->display ( 'sidebar' ); ?> </div> <!-- /home --> <?php $theme->display ('footer'); ?> <file_sep><?php /** * Plugin class that extends post editing functionality to allow selection of styles from a given directory. Any style * located in this directory will be checkbox selectable allowing multiple style selection. The plugin will also read * any sub-directories and make them drop-down list selectable. * * */ class DynamicStyleSelecor extends Plugin { //TODO: Change these to an configurable option in the admin screen const CSS_PATH = 'design/css/alts/'; const PARENT_CSS_DIRECTORY = 'alts'; const OPTION_PREFIX = 'css_option_'; const STYLE_EXTENSION = 'css'; const DEFAULT_STYLE_SELECTION = '--Select a style--'; /** * Add update beacon support */ public function action_update_check() { Update::add( $this->info->name, '2A105C98-A645-11DE-8977-425B55D89593', $this->info->version ); } /** * This function creates the style selection form, and appends it to the intercepted FormUI object. During the * construction of the form it will retrieve any existing selections for the post. * * The parent style directory defined with @param PARENT_CSS_DIRECTORY will have a checkbox form created, while * any sub-directory will have a drop-down selection form created for the style files included. * * @param $form The intercepted FormUI object to attach the extra form when editting posts. * @param $post The intercepted Post object which may contain information about already selected styles. * @param $context Not explicitly used in this function. * @return unknown_type */ public function action_form_publish($form, $post, $context) { //To satisfy reference constraint for some functions $default_css_selection = self::DEFAULT_STYLE_SELECTION; $parent_css_dir = self::PARENT_CSS_DIRECTORY; //Grab the 2D array of arrays. $css_styles = self::getCssStyleFileNames(Site::get_dir('theme', TRUE) . self::CSS_PATH); $keys = array_keys($css_styles); if (count($css_styles) == 0) { return; /* no fields to make */ } //Create the object that will be the style selection form $css_styles_fieldset = $form->insert('settings', 'fieldset', 'css_styles_fieldset', _t('Select style') ); $css_styles_fieldset->class = 'container'; $already_selected_css_styles = array(); //Retrieve already existing style selections saved in the database foreach($keys as $key) { $already_selected_css_styles[$key] = explode(',', $post->info->dynamicStyles[$key]); } $css_style_option_list = array(); //Iterate through all existing styles and create the relevant form controls (checkbox or selection box) while($styles_in_directory = current($css_styles)) { $current_dir = key($css_styles); //If we are at the parent directory, create the checkbox form if($current_dir == $parent_css_dir) { foreach($css_styles[$parent_css_dir] as $css_style) { /* skip if it's the none options */ if ($css_style == self::DEFAULT_STYLE_SELECTION) continue; //Since checkbox requires one id per box to identify which has been selected or not, need individual HTML name $css_style_html_name = self::OPTION_PREFIX . preg_replace("/\s+/", "", $css_style); $postprop = $css_styles_fieldset->append('checkbox', $css_style_html_name, 'null:null', _t('Page style: ' . ucwords($css_style)), 'tabcontrol_checkbox'); //If there are any existing selections, portray them as selected checkboxes if(in_array($css_style, $already_selected_css_styles[$parent_css_dir])) { $postprop->value = true; } else { $postprop->value = false; } $postprop->class = 'container'; } } //If we have a sub-directory, then create the drop-down selection form else { //One HTML name for each select-one selections $css_style_html_name = self::OPTION_PREFIX . preg_replace("/\s+/", "", $current_dir); //Since we need to add the option for the default value //array_unshift($default_css_selection, $styles_in_directory); $css_styles_fieldset->append('select', $css_style_html_name, 'null:null', _t('Style set: ' . ucwords($current_dir)), $styles_in_directory, 'tabcontrol_select'); //If there are any existing selections, have the selection pre-selected if($already_selected_css_styles[$current_dir] != self::DEFAULT_STYLE_SELECTION) { //Position 0 since we expect that there is only one selected for the drop-down selection $already_selected = array_search($already_selected_css_styles[$current_dir][0], $styles_in_directory); $css_styles_fieldset->{$css_style_html_name}->value = $already_selected; } } next($css_styles); } } /** * This function saves the style selection for the post to the database. The funciton will save any selections from the * parent style directory as a comma-separated string. Any sub-directories will save one style selection. * * @param $post Intercepted post object to be modified with relative selections made on the form to then be saved in the * database. * @param $form Intercepted form object to be used to retrieve form selections to be put into the post object before it is * committed into the database. * @return unknown_type */ public function action_publish_post( $post, $form ) { //To satisfy reference constraint for some functions $default_css_selection = self::DEFAULT_STYLE_SELECTION; $parent_css_dir = self::PARENT_CSS_DIRECTORY; //Grab all available styles $css_styles = array(); $css_styles = self::getCssStyleFileNames(Site::get_dir('theme', TRUE) . self::CSS_PATH, $css_styles); $keys = array_keys($css_styles); $dynamicStyles = array(); foreach($keys as $key) { $dynamicStyles[$key] = ''; //For the parent style directory, retrieve individual checkbox selections via the regenerated html ids and save them //in the database as a comma-sepearated string if($key == $parent_css_dir) { foreach($css_styles[$parent_css_dir] as $css_style) { /* skip if it's the none options */ if ($css_style == self::DEFAULT_STYLE_SELECTION) continue; if($form->css_styles_fieldset->{self::OPTION_PREFIX . $css_style}->value == true) { $dynamicStyles[$parent_css_dir] .= $css_style . ','; } } } //For sub-directories, we only expect one selection. Save the selection with its respective data storage name else { $drop_down_id = $form->css_styles_fieldset->{self::OPTION_PREFIX . $key}->value; $dynamicStyles[$key] = $css_styles[$key][$drop_down_id]; } } /* finally, set the data */ $post->info->dynamicStyles = $dynamicStyles; } /** * This is a function which retrieves all style files under a given directory path. The function will recurse through * any sub-directories. The function will ignore any file/directory name which starts with a '.'. * * @param $dir_path The given path to retrieve all style files under. * @param $dir_file_map 2D array to fill the contents with a list of style file names, and return. See @return for full description. * @return 2D array with the top level array having keys corresponding to a directory name. Each key will reference another * list of strings. Each string will represent the name of a style file without the file extension. */ private function getCssStyleFileNames($dir_path, $dir_file_map = array()) { //Alter this to include any specific exlusion other than files that start with '.' $exclude_array = array(); $file_list = array(); if(is_dir($dir_path)) { //In order to get the last element in the array as the directory name $dir_path = rtrim($dir_path, '/'); $dir_path_array = explode('/', $dir_path); //In order for the directory path manipulation to work in the following code $dir_path .= '/'; //Grab the last directory in the path in order to use as a key to include in the $dir_file_map $map_key = end($dir_path_array); $dir_handle = opendir($dir_path); while(($filename = readdir($dir_handle)) != false) { //To ignore any direcotries or files starting with '.' such as '.svn' if(strpos($filename, '.') != 0 || strpos($filename, '.') === false) { $filetype = filetype($dir_path . $filename); //If we detect a directory if(!in_array($filename, $exclude_array)) { if($filetype == 'dir') { //Recurse into the directory $dir_file_map = self::getCssStyleFileNames($dir_path . $filename, $dir_file_map); } elseif ($filetype == 'file') { $filename_array = explode('.', $filename); if(end($filename_array) == self::STYLE_EXTENSION) { $file_list[] = substr($filename, 0, - (strlen(self::STYLE_EXTENSION) + 1 /* for the dot */ )); } } } } } } /* add a default 'none' option if there are options', and add this set to list */ if (count($file_list) > 0) { /* add a default 'none' style */ array_unshift($file_list, self::DEFAULT_STYLE_SELECTION); $dir_file_map[$map_key] = $file_list; } return $dir_file_map; } function action_template_header( $theme ) { if (isset($theme->post->info->dynamicStyles) ) { foreach ( $theme->post->info->dynamicStyles as $styleGroup => $style ) { if ($styleGroup == self::PARENT_CSS_DIRECTORY) { /* mannny options */ foreach(explode(',', $style) as $singleStyle) { if ($singleStyle != '') { Stack::add( 'template_stylesheet', array( Site::get_url( 'theme' ) .'/' . self::CSS_PATH . $singleStyle . '.' . self::STYLE_EXTENSION, 'screen' ) ); } } } else { /* we are in a directory */ if ($style != self::DEFAULT_STYLE_SELECTION) { Stack::add( 'template_stylesheet', array( Site::get_url( 'theme' ) .'/' . self::CSS_PATH . $styleGroup . '/' . $style . '.' . self::STYLE_EXTENSION, 'screen' ) ); } } } } } } ?><file_sep><?php class BeaconTest extends Plugin { public function action_update_check ( ) { // add an extra GUID, in addition to the one in our .xml file to pretend a theme was registered Update::add( 'Test', '10cbaf18-bdd2-48e1-b0d3-e1853a4c649d', '3.0.2' ); // add an extra GUID, in addition to the one in our .xml file to pretend a plugin was registered Update::add( 'Test', '7a0313be-d8e3-11d1-8314-0800200c9a66', '0.9' ); } } ?><file_sep><?php /** * AtomThreading Class * **/ class AtomThreading extends Plugin { private $class_name = ''; /** * On plugin activation, set the default options */ public function action_plugin_activation($file) { if (realpath($file) === __FILE__) { $this->class_name = strtolower(get_class($this)); } } /** * On plugin init, add the template included with this plugin to the available templates in the theme */ public function action_init() { $this->class_name = strtolower(get_class($this)); $this->load_text_domain($this->class_name); } public function filter_atom_get_collection_namespaces($namespaces) { $namespaces['thr'] = 'http://purl.org/syndication/thread/1.0'; return $namespaces; } public function action_atom_add_post($xml, $post) { $link = $xml->addChild('link'); $link->addAttribute('rel', 'replies'); //type="application/atom+xml" is default, could be omitted //$link->addAttribute('type', 'application/atom+xml'); $link->addAttribute('href', URL::get('atom_feed_entry_comments', array('slug' => $post->slug))); $link->addAttribute('thr:count', $post->comments->approved->count, 'http://purl.org/syndication/thread/1.0'); if ($post->comments->approved->count > 0) $link->addAttribute('thr:updated', HabariDateTime::date_create(end($post->comments->approved)->date)->get(HabariDateTime::ATOM), 'http://purl.org/syndication/thread/1.0'); $xml->addChild('thr:total', $post->comments->approved->count, 'http://purl.org/syndication/thread/1.0'); } public function action_atom_add_comment($xml, $comment) { $in_reply_to = $xml->addChild('thr:in-reply-to', NULL, 'http://purl.org/syndication/thread/1.0'); $in_reply_to->addAttribute('ref', $comment->post->guid); $in_reply_to->addAttribute('href', $comment->post->permalink); $in_reply_to->addAttribute('type', 'text/html'); } } ?> <file_sep><?php /** * Movable Type Importer * Import Movable Type Database * * @package mtimport * @version $Id$ * @author ayunyan <<EMAIL>> * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link http://habariproject.org/ * * Tested with Movable Type Ver 4.12 (MySQL) */ require_once('mtparser.php'); class MTImport extends Plugin implements Importer { private $supported_importers; private $import_batch = 100; /** * plugin information * * @access public * @retrun void */ public function info() { return array( 'name' => 'Movable Type Importer', 'version' => '0.02-alpha', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Import Movable Type Database', 'guid' => 'd77b95b2-769e-11dd-90de-001b210f913f' ); } /** * action: init * * @access public * @return void */ public function action_init() { $this->load_text_domain('mtimport'); $this->supported_importers = array(); $this->supported_importers['mysql'] = _t('Movable Type Database (MySQL)', 'mtimport'); $this->supported_importers['file'] = _t('Movable Type Export File', 'mtimport'); } /** * action: update_check * * @access public * @return void */ public function action_update_check() { Update::add('Movable Type Importer', $this->info->guid, $this->info->version); } /** * filter: import_names * * @access public * @param array $import_names * @return array */ public function filter_import_names($import_names) { return array_merge($import_names, $this->supported_importers); } /** * Plugin filter that supplies the UI for the MT importer * * @access public * @param string $stageoutput The output stage UI * @param string $import_name The name of the selected importer * @param string $stage The stage of the import in progress * @param string $step The step of the stage in progress * @return mixed output for this stage of the import */ public function filter_import_stage($stageoutput, $import_name, $stage, $step) { if (($importer = array_search($import_name, $this->supported_importers)) === false) { return $stageoutput; } if (empty($stage)) $stage = 1; $stage_method = $importer . '_stage_' . $stage; if (!method_exists($this, $stage_method)) { return sprintf(_t('Unknown Stage: %s', 'mtimport'), $stage); } $output = $this->$stage_method(array()); return $output; } /** * filter: import_form_enctype * * @access public * @param string $enctype * @param string $import_name * @param string $stage * @return string */ public function filter_import_form_enctype($enctype, $import_name, $stage) { if (($importer = array_search($import_name, $this->supported_importers)) === false) { return $enctype; } if ($importer == 'file') { return 'multipart/form-data'; } return $enctype; } /** * first stage of Movable Type (MySQL) import process * * @access private * @return string The UI for the first stage of the import process */ private function mysql_stage_1($inputs) { $default_values = array( 'db_name' => '', 'db_host' => 'localhost', 'db_user' => '', 'db_pass' => '', 'db_prefix' => 'mt_', 'warning' => '' ); $inputs = array_merge( $default_values, $inputs ); extract( $inputs ); ob_start(); ?> <p><?php echo _t('Habari will attempt to import from a Movable Type Database.', 'mtimport'); ?></p> <?php if (!empty($warning)): ?> <p class="warning"><?php echo htmlspecialchars($warning); ?></p> <?php endif; ?> <p><?php echo _t('Please provide the connection details for an existing Movable Type database:', 'mtimport'); ?></p> <table> <tr><td><?php echo _t('Database Name', 'mtimport'); ?></td><td><input type="text" name="db_name" value="<?php echo htmlspecialchars($db_name); ?>"></td></tr> <tr><td><?php echo _t('Database Host', 'mtimport'); ?></td><td><input type="text" name="db_host" value="<?php echo htmlspecialchars($db_host); ?>"></td></tr> <tr><td><?php echo _t('Database User', 'mtimport'); ?></td><td><input type="text" name="db_user" value="<?php echo htmlspecialchars($db_user); ?>"></td></tr> <tr><td><?php echo _t('Database Password', '<PASSWORD>'); ?></td><td><input type="password" name="db_pass" value="<?php echo htmlspecialchars($db_pass); ?>"></td></tr> <tr><td><?php echo _t('Table Prefix', 'mtimport'); ?></td><td><input type="text" name="db_prefix" value="<?php echo htmlspecialchars($db_prefix); ?>"></td></tr> </table> <input type="hidden" name="stage" value="2"> <p class="submit"><input type="submit" name="import" value="<?php echo _t('Next', 'mtimport'); ?>" /></p> <?php $output = ob_get_contents(); ob_end_clean(); return $output; } /** * second stage of Movable Type (MySQL) import process * * @access private * @return string The UI for the first stage of the import process */ private function mysql_stage_2($inputs) { $valid_fields = array('db_name','db_host','db_user','db_pass','db_prefix'); $inputs = array_merge(Controller::get_handler_vars()->filter_keys($valid_fields)->getArrayCopy(), $inputs); extract($inputs); if(($mtdb = $this->mt_connect($db_host, $db_name, $db_user, $db_pass, $db_prefix)) === false) { $inputs['warning']= _t('Could not connect to the Movable Type database using the values supplied. Please correct them and try again.', 'mtimport'); return $this->mysql_stage_1($inputs); } $blogs = $mtdb->get_results("SELECT blog_id, blog_name FROM {$db_prefix}blog;"); ob_start(); ?> <p><?php echo _t('Please specify Blog which imports:', 'mtimport'); ?></p> <table> <tr><td><?php echo _t('Import Blog', 'mtimport'); ?></td><td> <select name="blog_id" size="1"> <?php while (list(, $blog) = @each($blogs)): ?> <option value="<?php echo $blog->blog_id; ?>"><?php echo htmlspecialchars($blog->blog_name); ?></option> <?php endwhile; ?> </select> </td></tr> </table> <input type="hidden" name="stage" value="3"> <?php while (list($key, $value) = @each($inputs)): ?> <input type="hidden" name="<?php echo htmlspecialchars($key); ?>" value="<?php echo htmlspecialchars($value); ?>" /> <?php endwhile; ?> <p class="submit"><input type="submit" name="import" value="<?php echo _t('Import', 'mtimport'); ?>" /></p> <?php $output = ob_get_contents(); ob_end_clean(); return $output; } /** * third stage of Movable Type (MySQL) import process * * @access private * @return string The UI for the first stage of the import process */ private function mysql_stage_3($inputs) { $valid_fields = array('db_name','db_host','db_user','db_pass','db_prefix', 'blog_id'); $inputs = array_merge(Controller::get_handler_vars()->filter_keys($valid_fields)->getArrayCopy(), $inputs); extract($inputs); if(($mtdb = $this->mt_connect($db_host, $db_name, $db_user, $db_pass, $db_prefix)) === false) { $inputs['warning']= _t('Could not connect to the Movable Type database using the values supplied. Please correct them and try again.', 'mtimport'); return $this->mysql_stage_1($inputs); } $ajax_url = URL::get('auth_ajax', array('context' => 'mt_mysql_import_users')); EventLog::log(sprintf(_t('Starting import from "%s"'), $db_name)); Options::set('import_errors', array()); ob_start(); ?> <p><?php _e('Import In Progress'); ?></p> <div id="import_progress"><?php _e('Starting Import...'); ?></div> <script type="text/javascript"> // A lot of ajax stuff goes here. $(document).ready(function(){ $('#import_progress').load( "<?php echo $ajax_url; ?>", { db_host: "<?php echo htmlspecialchars($db_host); ?>", db_name: "<?php echo htmlspecialchars($db_name); ?>", db_user: "<?php echo htmlspecialchars($db_user); ?>", db_pass: "<?php echo htmlspecialchars($db_pass); ?>", db_prefix: "<?php echo htmlspecialchars($db_prefix); ?>", blog_id: "<?php echo htmlspecialchars($blog_id); ?>", postindex: 0 } ); }); </script> <?php $output = ob_get_contents(); ob_end_clean(); return $output; } /** * The plugin sink for the auth_ajax_mt_import_users hook. * Responds via authenticated ajax to requests for post importing. * * @access public * @param mixed $handler * @return */ public function action_auth_ajax_mt_mysql_import_users($handler) { $valid_fields = array('db_name','db_host','db_user','db_pass','db_prefix','userindex', 'blog_id'); $inputs = Controller::get_handler_vars()->filter_keys($valid_fields)->getArrayCopy(); extract($inputs); $mtdb = $this->mt_connect($db_host, $db_name, $db_user, $db_pass, $db_prefix); if(!$mtdb ) { EventLog::log(sprintf(_t('Failed to import from "%s"'), $db_name), 'crit'); echo '<p>'._t( 'Failed to connect using the given database connection details.' ).'</p>'; return; } $mt_users = $mtdb->get_results("SELECT author_id AS mt_id, author_name AS username, author_email AS email FROM {$db_prefix}author;", array(), 'User'); $usercount = 0; echo _t('<p>Importing users...</p>'); @reset($mt_users); while (list(, $user) = @each($mt_users)) { $habari_user = User::get_by_name($user->username); // If username exists if(!($habari_user instanceof User)) { try { $user->info->mt_id = $user->mt_id; // This should probably remain commented until we implement ACL more, // or any imported user will be able to log in and edit stuff //$user->password = <PASSWORD>}' . $user->password; $user->exclude_fields(array('mt_id')); $user->insert(); $usercount++; } catch( Exception $e ) { EventLog::log($e->getMessage(), 'err', null, null, print_r(array($user, $e), 1)); $errors = Options::get('import_errors'); $errors[] = $user->username . ' : ' . $e->getMessage(); Options::set('import_errors', $errors); } } } $ajax_url = URL::get('auth_ajax', array('context' => 'mt_mysql_import_posts')); ?> <script type="text/javascript"> // A lot of ajax stuff goes here. $( document ).ready( function(){ $( '#import_progress' ).load( "<?php echo $ajax_url; ?>", { db_host: "<?php echo htmlspecialchars($db_host); ?>", db_name: "<?php echo htmlspecialchars($db_name); ?>", db_user: "<?php echo htmlspecialchars($db_user); ?>", db_pass: "<?php echo htmlspecialchars($db_pass); ?>", db_prefix: "<?php echo htmlspecialchars($db_prefix); ?>", blog_id: "<?php echo htmlspecialchars($blog_id); ?>", postindex: 0 } ); }); </script> <?php } /** * The plugin sink for the auth_ajax_mt_import_posts hook. * Responds via authenticated ajax to requests for post importing. * * @access public * @param AjaxHandler $handler The handler that handled the request, contains $_POST info */ public function action_auth_ajax_mt_mysql_import_posts($handler) { $valid_fields = array('db_name','db_host','db_user','db_pass','db_prefix','postindex', 'blog_id'); $inputs = Controller::get_handler_vars()->filter_keys($valid_fields)->getArrayCopy(); extract($inputs); $mtdb = $this->mt_connect($db_host, $db_name, $db_user, $db_pass, $db_prefix); if(!$mtdb) { EventLog::log(sprintf(_t('Failed to import from "%s"'), $db_name), 'crit'); echo '<p>'._t( 'The database connection details have failed to connect.' ).'</p>'; return; } $postcount = $mtdb->get_value("SELECT count(entry_id) FROM {$db_prefix}entry WHERE entry_blog_id = '{$blog_id}';"); $min = $postindex * $this->import_batch + ($postindex == 0 ? 0 : 1); $max = min( ( $postindex + 1 ) * $this->import_batch, $postcount ); $user_map = array(); $userinfo = DB::get_results('SELECT user_id, value FROM ' . DB::table('userinfo') . ' WHERE name = "mt_id";'); @reset($userinfo); while (list(, $info) = @each($userinfo)) { $user_map[$info->value] = $info->user_id; } echo sprintf(_t('<p>Importing posts %d-%d of %d.</p>'), $min, $max, $postcount); flush(); $posts = $mtdb->get_results("SELECT entry_id AS id, entry_author_id AS user_id, entry_authored_on AS pubdate, entry_modified_on AS updated, entry_title AS title, entry_atom_id AS guid, entry_basename AS slug, entry_text, entry_text_more, entry_class, entry_status, {$db_prefix}category.category_label FROM {$db_prefix}entry LEFT JOIN {$db_prefix}category ON entry_category_id = category_id WHERE entry_blog_id = '{$blog_id}' ORDER BY id DESC LIMIT {$min}," . $this->import_batch . ';', array(), 'Post'); $post_map = DB::get_column("SELECT value FROM " . DB::table('postinfo') . " WHERE name='mt_id';"); @reset($posts); while (list(, $post) = @each($posts)) { // already exists skipped if(in_array($post->id, $post_map)) continue; $tags = $mtdb->get_column("SELECT tag_name FROM {$db_prefix}objecttag LEFT JOIN {$db_prefix}tag ON objecttag_tag_id = tag_id WHERE objecttag_object_datasource = 'entry' AND objecttag_object_id = {$post->id};"); $post_array = $post->to_array(); $tags[] = $post_array['category_label']; unset($post_array['category_label']); $tags = implode(',', $tags); if ($post_array['entry_status'] == 2) { $post_array['status'] = Post::status('published' ); } else { $post_array['status'] = Post::status('draft'); } unset($post_array['entry_status']); switch($post_array['entry_class']) { case 'entry': $post_array['content_type'] = Post::type( 'entry' ); break; default: // We're not inserting MT's media records. That would be silly. continue; } unset($post_array['entry_class']); $post_array['content'] = $post_array['entry_text'] . $post_array['entry_text_more']; unset($post_array['entry_text']); unset($post_array['entry_text_more']); $p = new Post($post_array); $p->slug = $post->slug; $p->user_id = $user_map[$p->user_id]; $p->guid = $p->guid; // Looks fishy, but actually causes the guid to be set. $p->tags = $tags; $p->info->mt_id = $post_array['id']; // Store the MT post id in the post_info table for later try { $p->insert(); } catch( Exception $e ) { EventLog::log($e->getMessage(), 'err', null, null, print_r(array($p, $e), 1)); $errors = Options::get('import_errors'); $errors[] = $p->title . ' : ' . $e->getMessage(); Options::set('import_errors', $errors); } } if($max < $postcount) { $ajax_url = URL::get('auth_ajax', array('context' => 'mt_mysql_import_posts')); $postindex++; } else { $ajax_url = URL::get('auth_ajax', array('context' => 'mt_mysql_import_comments')); } ?> <script type="text/javascript"> $('#import_progress').load( "<?php echo $ajax_url; ?>", { db_host: "<?php echo htmlspecialchars($db_host); ?>", db_name: "<?php echo htmlspecialchars($db_name); ?>", db_user: "<?php echo htmlspecialchars($db_user); ?>", db_pass: "<?php echo htmlspecialchars($db_<PASSWORD>); ?>", db_prefix: "<?php echo htmlspecialchars($db_prefix); ?>", blog_id: "<?php echo htmlspecialchars($blog_id); ?>", postindex: <?php echo $postindex; ?>, commentindex: 0 } ); </script> <?php } /** * The plugin sink for the auth_ajax_mt_import_comments hook. * Responds via authenticated ajax to requests for comment importing. * * @access public * @param AjaxHandler $handler The handler that handled the request, contains $_POST info */ public function action_auth_ajax_mt_mysql_import_comments($handler) { $valid_fields = array( 'db_name','db_host','db_user','db_pass','db_prefix', 'blog_id', 'commentindex'); $inputs = Controller::get_handler_vars()->filter_keys($valid_fields)->getArrayCopy(); extract($inputs); $mtdb = $this->mt_connect( $db_host, $db_name, $db_user, $db_pass, $db_prefix ); if(!$mtdb) { EventLog::log(sprintf(_t('Failed to import from "%s"'), $db_name), 'crit'); echo '<p>'._t( 'Failed to connect using the given database connection details.' ).'</p>'; return; } $commentcount = $mtdb->get_value("SELECT count(comment_id) FROM {$db_prefix}comment WHERE comment_blog_id = '{$blog_id}';"); $min = $commentindex * $this->import_batch + 1; $max = min(($commentindex + 1) * $this->import_batch, $commentcount); echo sprintf(_t('<p>Importing comments %d-%d of %d.</p>'), $min, $max, $commentcount); $post_info = DB::get_results("SELECT post_id, value FROM " . DB::table('postinfo') . " WHERE name= 'mt_id';"); @reset($post_info); while (list(, $info) = @each($post_info)) { $post_map[$info->value]= $info->post_id; } $comments = $mtdb->get_results("SELECT comment_author AS name, comment_email AS email, comment_url AS url, INET_ATON(comment_ip) AS ip, comment_text AS content, comment_created_on AS date, comment_visible AS status, comment_entry_id AS mt_post_id, comment_id, comment_junk_status FROM {$db_prefix}comment WHERE comment_blog_id = '{$blog_id}' LIMIT {$min}," . $this->import_batch, array(), 'Comment'); $comment_map = DB::get_column("SELECT value FROM " . DB::table('commentinfo') . " WHERE name='mt_comment_id';"); @reset($comments); while (list(, $comment) = @each($comments)) { // already exists skipped if(in_array($comment->comment_id, $comment_map)) continue; $comment->type = Comment::COMMENT; $carray = $comment->to_array(); if ($carray['ip'] == '') { $carray['ip'] = 0; } if ($carray['status'] == 1) { $carray['status'] = Comment::STATUS_APPROVED; } elseif ($carray['comment_junk_status'] != 0) { $carray['status'] = Comment::STATUS_SPAM; } else { $carray['status'] = Comment::STATUS_UNAPPROVED; } unset($carray['comment_junk_status']); if (!isset($post_map[$carray['mt_post_id']] ) ) { Utils::debug( $carray ); } else { $carray['post_id']= $post_map[$carray['mt_post_id']]; unset( $carray['mt_post_id'] ); $comment_id = $carray['comment_id']; unset($carray['comment_id']); $c = new Comment( $carray ); $c->info->mt_comment_id = $comment_id; try{ $c->insert(); } catch( Exception $e ) { EventLog::log($e->getMessage(), 'err', null, null, print_r(array($c, $e), 1)); $errors = Options::get('import_errors'); $errors[] = $e->getMessage(); Options::set('import_errors', $errors); } } } if( $max < $commentcount ) { $ajax_url = URL::get('auth_ajax', array( 'context' => 'mt_mysql_import_comments')); $commentindex++; } else { $ajax_url = URL::get('auth_ajax', array('context' => 'mt_mysql_import_trackbacks')); } ?> <script type="text/javascript"> $( '#import_progress' ).load( "<?php echo $ajax_url; ?>", { db_host: "<?php echo htmlspecialchars($db_host); ?>", db_name: "<?php echo htmlspecialchars($db_name); ?>", db_user: "<?php echo htmlspecialchars($db_user); ?>", db_pass: "<?php echo htmlspecialchars($db_pass); ?>", db_prefix: "<?php echo htmlspecialchars($db_prefix); ?>", blog_id: "<?php echo htmlspecialchars($blog_id); ?>", commentindex: <?php echo $commentindex; ?>, trackbackindex: 0 } ); </script> <?php } /** * The plugin sink for the auth_ajax_mt_import_trackbacks hook. * Responds via authenticated ajax to requests for comment importing. * * @access public * @param AjaxHandler $handler The handler that handled the request, contains $_POST info */ public function action_auth_ajax_mt_mysql_import_trackbacks($handler) { $valid_fields = array( 'db_name','db_host','db_user','db_pass','db_prefix', 'blog_id', 'trackbackindex'); $inputs = Controller::get_handler_vars()->filter_keys($valid_fields)->getArrayCopy(); extract($inputs); $mtdb = $this->mt_connect($db_host, $db_name, $db_user, $db_pass, $db_prefix); if(!$mtdb) { EventLog::log(sprintf(_t('Failed to import from "%s"'), $db_name), 'crit'); echo '<p>'._t( 'Failed to connect using the given database connection details.' ).'</p>'; return; } $trackbackcount = $mtdb->get_value("SELECT count(trackback_id) FROM {$db_prefix}trackback WHERE trackback_blog_id = '{$blog_id}';"); $min = $trackbackindex * $this->import_batch + 1; $max = min( ( $trackbackindex + 1 ) * $this->import_batch, $trackbackcount ); echo sprintf(_t('<p>Importing trackbacks %d-%d of %d.</p>'), $min, $max, $trackbackcount); $post_info = DB::get_results("SELECT post_id, value FROM " . DB::table('postinfo') . " WHERE name= 'mt_id';"); @reset($post_info); while (list(, $info) = @each($post_info)) { $post_map[$info->value]= $info->post_id; } $trackbacks = $mtdb->get_results("SELECT trackback_title AS name, trackback_url AS url, trackback_description AS content, trackback_created_on AS date, trackback_entry_id AS mt_post_id, trackback_id, trackback_is_disabled FROM {$db_prefix}trackback WHERE trackback_blog_id = '{$blog_id}' LIMIT {$min}," . $this->import_batch, array(), 'Comment'); $comment_map = DB::get_column("SELECT value FROM " . DB::table('commentinfo') . " WHERE name='mt_trackback_id';"); @reset($trackbacks); while (list(, $trackback) = @each($trackback)) { // already exists skipped if(in_array($trackback->trackback_id, $comment_map)) continue; $trackback->type = Comment::TRACKBACK; $carray = $trackback->to_array(); $carray['ip']= 0; if ($carray['trackback_is_disabled'] == 0) { $carray['status']= Comment::STATUS_APPROVED; } else { $carray['status']= Comment::STATUS_UNAPPROVED; } unset($carray['trackback_is_disabled']); if (!isset($post_map[$carray['mt_post_id']] ) ) { Utils::debug( $carray ); } else { $carray['post_id']= $post_map[$carray['wp_post_id']]; unset( $carray['mt_post_id'] ); $trackback_id = $carray['trackback_id']; unset($carray['trackback_id']); $c = new Comment( $carray ); $c->info->mt_trackback_id = $trackback_id; try{ $c->insert(); } catch( Exception $e ) { EventLog::log($e->getMessage(), 'err', null, null, print_r(array($c, $e), 1)); $errors = Options::get('import_errors'); $errors[] = $e->getMessage(); Options::set('import_errors', $errors); } } } if($max < $trackbackcount) { $ajax_url = URL::get('auth_ajax', array( 'context' => 'mt_mysql_import_trackbacks')); $trackbackindex++; } else { EventLog::log('Import complete from "'. $db_name .'"'); echo '<p>' . _t( 'Import is complete.' ) . '</p>'; $errors = Options::get('import_errors'); if(count($errors) > 0 ) { echo '<p>' . _t('There were errors during import:') . '</p>'; echo '<ul>'; foreach($errors as $error) { echo '<li>' . $error . '</li>'; } echo '</ul>'; } return; } ?> <script type="text/javascript"> $( '#import_progress' ).load( "<?php echo $ajax_url; ?>", { db_host: "<?php echo htmlspecialchars($db_host); ?>", db_name: "<?php echo htmlspecialchars($db_name); ?>", db_user: "<?php echo htmlspecialchars($db_user); ?>", db_pass: "<?php echo htmlspecialchars($db_pass); ?>", db_prefix: "<?php echo htmlspecialchars($db_prefix); ?>", blog_id: "<?php echo htmlspecialchars($blog_id); ?>", trackbackindex: <?php echo $trackbackindex; ?> } ); </script> <?php } /** * first stage of Movable Type Export File import process * * @access private * @return string The UI for the first stage of the import process */ private function file_stage_1($inputs) { $default_values = array( 'warning' => '' ); $inputs = array_merge( $default_values, $inputs ); extract( $inputs ); ob_start(); ?> <p><?php echo _t('Habari will attempt to import from a Movable Type Export File.', 'mtimport'); ?></p> <?php if (!empty($warning)): ?> <p class="warning"><?php echo htmlspecialchars($warning); ?></p> <?php endif; ?> <table> <tr><td><?php echo _t('MT Export File', 'mtimport'); ?></td><td><input type="file" name="file" /></td></tr> </table> <input type="hidden" name="stage" value="2"> <p class="submit"><input type="submit" name="import" value="<?php echo _t('Next', 'mtimport'); ?>" /></p> <?php $output = ob_get_contents(); ob_end_clean(); return $output; } /** * second stage of Movable Type Export File import process * * @access private * @return string The UI for the first stage of the import process */ private function file_stage_2($inputs) { $default_values = array( 'warning' => '' ); $inputs = array_merge($default_values, $inputs); extract($inputs); if (empty($_FILES['file'])) { $inputs['warning'] = _t('Please specify Movable Type Export File.', 'mtimport'); return $this->stage_1($inputs); } switch ($_FILES['file']['error']) { case UPLOAD_ERR_OK: break; default: $inputs['warning'] = _t('Upload failed.', 'mtimport'); return $this->stage_1($inputs); } $mt_file = tempnam(null, 'habari_'); if (!move_uploaded_file($_FILES['file']['tmp_name'], $mt_file)) { $inputs['warning'] = _t('Possible file upload attack!', 'mtimport'); return $this->stage_1($inputs); } $_SESSION['mtimport_mt_file'] = $mt_file; $ajax_url = URL::get('auth_ajax', array('context' => 'mt_file_import_all')); EventLog::log(sprintf(_t('Starting import from "%s"'), 'mtfile')); Options::set('import_errors', array()); ob_start(); ?> <p>Import In Progress</p> <div id="import_progress">Starting Import...</div> <script type="text/javascript"> // A lot of ajax stuff goes here. $(document).ready(function(){ $('#import_progress').load( "<?php echo $ajax_url; ?>", { postindex: 0 } ); }); </script> <?php $output = ob_get_contents(); ob_end_clean(); return $output; } /** * action: auth_ajax_mt_file_import_all * * @access public * @param array $handler */ public function action_auth_ajax_mt_file_import_all($handler) { $text = file_get_contents($_SESSION['mtimport_mt_file']); try { $parser = new MTFileParser($text); } catch (Exception $e) { echo '<p>' . _t('Failed parsing File: ') . $e->getMessage() . '</p>'; return; } $posts = $parser->getResult(); @reset($posts); while (list(, $mt_post) = @each($posts)) { // Post $t_post = array(); $tags = array(); if (isset($mt_post['_META']['BASENAME'])) { $t_post['slug'] = $mt_post['_META']['BASENAME']; } $t_post['content_type'] = Post::type('entry'); $t_post['title'] = strip_tags(htmlspecialchars_decode(MultiByte::convert_encoding($mt_post['_META']['TITLE']))); if (isset($mt_post['EXTENDED BODY']['_BODY'])) { $t_post['content'] = MultiByte::convert_encoding($mt_post['BODY']['_BODY'] . $mt_post['EXTENDED BODY']['_BODY']); } else { $t_post['content'] = MultiByte::convert_encoding($mt_post['BODY']['_BODY']); } if (!isset($mt_post['_META']['STATUS']) || $mt_post['_META']['STATUS'] == 'Publish') { $t_post['status'] = Post::status('published'); } else { $t_post['status'] = Post::status('draft'); } $t_post['pubdate'] = $t_post['updated'] = HabariDateTime::date_create($mt_post['_META']['DATE']); if (isset($mt_post['_META']['CATEGORY'])) { $tags = array_merge($tags, $mt_post['_META']['CATEGORY']); } if (isset($mt_post['_META']['TAGS'])) { $t_tags = explode(',', $mt_post['_META']['TAGS']); $t_tags = array_map('trim', $t_tags, array('"')); $tags = array_merge($tags, $t_tags); } $post = new Post($t_post); if (isset($mt_post['_META']['ALLOW COMMENTS']) && $mt_post['_META']['ALLOW COMMENTS'] != 1) { $post->info->comments_disabled = 1; } $post->tags = array_unique($tags); $post->user_id = User::identify()->id; // TODO: import MT author try { $post->insert(); } catch (Exception $e) { EventLog::log($e->getMessage(), 'err', null, null, print_r(array($p, $e), 1)); Session::error($e->getMessage()); $errors = Options::get('import_errors'); $errors[] = $p->title . ' : ' . $e->getMessage(); Options::set('import_errors', $errors); } // Comments if (isset($mt_post['COMMENT'])) { @reset($mt_post['COMMENT']); while (list(, $mt_comment) = @each($mt_post['COMMENT'])) { $t_comment = array(); $t_comment['post_id'] = $post->id; $t_comment['name'] = MultiByte::convert_encoding($mt_comment['AUTHOR']); if (isset($mt_comment['EMAIL'])) { $t_comment['email'] = $mt_comment['EMAIL']; } if (isset($mt_comment['URL'])) { $t_comment['url'] = strip_tags($mt_comment['URL']); } if (isset($mt_comment['IP'])) { $t_comment['ip'] = $mt_comment['IP']; } $t_comment['content'] = MultiByte::convert_encoding($mt_comment['_BODY']); $t_comment['status'] = Comment::STATUS_APPROVED; $t_comment['date'] = HabariDateTime::date_create($mt_comment['DATE']); $t_comment['type'] = Comment::COMMENT; $comment = new Comment($t_comment); try { $comment->insert(); } catch (Exception $e) { EventLog::log($e->getMessage(), 'err', null, null, print_r(array($c, $e), 1)); Session::error($e->getMessage()); $errors = Options::get('import_errors'); $errors[] = $e->getMessage(); Options::set('import_errors', $errors); } } } // Trackbacks if (isset($mt_post['PING'])) { @reset($mt_post['PING']); while (list(, $mt_comment) = @each($mt_post['PING'])) { $t_comment = array(); $t_comment['post_id'] = $post->id; $t_comment['name'] = MultiByte::convert_encoding($mt_comment['BLOG NAME'] . ' - ' . $mt_comment['TITLE']); if (isset($mt_comment['EMAIL'])) { $t_comment['email'] = $mt_comment['EMAIL']; } if (isset($mt_comment['URL'])) { $t_comment['url'] = strip_tags($mt_comment['URL']); } if (isset($mt_comment['IP'])) { $t_comment['ip'] = $mt_comment['IP']; } $t_comment['content'] = MultiByte::convert_encoding($mt_comment['_BODY']); $t_comment['status'] = Comment::STATUS_APPROVED; $t_comment['date'] = HabariDateTime::date_create($mt_comment['DATE']); $t_comment['type'] = Comment::TRACKBACK; $comment = new Comment($t_comment); try { $comment->insert(); } catch (Exception $e) { EventLog::log($e->getMessage(), 'err', null, null, print_r(array($c, $e), 1)); Session::error($e->getMessage()); $errors = Options::get('import_errors'); $errors[] = $e->getMessage(); Options::set('import_errors', $errors); } } } } EventLog::log(_t('Import complete from MT Export File', 'mtimport')); echo '<p>' . _t('Import is complete.') . '</p>'; $errors = Options::get('import_errors'); if(count($errors) > 0 ) { echo '<p>' . _t('There were errors during import:') . '</p>'; echo '<ul>'; foreach ($errors as $error) { echo '<li>' . $error . '</li>'; } echo '</ul>'; } } /** * Attempt to connect to the Movable Type database * * @access private * @param string $db_host The hostname of the MT database * @param string $db_name The name of the MT database * @param string $db_user The user of the MT database * @param string $db_pass The user's password for the MT database * @param string $db_prefix The table prefix for the MT instance in the database * @return mixed false on failure, DatabseConnection on success */ private function mt_connect( $db_host, $db_name, $db_user, $db_pass, $db_prefix ) { // Connect to the database or return false try { $mtdb = new DatabaseConnection(); $mtdb->connect( "mysql:host={$db_host};dbname={$db_name}", $db_user, $db_pass, $db_prefix ); return $mtdb; } catch( Exception $e ) { return false; } } } ?><file_sep><?php include( HABARI_PATH . '/system/admin/header.php'); ?> <div class="container navigator"> <span class="older pct10"><a href="#">&laquo; Older</a></span> <span class="currentposition pct15 minor">0-0 of 0</span> <span class="search pct50"><input type="search" placeholder="Type and wait to search for any entry component" autosave="habaricontent" results="10"></span> <span class="nothing pct15">&nbsp;</span> <span class="newer pct10"><a href="#">Newer &raquo;</a></span> </div> <form method="post" name="moderation" action="<?php URL::out( 'admin', array( 'page' => 'spam' ) ); ?>"> <input type="hidden" name="search" value="<?php echo $search; ?>"> <input type="hidden" name="limit" value="<?php echo $limit; ?>"> <input type="hidden" name="index" value="<?php echo isset($index)?$index:''; ?>"> <input type="hidden" name="status" value="<?php echo $status; ?>"> <input type="hidden" name="nonce" value="<?php echo $wsse['nonce']; ?>"> <input type="hidden" name="timestamp" value="<?php echo $wsse['timestamp']; ?>"> <input type="hidden" name="PasswordDigest" value="<?php echo $wsse['digest']; ?>"> <div class="container transparent"> <div class="item controls"> <span class="checkboxandselected pct25"> <input type="checkbox"></input> <span class="selectedtext minor none">None selected</span> </span> <span class="buttons"> <input type="submit" name="do_delete" value="Delete" class="deletebutton"></input> <input type="submit" name="do_unapprove" value="Unapprove" class="spambutton"></input> <input type="submit" name="do_approve" value="Approve" class="approvebutton"></input> </span> </div> </div> <div id="comments" class="container manage"> <?php usort($comments, array('Defensio', 'sort_by_spaminess')); foreach( $comments as $comment ) : ?> <div class="item clear" style="<?php echo Defensio::get_spaminess_style($comment); ?>" id="comment_<?php echo $comment->id; ?>"> <div class="head clear"> <span class="checkbox title pct25"> <input type="checkbox" class="checkbox" name="comment_ids[<?php echo $comment->id; ?>]" id="comments_ids[<?php echo $comment->id; ?>]" value="1"></input> <?php if($comment->url != ''): ?> <a href="#" class="author"><?php echo $comment->name; ?></a> <?php else: ?> <?php echo $comment->name; ?> <?php endif; ?> </span> <span class="entry pct30"><a href="<?php echo $comment->post->permalink ?>#comment-<?php echo $comment->id; ?>"><?php echo $comment->post->title; ?></a></span> <span class="time pct10"><a href="#"><span class="dim">at</span> <?php echo date('H:i', strtotime($comment->date));?></a></span> <span class="date pct15"><a href="#"><span class="dim">on</span> <?php echo date('M d, Y', strtotime($comment->date));?></a></span> <ul class="dropbutton"> <li><a href="#" onclick="itemManage.update( 'delete', <?php echo $comment->id; ?> );return false;">Delete</a></li> <li><a href="#" onclick="itemManage.update( 'spam', <?php echo $comment->id; ?> );return false;">Spam</a></li> <li><a href="#" onclick="itemManage.update( 'approve', <?php echo $comment->id; ?> );return false;">Approve</a></li> <li><a href="#" onclick="itemManage.update( 'unapprove', <?php echo $comment->id; ?> );return false;">Unapprove</a></li> <li><a href="#">Edit</a></li> </ul> </div> <div class="infoandcontent clear"> <ul class="spamcheckinfo pct25 minor"> <?php $reasons = (array)$comment->info->spamcheck; $reasons = array_unique($reasons); foreach($reasons as $reason): ?> <li><?php echo $reason; ?></li> <?php endforeach; ?> </ul> <span class="content pct50"><?php echo Utils::truncate( strip_tags( $comment->content ), 120 ); ?></span> <span class="authorinfo pct25 minor"> <?php if ($comment->url != '') echo '<a href="' . $comment->url . '">' . Utils::truncate( $comment->url, 30 ) . '</a>'."\r\n"; ?> <?php if ( $comment->email != '' ) echo '<a href="mailto:' . $comment->email . '">' . Utils::truncate( $comment->email, 30 ) . '</a>'."\r\n"; ?> </span> </div> </div> <?php endforeach; ?> </div> <div class="container transparent"> <div class="item controls"> <span class="checkboxandselected pct25"> <input type="checkbox"></input> <span class="selectedtext minor none">None selected</span> </span> <span class="buttons"> <input type="submit" name="do_delete" value="Delete" class="deletebutton"></input> <input type="submit" name="do_unapprove" value="Unapprove" class="spambutton"></input> <input type="submit" name="do_approve" value="Approve" class="approvebutton"></input> </span> </div> </div> </form> <script type="text/javascript"> timelineHandle.loupeUpdate = function() { spinner.start(); $.ajax({ type: "POST", url: "<?php echo URL::get('admin_ajax', array('context' => 'comments')); ?>", data: "limit=60" + <?php $vars = Controller::get_handler_vars(); $out = ''; $keys = array_keys($vars); foreach($keys as $key) { $out .= "&$key=$vars[$key]"; } echo '"' . $out . '"'; ?>, dataType: 'json', success: function(json){ $('#comments').html(json.items); spinner.stop(); itemManage.initItems(); findChildren(); } }); }; itemManage.update = function( action, id ) { if ( id ) { itemManage.selected['p' + id] = 1; } itemManage.initItems(); selector = 'form .' + action + 'button:first'; $(selector).click(); } </script> <?php include( HABARI_PATH . '/system/admin/footer.php'); ?> <file_sep><hr class="hide" /> <div id="ancillary"> <div class="inside"> <div class="first block"> <?php if ( count($previous_posts) > 0 ): ?> <h3>Previously</h3> <ul class="dates"> <?php foreach ( $previous_posts as $post ) { $date = Format::nice_date($post->pubdate, 'm.d'); echo "<li><a href=\"{$post->permalink}\"><span class=\"date\">{$date}</span>{$post->title}</a></li>"; } ?> </ul> <?php endif; ?> </div> <?php if ( $show_interests ): ?> <div class="block" id="interests"> <!-- Will eventually be powered by the delicious plugin --> <h3>Interests</h3> <script type="text/javascript" src="http://del.icio.us/feeds/js/tags/<?php echo $delicious ?>?sort=freq;count=26;size=12-20;color=808080-ff91bc;"> </script> </div> <?php endif; ?> <?php if ( $show_other_news ): ?> <div class="block"> <!-- Will eventually be powered by the lifestream plugin --> <h3>In Other News</h3> <ul class="counts"> <script type="text/javascript" src="http://del.icio.us/feeds/js/<?php echo $delicious ?>?extended;count=1"></script> </div> <?php endif; ?> <div class="clear"></div> </div> </div> <!-- /#ancillary --> <file_sep><?php /** * Create a block with arbitrary content. * */ class SimpleBlock extends Plugin { /** * Register the template. **/ function action_init() { $this->add_template( 'block.simpleblock', dirname(__FILE__) . '/block.simpleblock.php' ); } /** * Add to the list of possible block types. **/ public function filter_block_list($block_list) { $block_list['simpleblock'] = _t('Simple Block'); return $block_list; } /** * Output the content of the block, and nothing else. **/ public function action_block_content_simpleblock($block, $theme) { return $block; } /** * Configuration form with one big textarea. Raw to allow JS/HTML/etc. Insert them at your own peril. **/ public function action_block_form_simpleblock($form, $block) { $content = $form->append('textarea', 'content', $block, _t( 'Content:' ) ); $content->raw = true; $content->rows = 5; $form->append('submit', 'save', 'Save'); } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Simple Block', '50a5f6c5-8343-43ee-b9dd-aa783a7f07b8', $this->info->version ); } } ?> <file_sep><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title> <?php Options::out( 'tagline' ); ?> </title> <meta http-equiv="Content-Type" content="text/html"> <meta name="generator" content="Habari"> <link rel="alternate" type="application/atom+xml" title="Atom" href="http://www.chrisjdavis.org/atom/1"> <link rel="edit" type="application/atom+xml" title="Atom Publishing Protocol" href="<?php URL::out( 'atompub_servicedocument' ); ?>"> <link rel="EditURI" type="application/rsd+xml" title="RSD" href="<?php URL::out( 'rsd' ); ?>"> <link rel="stylesheet" type="text/css" media="screen" href="<?php Site::out_url( 'theme' ); ?>/style.css"> <?php $theme->header(); ?> <?php Stack::out('template_header_javascript', '<script type="text/javascript" src="%s"></script>'); ?> </head> <body> <div class="container"> <div class="header column span-13"> <ul class="navigation"> <li class="first-item"><a href="/" title="Go Home">Home</a></li> </ul> </div> <div class="searchfield"> <?php Plugins::act( 'theme_searchform_before' ); ?> <form method="get" id="searchform" action="<?php URL::out('display_search'); ?>"> <input type="text" id="s" name="criteria" class="search" value="search this site"> </form> <?php Plugins::act( 'theme_searchform_after' ); ?> </div> <file_sep><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title> <?php if($request->display_entry && isset($post)) { echo "{$post->title} | "; } elseif ($request->display_entries_by_tag) { echo "Tag Archives for '".str_replace("-","&nbsp;","$tag")."' | "; } elseif ($request->display_search) { echo "Search for '".$_GET['criteria']."' | "; } elseif ($request->display_entries_by_date) { echo "Archives for ".$theme->monthname($month)." $year | "; } Options::out( 'title' ); if($request->display_home) { echo " | "; Options::out( 'tagline' ); } ?> </title> <meta http-equiv="Content-Type" content="text/html"> <meta name="generator" content="Habari"> <link rel="alternate" type="application/atom+xml" title="Atom 1.0" href="<?php $theme->feed_alternate(); ?>"> <link rel="edit" type="application/atom+xml" title="Atom Publishing Protocol" href="<?php URL::out( 'atompub_servicedocument' ); ?>"> <link rel="EditURI" type="application/rsd+xml" title="RSD" href="<?php URL::out( 'rsd' ); ?>"> <link rel="stylesheet" type="text/css" media="screen" href="<?php Site::out_url( 'theme' ); ?>/style.css"> <!--[if IE]> <link rel="stylesheet" type="text/css" media="screen" href="<?php Site::out_url( 'theme' ); ?>/style-ie.css"> <![endif]--> <?php $theme->header(); ?> </head> <body id="home"> <div id="wrap"> <div id="header"> <h1><a href="<?php Site::out_url( 'habari' ); ?>"><?php Options::out( 'title' ); ?></a></h1> <p id="tagline"><?php Options::out( 'tagline' ); ?></p> <ul id="nav"> <li><a href="<?php Site::out_url( 'habari' ); ?>" title="<?php Options::out( 'title' ); ?>" <?php if($request->display_home) { ?> class="selected" <?php } ?>>Home</a></li> <?php foreach ($pages as $tab) { ?> <li><a href="<?php Site::out_url( 'habari' ); ?>/<?php echo $tab->slug; ?>" title="<?php echo $tab->title; ?>" <?php if($request->display_404 || $request->display_search) { } elseif($tab->slug == $post->slug) { ?> class="selected" <?php } ?>><?php echo $tab->title; ?></a></li> <?php } ?> <li id="rss"><a href="/atom/1">Atom</a></li> <li class="clear"></li> </ul> </div> <div id="content"> <!-- /header --> <file_sep><div class="block"> <?php if($block->_show_title): ?> <h3><?php echo $block->title; ?></h3> <?php endif; ?> <div class="block_content""> <?php echo $content; ?> </div> </div> <file_sep><?php $theme->display( 'header'); ?> <div id="page_content"> <?php echo $post->content_out; ?> </div> <div id="footer"><p>This site is powered by <a href="http://habariproject.org/en/" title="Habari Project">Habari</a></p></div> </div> </div> </body> </html><file_sep><?php /** * DiggBar Blocker Plugin * * Inspired by http://daringfireball.net/2009/04/how_to_block_the_diggbar **/ class DiggbarBlocker extends Plugin { /** * Add actions to the plugin page for this plugin * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id **/ public function filter_plugin_config( $actions ) { $actions['configure'] = _t( 'Configure' ); return $actions; } /** * Respond to the user selecting an action on the plugin page * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook **/ public function action_plugin_ui_configure() { $ui = new FormUI( strtolower( get_class( $this ) ) ); $reload_fieldset = $ui->append( 'fieldset', 'reload', _t( 'No Message' ) ); $reload_page = $reload_fieldset->append( 'checkbox', 'reload', 'option:diggbarblocker__reload', _t( 'Instead of displaying a message, reload the page without the bar' ) ); $message_fieldset = $ui->append( 'fieldset', 'message_settings', _t( 'Message Settings' ) ); $message = $message_fieldset->append( 'textarea', 'message', 'option:diggbarblocker__message', _t( 'If the box above is not checked, display this to Diggbar-using visitors:' ) ); $message->rows = 2; $message->class[] = 'resizable'; $link = $message_fieldset->append( 'checkbox', 'addlink', 'option:diggbarblocker__addlink', _t( 'Add a link to the target page.' ) ); $ui->append( 'submit', 'save', _t( 'Save' ) ); $ui->out(); } /** * Set default text & link behavior **/ public function action_plugin_activation( $file ) { if ( Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__) ) { if ( Options::get( 'diggbarblocker__message' ) == null ) { Options::set( 'diggbarblocker__message', _t( 'This site does not support use of the DiggBar.' ) ); } if ( Options::get( 'diggbarblocker__add_link' ) == null ) { Options::set( 'diggbarblocker__addlink', 1 ); } } } /** * Return either a message for the Diggbar user, or just reload the page. * @return string buffer of either the message displayed, or reload headers. **/ public function filter_final_output( $buffer ) { if ( preg_match( '#http://digg.com/\w{1,8}/*(\?.*)?$#', $_SERVER[ 'HTTP_REFERER' ]) ) { if ( Options::get( 'diggbarblocker__reload' ) ) { $buffer = '<SCRIPT TYPE="text/JavaScript"> if (window != top) { top.location.replace( self.location.href ); } </SCRIPT>'; } else { $buffer = '<p>' . Options::get( 'diggbarblocker__message' ) .'</p>' . ( Options::get( 'diggbarblocker__addlink' ) ? _t( '<p>Open <a title="Open in a new window" target="_top" href="') . $_SERVER[ 'SCRIPT_URI' ] . '">' . $_SERVER[ 'SCRIPT_URI' ] . _t('</a> in a new tab or window to view it.</p>') : ''); } } return $buffer; } } ?> <file_sep><?php class FlickrFill extends Plugin { private $flickr= null; private $person_id= null; private $photo= null; private $size= 't'; private $number= '5'; public function setup() { $this->person_id= Options::get( 'flickrfill__person' ); $this->size= Options::get ( 'flickrfill__size' ); $this->number= Options::get ( 'flickrfill__number' ); } /** * function info * Returns information about this plugin * @return array Plugin info array **/ function info() { return array( 'name' => 'FlickrFill', 'url' => 'http://642Design.com/', 'author' => '<NAME>', 'authorurl' => 'http://morydd.net/', 'version' => '0.2', 'license' => 'Apache License 2.0', 'description' => 'Displays flickr images before each post based on date' ); } public function help() { return <<< END_HELP <p>Add this code to your theme where you would like your photos displayed. This must be inside the post loop.</p> <code>&lt;?php \$theme-&gt;flickrfill(\$post,\$posts); ?&gt;</code> <p>CSS Classes</p> <ul><li>flickrfill: container div for images</li> <li>flickrfillimg: class assigned to each img</li></ul> <p>You can use <a href="http://idgettr.com/">idgetter.com</a> to find your Flickr User ID Number.</p> END_HELP; } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t('Configure'); $actions[]= _t('Refresh'); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure') : $ui = new FormUI( strtolower( get_class( $this ) ) ); $person= $ui->append( 'text', 'person', 'flickrfill__person', _t('Flickr ID Number: ' ) ); // $ui->on_success( array( $this, 'updated_config' ) ); $number= $ui->append ('text', 'number', 'flickrfill__number', _t('Number of Pictures to Display: ' ) ); $size= $ui->append( 'select', 'size', 'flickrfill__size', _t('Size of Images to Display' ) ); /** TODO Make this tranlateable **/ $size->options= array( '_s' => 'Square (75px Each Side)', '_t' => 'Thumbnail (Longest Side 100px)', '_m' => 'Small (Longest Side 240px )', '' => 'Medium (Longest Side 500px)' ); $ui->append( 'submit', 'save', _t('Save') ); $ui->out(); break; case _t('Refresh') : $this->theme_flickrfill(); Utils::redirect( URL::get('admin', 'page=plugins') ); break; } } } public function updated_config( $ui ) { return true; } function action_init() { $this->add_template( 'flickrfill', dirname(__FILE__) . '/flickrfill.php' ); } public function theme_flickrfill_bydate( $theme, $post1date, $post2date ) { $this->person_id= Options::get( 'flickrfill__person' ); $this->size= Options::get ( 'flickrfill__size' ); $this->number= Options::get ( 'flickrfill__number' ); $feed_url = 'http://api.flickr.com/services/rest/?method=flickr.photos.search&format=rest&api_key=<KEY>&user_id=' . $this->person_id . '&min_taken_date=' . $post2date . '&max_taken_date=' . $post1date . '&sort=interestingness-desc&media=photos&per_page=' . $this->number; if(Cache::has($feed_url)) { $response = Cache::get($feed_url); } if(!Cache::has($feed_url) || Cache::expired($feed_url)) { // Cache::expired() is a 0.7 feature. $request = new RemoteRequest( $feed_url ); $request->set_timeout( 5 ); $result= $request->execute(); if ( Error::is_error( $result ) ) { EventLog::log( 'Error getting photo from Flickr', 'err', 'default', 'habari' ); } else { $response= $request->get_response_body(); } } $output = ''; $xml= new SimpleXMLElement( $response ); if ( ! $xml ) { return 'no xml'; } $output .= '<div class="flickrfill">'; foreach ( $xml->photos->photo as $photo ) { if ( ! $photo ) { return; } if ( ! $photo['id'] ) { return; } $output .= '<a href="http://www.flickr.com/photos/' . $this->person_id . '/' . $photo['id'] . '"><img class="flickrfeedimg" src="http://farm' . $photo['farm'] . '.static.flickr.com/' . $photo['server'] . '/' . $photo['id'] . '_' . $photo['secret'] . $this->size . '.jpg"></a>'; } $output .= '</div>'; return $output; } public function theme_flickrfill( $theme, $post, $posts ) { $prevpost = $posts->ascend($post); if (empty($prevpost)) { $post1date = date('Y-m-d'); } else { $post1date = $prevpost->pubdate->format('Y-m-d'); } $post2date = $post->pubdate->format('Y-m-d'); return $this->theme_flickrfill_bydate( $theme, $post1date, $post2date ); } /** * Enable update notices to be sent using the Habari beacon **/ public function action_update_check() { Update::add( 'FlickrFill', '98347b74-6a00-4601-bd7b-76e5476e193f', $this->info->version ); } } ?><file_sep><?php /** * Twitter Plugin * * Lets you show your current Twitter status in your theme, as well * as an option automatically post your new posts to Twitter. * * Usage: <?php $theme->twitter(); ?> to show your latest tweet in a theme. * A sample tweets.php template is included with the plugin.This can be copied to your * active theme and modified. * **/ class Twitter extends Plugin { const DEFAULT_CACHE_EXPIRE = 60; // seconds const CONSUMER_KEY = 'vk8lo1Zqut4g0q1VA1r0BQ'; const CONSUMER_SECRET = '<KEY>'; /** * Sets the new 'hide_replies' option to '0' to mimic current, non-reply-hiding * functionality, and 'twitter__limit' to '1', again to match earlier results. **/ public function action_plugin_activation( $file ) { if( Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__) ) { if ( Options::get( 'twitter__hide_replies' ) == null ) { Options::set( 'twitter__hide_replies', 0 ); } if ( ( Options::get( 'twitter__linkify_urls' ) == null ) or ( Options::get( 'twitter__linkify_urls' ) > 1 ) ) { Options::set( 'twitter__linkify_urls', 0 ); } if ( Options::get( 'twitter__hashtags_query' ) == null ) { Options::set( 'twitter__hashtags_query', 'http://hashtags.org/search?query=' ); } if ( !Options::get( 'twitter__limit' ) ) { Options::set( 'twitter__limit', 1 ); } } } /** * Add the Configure, Authorize and De-Authorize options for the plugin * * @access public * @param array $actions * @param string $plugin_id * @return array */ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { if ( User::identify()->info->twitter__access_token ) { $actions['configure'] = _t( 'Configure' ); $actions['deauthorize'] = _t( 'De-Authorize' ); } else { $actions['authorize'] = _t( 'Authorize' ); } } return $actions; } public function action_plugin_ui ( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure'): $this->action_plugin_ui_configure(); break; case _t('De-Authorize'): $this->action_plugin_ui_deauthorize(); break; case _t('Authorize'): $this->action_plugin_ui_authorize(); break; // confirm is called by the return request from twitter, it's not ordinarily user-accessible case _t('Confirm'): $this->action_plugin_ui_confirm(); break; } } } /** * Plugin UI - Displays the 'authorize' config option * * @access public * @return void */ public function action_plugin_ui_authorize() { require_once dirname( __FILE__ ) . '/lib/twitteroauth/twitteroauth.php'; unset( $_SESSION['TwitterReqToken'] ); // Just being safe. $oauth = new TwitterOAuth(Twitter::CONSUMER_KEY, Twitter::CONSUMER_SECRET ); $oauth_token = $oauth->getRequestToken( URL::get( 'admin', array( 'page' => 'plugins', 'configure' => $this->plugin_id(), 'configaction' => 'confirm' ) ) ); $request_link = $oauth->getAuthorizeURL( $oauth_token ); $reqToken = array( "request_link" => $request_link, "request_token" => $oauth_token['oauth_token'], "request_token_secret" => $oauth_token['oauth_token_secret'] ); $_SESSION['TwitterReqToken'] = serialize( $reqToken ); $ui = new FormUI( strtolower( __CLASS__ ) ); $ui->append( 'static', 'nocontent', '<h3>Authorize the Habari Twitter Plugin</h3> <p>Authorize your blog to have access to your Twitter account.</p> <p>Click the button below, and you will be taken to Twitter.com. If you\'re already logged in, you will be presented with the option to authorize your blog. Press the "Allow" button to do so, and you will come right back here.</p> <br><p style="text-align:center"><a href="'.$reqToken['request_link'].'"><img src="'. URL::get_from_filesystem( __FILE__ ) .'/lib/twitter_connect.png" alt="Sign in with Twitter" /></a></p> '); $ui->out(); } /** * Plugin UI - Displays the 'confirm' config option. * * @access public * @return void */ public function action_plugin_ui_confirm() { require_once dirname( __FILE__ ) . '/lib/twitteroauth/twitteroauth.php'; $user = User::identify(); $ui = new FormUI( strtolower( __CLASS__ ) ); if( !isset( $_SESSION['TwitterReqToken'] ) ){ $auth_url = URL::get( 'admin', array( 'page' => 'plugins', 'configure' => $this->plugin_id(), 'configaction' => 'Authorize' ) ); $ui->append( 'static', 'nocontent', '<p>'._t( 'Either you have already authorized Habari to access your Twitter account, or you have not yet done so. Please ' ).'<strong><a href="' . $auth_url . '">'._t( 'try again' ).'</a></strong>.</p>'); $ui->out(); } else { $reqToken = unserialize( $_SESSION['TwitterReqToken'] ); $oauth = new TwitterOAuth( Twitter::CONSUMER_KEY, Twitter::CONSUMER_SECRET, $reqToken['request_token'], $reqToken['request_token_secret'] ); $token = $oauth->getAccessToken($_GET['oauth_verifier']); $config_url = URL::get( 'admin', array( 'page' => 'plugins', 'configure' => $this->plugin_id(), 'configaction' => 'Configure' ) ); if( ! empty( $token ) && isset( $token['oauth_token'] ) ){ $user->info->twitter__access_token = $token['oauth_token']; $user->info->twitter__access_token_secret = $token['oauth_token_secret']; $user->info->twitter__user_id = $token['user_id']; $user->info->commit(); Session::notice( _t( 'Habari Twitter plugin successfully authorized.', 'twitter' ) ); Utils::redirect( $config_url ); } else{ // TODO: We need to fudge something to report the error in the event something fails. Sadly, the Twitter OAuth class we use doesn't seem to cater for errors very well and returns the Twitter XML response as an array key. // TODO: Also need to gracefully cater for when users click "Deny" echo '<form><p>'._t( 'There was a problem with your authorization.' ).'</p></form>'; } unset( $_SESSION['TwitterReqToken'] ); } } /** * Plugin UI - Displays the 'deauthorize' config option. * * @access public * @return void */ public function action_plugin_ui_deauthorize() { $user = User::identify(); $user->info->twitter__user_id = ''; $user->info->twitter__access_token = ''; $user->info->twitter__access_token_secret = ''; $user->info->commit(); $reauth_url = URL::get( 'admin', array( 'page' => 'plugins', 'configure' => $this->plugin_id(), 'configaction' => 'Authorize' ) ) . '#plugin_options'; //$ui->append( 'static', 'nocontent', '<p>'._t( 'The Twitter Plugin authorization has been deleted. Please ensure you ' ) . '<a href="http://twitter.com/settings/connections" target="_blank">' . _t( 'revoke access ' ).'</a>'._t( 'from your Twitter account too.' ).'<p><p>'._t( 'Do you want to ' ).'<b><a href="'.$reauth_url.'">'._t( 're-authorize this plugin' ).'</a></b>?<p>' ); Session::notice( _t( 'Habari Twitter plugin authorization revoked. <br>Don\'t forget to revoke access on Twitter itself.', 'twitter' ) ); Utils::redirect( $reauth_url ); } /** * Plugin UI - Displays the 'configure' config option. * * @access public * @return void */ public function action_plugin_ui_configure() { $ui = new FormUI( strtolower( __CLASS__ ) ); $post_fieldset = $ui->append( 'fieldset', 'post_settings', _t( 'Autopost Updates from Habari', 'twitter' ) ); $twitter_post = $post_fieldset->append( 'checkbox', 'post_status', 'twitter__post_status', _t( 'Autopost to Twitter:', 'twitter' ) ); $twitter_post = $post_fieldset->append( 'text', 'prepend', 'twitter__prepend', _t( 'Prepend to Autopost:', 'twitter' ) ); $twitter_post->value = "New Blog Post:"; $tweet_fieldset = $ui->append( 'fieldset', 'tweet_settings', _t( 'Displaying Status Updates', 'twitter' ) ); $twitter_limit = $tweet_fieldset->append( 'select', 'limit', 'twitter__limit', _t( 'Number of updates to show', 'twitter' ) ); $twitter_limit->options = array_combine(range(1, 20), range(1, 20)); $twitter_show = $tweet_fieldset->append( 'checkbox', 'hide_replies', 'twitter__hide_replies', _t( 'Do not show @replies', 'twitter' ) ); $twitter_show = $tweet_fieldset->append( 'checkbox', 'linkify_urls', 'twitter__linkify_urls', _t('Linkify URLs') ); $twitter_hashtags = $tweet_fieldset->append( 'text', 'hashtags_query', 'twitter__hashtags_query', _t( '#hashtags query link:', 'twitter' ) ); $twitter_cache_time = $tweet_fieldset->append( 'text', 'cache', 'twitter__cache', _t( 'Cache expiry in seconds:', 'twitter' ) ); $ui->on_success( array( $this, 'updated_config' ) ); $ui->append( 'submit', 'save', _t( 'Save', 'twitter' ) ); $ui->out(); } /** * Give the user a session message to confirm options were saved. **/ public function updated_config( FormUI $ui ) { Session::notice( _t( 'Twitter options saved.', 'twitter' ) ); $ui->save(); } /** * React to the update of a post status to 'published' * @param Post $post The post object with the status change * @param int $oldvalue The old status value * @param int $newvalue The new status value **/ public function action_post_update_status( $post, $oldvalue, $newvalue ) { if ( is_null( $oldvalue ) ) return; if ( $newvalue == Post::status( 'published' ) && $post->content_type == Post::type('entry') && $newvalue != $oldvalue ) { if ( Options::get( 'twitter__post_status' ) == '1' ) { require_once dirname( __FILE__ ) . '/lib/twitteroauth/twitteroauth.php'; $user = User::get_by_id( $post->user_id ); $oauth = new TwitterOAuth( Twitter::CONSUMER_KEY, Twitter::CONSUMER_SECRET, $user->info->twitter__access_token, $user->info->twitter__access_token_secret ); $oauth->post('statuses/update', array('status' => Options::get( 'twitter__prepend' ) . $post->title . ' ' . $post->permalink ) ); Session::notice( 'Post Tweeted' ); } } } public function action_post_insert_after( $post ) { return $this->action_post_update_status( $post, -1, $post->status ); } /** * Add last Twitter status, time, and image to the available template vars * @param Theme $theme The theme that will display the template **/ public function theme_twitter( $theme ) { $twitter = Options::get_group( 'twitter'); $theme->tweets = $this->tweets( $twitter['username'], $twitter['hide_replies'], $twitter['limit'], $twitter['cache'], $twitter['linkify_urls'], $twitter['hashtags_query'] ); return $theme->fetch( 'tweets' ); } /** * Add twitter block to the list of selectable blocks **/ public function filter_block_list( $block_list ) { $block_list[ 'twitter' ] = _t( 'Twitter', 'twitter' ); return $block_list; } /** * Configure the block **/ public function action_block_form_twitter( $form, $block ) { $tweet_fieldset = $form->append( 'fieldset', 'tweet_settings', _t( 'Displaying Status Updates', 'twitter' ) ); $twitter_username = $tweet_fieldset->append( 'text', 'username', $block, _t( 'Twitter Username:', 'twitter' ) ); $twitter_limit = $tweet_fieldset->append( 'select', 'limit', $block, _t( 'Number of updates to show', 'twitter' ) ); $twitter_limit->options = array_combine(range(1, 20), range(1, 20)); $twitter_show = $tweet_fieldset->append( 'checkbox', 'hide_replies', $block, _t( 'Do not show @replies', 'twitter' ) ); $twitter_show = $tweet_fieldset->append( 'checkbox', 'linkify_urls', $block, _t( 'Linkify URLs', 'twitter' ) ); $twitter_hashtags = $tweet_fieldset->append( 'text', 'hashtags_query', $block, _t( '#hashtags query link:', 'twitter' ) ); $twitter_cache_time = $tweet_fieldset->append( 'text', 'cache', $block, _t( 'Cache expiry in seconds:', 'twitter' ) ); $form->append( 'submit', 'save', _t( 'Save', 'twitter' ) ); } /** * Populate the block **/ public function action_block_content_twitter( $block, $theme ) { $block->tweets = $this->tweets( $block->username, $block->hide_replies, $block->limit, $block->cache, $block->linkify_urls, $block->hashtags_query ); } /** * Retrieve tweets * @return array notices The tweets to display in the theme template or block */ public function tweets( $username, $hide_replies = false, $limit = 5, $cache = 60, $linkify_urls = false, $hashtags_query = 'http://hashtags.org/search?query=' ) { $notices = array(); if ( $username != '' ) { $twitter_url = 'http://twitter.com/statuses/user_timeline/' . urlencode( $username ) . '.xml'; // We only need to get a single tweet if we're hiding replies (otherwise we can rely on the maximum returned and hope there's a non-reply) if ( ! $hide_replies && $limit ) { $twitter_url .= '?count=' . $limit; } if ( Cache::has( 'twitter_notices' ) ) { $notices = Cache::get( 'twitter_notices' ); } else { try { $r = new RemoteRequest( $twitter_url ); $r->set_timeout( 10 ); $r->execute(); $response = $r->get_response_body(); $xml = @new SimpleXMLElement( $response ); // Check we've got a load of statuses returned if ( $xml->getName() === 'statuses' ) { foreach ( $xml->status as $status ) { if ( ( ! $hide_replies ) || ( strpos( $status->text, '@' ) === FALSE ) ) { $notice = (object) array ( 'text' => (string) $status->text, 'time' => (string) $status->created_at, 'image_url' => (string) $status->user->profile_image_url, 'id' => (int) $status->id, 'permalink' => 'http://twitter.com/' . $username . '/status/' . (string) $status->id ); $notices[] = $notice; if ( $hide_replies && count( $notices ) >= $limit ) { break; } } else { // it's a @. Keep going. } } if ( ! $notices ) { $notice = (object) array ( 'text' => _t( 'No non-replies replies available from Twitter.', 'twitter' ), 'time' => '', 'image_url' => '' ); } } // You can get error as a root element if Twitter is in maintenance mode. else if ( $xml->getName() === 'error' ) { $notice = (object) array ( 'text' => (string) $xml, 'time' => '', 'image_url' => '' ); } // Um, yeah. We shouldn't ever hit this. else { $notice = (object) array ( 'text' => 'Received unexpected XML from Twitter.', 'time' => '', 'image_url' => '' ); } } catch ( Exception $e ) { EventLog::log( _t( 'Twitter error: %1$s', array( $e->getMessage() ), 'twitter' ), 'err', 'plugin', 'twitter' ); $notice = (object) array ( 'text' => 'Unable to contact Twitter.', 'time' => '', 'image_url' => '' ); } if ( ! $notices ) { $notices[] = $notice; } // Cache (even errors) to avoid hitting rate limit. Cache::set( 'twitter_notices', $notices, ( $cache !== false ? $cache : Twitter::DEFAULT_CACHE_EXPIRE ) ); // , true ); } } else { $notice = (object) array ( 'text' => _t( 'Please set your username in the <a href="%s">Twitter plugin config</a>', array( URL::get( 'admin' , 'page=plugins&configure=' . $this->plugin_id . '&configaction=Configure' ) . '#plugin_' . $this->plugin_id ) , 'twitter' ), 'time' => '', 'image_url' => '' ); $notices[] = $notice; } if ( $linkify_urls != FALSE ) { foreach ( $notices as $notice ) { /* link to all http: */ $notice->text = preg_replace( '%https?://\S+?(?=(?:[.:?"!$&\'()*+,=]|)(?:\s|$))%i', "<a href=\"$0\">$0</a>", $notice->text ); /* link to usernames */ $notice->text = preg_replace( "/(?<!\w)@([\w-_.]{1,64})/", "@<a href=\"http://twitter.com/$1\">$1</a>", $notice->text ); /* link to hashtags */ $notice->text = preg_replace( '/(?<!\w)#((?>\d{1,64}|)[\w-.]{1,64})/', "<a href=\"" . $hashtags_query ."$1\">#$1</a>", $notice->text ); } } return $notices; } /** * On plugin init, add the template included with this plugin to the available templates in the theme */ public function action_init() { $this->add_template( 'tweets', dirname(__FILE__) . '/tweets.php' ); $this->add_template( 'block.twitter', dirname(__FILE__) . '/block.twitter.php' ); } } ?> <file_sep><?php class CustomQuery extends Plugin { const VERSION = '0.2'; public function info() { return array( 'name' => 'Custom Query', 'author' => 'Habari Community', 'description' => 'Allows you to set the number of posts to display for each page.', 'url' => 'http://habariproject.org', 'version' => self::VERSION, 'license' => 'Apache License 2.0' ); } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t('Configure', 'customquery'); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure', 'customquery') : $ui = new FormUI( 'customquery' ); foreach ( RewriteRules::get_active()->getArrayCopy() as $rule ) { if ( strpos( $rule->name, 'display_' ) === 0 and ( $rule->name <> 'display_404' )) { $ui->append( 'text', $rule->name,'customquery__'. $rule->name, 'Number of Posts for ' . $rule->name ); } } $ui->append( 'submit', 'save', _t('Save') ); $ui->out(); break; } } } public function action_update_check() { Update::add( 'Custom Query', '1fe407a0-729e-11dd-ad8b-0800200c9a66', $this->info->version ); } public function filter_template_where_filters( $where_filters ) { if ( Options::get( 'customquery__' . URL::get_matched_rule()->name ) ) { $where_filters['limit']= Options::get( 'customquery__' . URL::get_matched_rule()->name ); } return $where_filters; } } ?> <file_sep><?php require_once "phpunit_bootstrap.php"; require_once dirname(dirname(__FILE__)) . "/classes/pluginsearchinterface.php"; require_once dirname(dirname(__FILE__)) . "/multisearch.plugin.php"; require_once 'PHPUnit/Extensions/OutputTestCase.php'; /** * Tests for the MultiSearch for Habari. * */ class MultiSearchTest extends PHPUnit_Extensions_OutputTestCase { private $_class; public function setUp() { $this->_class = new MultiSearch(); } public function getMockBackend() { return $this->getMock( 'PluginSearchInterface', array( 'open_writable_database', 'open_readable_database', 'index_post', 'delete_post', 'update_post', '__construct', '__destruct', 'check_conditions', 'get_by_criteria', 'get_corrected_query_string', 'get_similar_posts', ) ); } public function getMockTheme() { $themedata = new stdClass(); $themedata->name = 'Mock'; $themedata->version = 1; $themedata->theme_dir = '/'; $themedata->template_engine = 'rawphpengine'; return $this->getMock( 'Theme', array( 'fetch' ), array( $themedata ) ); } /** * @test */ public function getAValidListOfActions() { $actions = array(); $return = $this->_class->filter_plugin_config( $actions, false ); $this->assertSame( $actions, $return ); $return = $this->_class->filter_plugin_config( $actions, $this->_class->plugin_id() ); $this->assertTrue( count($return) > 0 ); } /** * @test */ public function postIsIndexedOnCreate() { $post = new stdClass(); $post->status = Post::status( 'published' ); $backend = $this->getMockBackend(); $backend->expects( $this->once() )->method( 'open_writable_database' ); $backend->expects( $this->once() )->method( 'index_post' )->with( $post ); $this->_class->force_backend( $backend ); $this->_class->action_post_insert_after( $post ); } /** * @test */ public function unpublishedPostIsNotIndexed() { $post = new stdClass(); $post->id = 1; $post->status = Post::status( 'draft' ); $backend = $this->getMockBackend(); $backend->expects( $this->never() )->method( 'open_writable_database' ); $backend->expects( $this->never() )->method( 'index_post' ); $this->_class->force_backend( $backend ); $this->_class->action_post_insert_after( $post ); } /** * @test */ public function updatedPostIsUpdated() { $post = new stdClass(); $post->id = 1; $post->status = Post::status( 'published' ); $backend = $this->getMockBackend(); $backend->expects( $this->once() )->method( 'open_writable_database' ); $backend->expects( $this->once() )->method( 'update_post' )->with( $post ); $this->_class->force_backend( $backend ); $this->_class->action_post_update_after( $post ); } /** * @test */ public function deletedPostIsDeleted() { $post = new stdClass(); $post->id = 1; $backend = $this->getMockBackend(); $backend->expects( $this->once() )->method( 'open_writable_database' ); $backend->expects( $this->once() )->method( 'delete_post' )->with( $post ); $this->_class->force_backend( $backend ); $this->_class->action_post_delete_before( $post ); } /** * @test */ public function unpublishingPostRemovesFromIndex() { $post = new stdClass(); $post->status = Post::status( 'published' ); $post->id = 1; $backend = $this->getMockBackend(); $backend->expects( $this->once() )->method( 'open_writable_database' ); $backend->expects( $this->once() )->method( 'delete_post' )->with( $post ); $backend->expects( $this->never() )->method( 'update_post' ); $this->_class->force_backend( $backend ); $this->_class->action_post_update_before( $post ); $post->status = Post::status( 'draft' ); $this->_class->action_post_update_after( $post ); } /** * @test */ public function paramarrayWithoutCriteriaIsUnmodified() { $paramarray = array('hello' => 'world'); $backend = $this->getMockBackend(); $this->_class->force_backend( $backend ); $return = $this->_class->filter_posts_get_paramarray( $paramarray ); $this->assertSame($return, $paramarray); } /** * @test */ public function paramArrayWithCriteriaIsModified() { $paramarray = array('criteria' => 'search terms', 'limit' => 5, 'page' => 2); $backend = $this->getMockBackend(); $this->_class->force_backend( $backend ); $backend->expects( $this->once() )->method( 'open_readable_database' ); $backend->expects( $this->once() )->method( 'get_by_criteria' ) ->with( $paramarray['criteria'],$paramarray['limit'], 5 ) ->will( $this->returnValue(array(1, 2, 3)) ); $return = $this->_class->filter_posts_get_paramarray( $paramarray ); } /** * @test */ public function themeSpellingReturnsTheSpellingString() { $backend = $this->getMockBackend(); $this->_class->force_backend( $backend ); $correction = 'correction'; $backend->expects( $this->once() )->method( 'get_corrected_query_string' ) ->will( $this->returnValue( $correction ) ); $theme = $this->getMockTheme(); $return = $this->_class->theme_search_spelling( $theme ); $this->assertSame( $theme->spelling, $correction ); } /** * @test */ public function themeSimilarReturnsPostsFromBackend() { $backend = $this->getMockBackend(); $this->_class->force_backend( $backend ); $max = 5; $post = new Post(); $post->id = 1; $backend->expects( $this->once() )->method( 'get_similar_posts' ) ->with( $post, $max); $theme = $this->getMockTheme(); $return = $this->_class->theme_similar_posts( $theme, $post, $max ); } /** * @test */ public function choosingEngineChecksBackend() { $backend = $this->getMockBackend(); $backend->expects( $this->once() )->method( 'check_conditions' )->will( $this->returnValue( true ) ); $ui = $this->getMock('FormUI', array('set_option'), array( 'testform' )); $ui->append( 'hidden','engine', 'noengine', 'test' ); $this->_class->force_backend( $backend ); $this->_class->chosen_engine( $ui ); } /** * @test */ public function configuringEngineChecksBackend() { $backend = $this->getMockBackend(); $backend->expects( $this->once() )->method( 'check_conditions' )->will( $this->returnValue( true ) ); $backend->expects( $this->once() )->method( 'open_writable_database' )->with( PluginSearchInterface::INIT_DB ); $ui = $this->getMock('FormUI', array('set_option'), array( 'testform' )); $ui->append( 'hidden','engine', 'noengine', 'test' ); $engine = Options::get( MultiSearch::ENGINE_OPTION ); Options::set( MultiSearch::ENGINE_OPTION, 'noengine' ); $this->_class->force_backend( $backend ); $this->_class->updated_config( $ui ); Options::set( MultiSearch::ENGINE_OPTION, $engine ); } /** * @test */ public function initShouldCheckBackendConditions() { $backend = $this->getMockBackend(); $backend->expects( $this->once() )->method( 'check_conditions' )->will( $this->returnValue( true ) ); $engine = Options::get( MultiSearch::ENGINE_OPTION ); Options::set( MultiSearch::ENGINE_OPTION, 'noengine' ); $this->_class->force_backend( $backend ); $this->_class->action_init( ); Options::set( MultiSearch::ENGINE_OPTION, $engine ); } /** * @test */ public function configureActionShouldReturnEngineListIfNotOptionSet() { $engine = Options::get( MultiSearch::ENGINE_OPTION ); Options::set( MultiSearch::ENGINE_OPTION, '' ); $this->expectOutputRegex('/xapian/'); $this->_class->action_plugin_ui( $this->_class->plugin_id(), 'Configure' ); Options::set( MultiSearch::ENGINE_OPTION, $engine ); } /** * @test */ public function configureActionShouldReturnConfigureForm() { $engine = Options::get( MultiSearch::ENGINE_OPTION ); Options::set( MultiSearch::ENGINE_OPTION, 'noengine' ); $this->expectOutputRegex('/index_path/'); $this->_class->action_plugin_ui( $this->_class->plugin_id(), 'Configure' ); Options::set( MultiSearch::ENGINE_OPTION, $engine ); } /** * @test */ public function chooseEngineActionShouldReturnEngineList() { $this->_class->action_plugin_ui( $this->_class->plugin_id(), 'Choose Engine' ); $this->expectOutputRegex('/xapian/'); } }<file_sep><?php /** * Maintenance Mode plugin * **/ class Maintenance extends Plugin { const OPTION_NAME = 'maint_mode'; /** * Set options when the plugin is activated */ public function action_plugin_activation( $file ) { if ( realpath( $file ) == __FILE__ ) { Options::set( self::OPTION_NAME . '__text' , _t( "We're down for maintenance. Please return later." ) ); Options::set( self::OPTION_NAME . '__in_maintenance', FALSE ); Options::set( self::OPTION_NAME . '__display_feeds', FALSE ); } } /** * Remove options when the plugin is deactivated */ public function action_plugin_deactivation( $file ) { if ( realpath( $file ) == __FILE__ ) { Options::delete( self::OPTION_NAME . '__text' , _t( "We're down for maintenance. Please return later." ) ); Options::delete( self::OPTION_NAME . '__in_maintenance', FALSE ); Options::delete( self::OPTION_NAME . '__display_feeds', FALSE ); } } /** * Implement the simple plugin configuration. * @return FormUI The configuration form */ public function configure() { $ui = new FormUI( 'maintenance_mode' ); // Add a text control for the maintenance mode text $ui->append( 'textarea', 'mm_text', self::OPTION_NAME . '__text', _t('Display Text: ' ) ); // Add checkbox to put in/out of maintenance mode $ui->append( 'checkbox', 'in_maintenance', self::OPTION_NAME . '__in_maintenance', _t( 'In Maintenance Mode' ) ); $ui->append( 'checkbox', 'display_feeds', self::OPTION_NAME . '__display_feeds', _t( 'Display Feeds When In Maintenance Mode' ) ); $ui->append( 'submit', 'save', _t( 'Save' ) ); $ui->on_success( array( $this, 'updated_config' ) ); $ui->out(); } /** * Save updated configuration */ public function updated_config( $ui ) { $msg = _t( "Maintenance Mode configuration updated" ); $msg .= "<br/>"; if ( $ui->in_maintenance->value === FALSE ) { $msg .= _t( "The site is not in maintenance mode" ); } else { $msg .= _t( "The site is in maintenance mode" ); } Session::notice( $msg ); $ui->save(); } /** * Filter requests */ public function filter_rewrite_request( $start_url ) { // Just return if the site isn't maintenance mode if ( ! Options::get( self::OPTION_NAME . '__in_maintenance' ) ) { return $start_url; } // Display feeds if that option is checked if ( Options::get( self::OPTION_NAME . '__display_feeds' ) ) { if ( strpos( $start_url, 'atom' ) !== FALSE || strpos( $start_url, 'rss' ) !== FALSE || strpos( $start_url, 'rsd' ) !== FALSE ) { return $start_url; } } // Put the site in maintenance mode, unless it's a request to login pages or the admin if ( ! User::identify()->loggedin ) { if ( strpos( $start_url, 'user/login' ) === FALSE && strpos( $start_url, 'auth/login' ) === FALSE && strpos( $start_url, 'admin' ) === FALSE ) { $start_url = 'maintenance'; } } return $start_url; } /** * Add a rule to respond to redirected requests when the site is in maintenance mode */ public function filter_rewrite_rules( $rules ) { $rules[] = new RewriteRule ( array( 'name' => 'maintenance', 'parse_regex' => '%^maintenance%i', 'build_str' => 'maintenance', 'handler' => 'UserThemeHandler', 'action' => 'display_maintenance', 'priority' => 4, 'rule_class' => RewriteRule::RULE_PLUGIN, 'is_active' => ( User::identify()->loggedin ? 0 : 1 ), 'description' => 'Displays the maintenance mode page' ) ); return $rules; } /** * Respond to redirected requests when the site is in maintenance mode */ public function filter_theme_act_display_maintenance( $handled, $theme ) { header("HTTP/1.1 503 Service Unavailable"); header('Retry-After: 900'); if ( $theme->template_exists('maintenance') ) { $theme->maintenance_text = Options::get( self::OPTION_NAME . '__text' ); $theme->display( 'maintenance' ); } else { $theme->display('header'); echo '<h2 id="maintenance_text">' . htmlspecialchars( Options::get( self::OPTION_NAME . '__text' ), ENT_COMPAT, 'UTF-8' ) . '</h2>'; $theme->display('footer'); die(); } return TRUE; } /** * Check for updates to the plugin */ public function action_update_check() { Update::add( 'Maintenance Mode', '1F66810A-6CD5-11DD-BC10-8E2156D89593', $this->info->version ); } /** * Add help text to plugin configuration page */ public function help() { $help = _t( 'When \'In Maintenance Mode\' is checked, a maintenance message is displayed to anonymous users. The template named \'maintenance.php\' will be used to display the maintenance text, and if that template isn\'t found the plugin will try to incorporate the maintenance text into the site by inserting it between the theme\'s header and footer templates. Feeds can be excluded from maintenance mode by checking \'Display Feeds When In Maintenance Mode\'.' ); return $help; } } ?> <file_sep><?php class TagRewriter extends Plugin { /** * Add update beacon support **/ public function action_update_check() { Update::add( $this->info->name, '7cc973f3-dd6e-4081-98a3-535c7bf6e799', $this->info->version ); } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t('Configure'); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure') : $ui = new FormUI( strtolower( get_class( $this ) ) ); $ui->append( 'checkbox', 'pluralization', 'tagrewriter__plurals', _t('Attempt automatic pluralization coordination to existing tags') ); $ui->append( 'static', 'explanation', 'Create aliases in the form of <code>{original}={new}</code>' ); $ui->append( 'textmulti', 'aliases', 'tagrewriter__aliases', _t('Aliases:') ); $ui->append( 'submit', 'save', _t('Save') ); $ui->out(); break; } } } private static function get_aliases() { $option= Options::get('tagrewriter__aliases'); $aliases= array(); foreach($option as $alias) { $exploded= explode('=', $alias); $aliases[$exploded[0]]= $exploded[1]; } return $aliases; } public function action_post_update_before($post) { $aliases= self::get_aliases(); if(Options::get('tagrewriter__plurals') != NULL && Options::get('tagrewriter__plurals') == 1) { $pluralize= true; } else { $pluralize= false; } $tags= array(); foreach($post->tags as $tag) { if(isset($aliases[$tag])) { $tags[]= $aliases[$tag]; continue; } if($pluralize) { if(Tags::get_by_slug($tag . 's') != false) { $tags[]= $tag . 's'; continue; } elseif(Tags::get_by_slug(rtrim($tag, 's')) != false) { $tags[]= rtrim($tag, 's'); continue; } } $tags[]= $tag; } $post->tags= $tags; } } ?><file_sep><?php /** * habaridiggbarkiller Plugin * * A plugin for Habari that removes the diggbar frame * adapted from http://farukat.es/journal/2009/04/225-javascript-diggbar-killer-not-blocker * * @package habaridiggbarkiller */ class habaridiggbarkiller extends Plugin { const VERSION= '1.0.0'; /** * function info * * Returns information about this plugin * @return array Plugin info array */ public function info() { return array ( 'name' => 'habaridiggbarkiller', 'url' => 'http://www.somefoolwitha.com', 'author' => 'MatthewM', 'authorurl' => 'http://somefoolwitha.com', 'version' => self::VERSION, 'description' => 'Removes the Diggbar frame.', 'license' => 'Apache License 2.0', ); } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'habaridiggbarkiller', '506FC1DE-263A-11DE-8510-152456D89593', $this->info->version ); } public function action_template_header() { ?> <!-- habaridiggbarkiller --> <script type="text/javascript"> if (top !== self && document.referrer.match(/digg\.com\/\w{1,8}/)) { top.location.replace(self.location.href); } </script> <!-- habaridiggbarkiller END --> <?php } } ?> <file_sep><?php class Technorati extends Plugin { /* * Technorati API key * You MUST change this have your Technorati API key * which can be found on http://technorati.com/developers/apikey.html * */ /* Required Plugin Informations */ public function info() { return array( 'name' => 'Technorati', 'version' => '0.5', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Technorati plugin for Habari', 'copyright' => '2007' ); } public function action_plugin_activation( $file ) { if ( realpath( $file ) == __FILE__ ) { Modules::add( 'Technorati' ); Session::notice( _t( 'Please set your Technorati API Key in the configuration.' ) ); Options::set( 'technorati__apikey', '' ); } } public function action_plugin_deactivation( $file ) { if ( realpath( $file ) == __FILE__ ) { Modules::remove_by_name( 'Technorati' ); } } public function filter_dash_modules( $modules ) { $modules[]= 'Technorati'; $this->add_template( 'dash_technorati', dirname( __FILE__ ) . '/dash_technorati.php' ); return $modules; } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t( 'Configure' ); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t( 'Configure' ): $ui = new FormUI( strtolower( get_class( $this ) ) ); $technorati_apikey = $ui->append( 'text', 'apikey', 'option:technorati__apikey', _t( 'Technorati API Key (Get it from ' ) . '<a href="http://www.technorati.com/developers/apikey.html">' . _t( 'Developer Center' ) . '</a>)' ); $technorati_apikey->add_validator( 'validate_required' ); $ui->append( 'submit', 'save', _t( 'Save' ) ); $ui->set_option( 'success_message', _t( 'Configuration saved' ) ); $ui->out(); break; } } } public function filter_dash_module_technorati( $module, $module_id, $theme ) { $theme->technorati_stats = $this->theme_technorati_stats(); $module['content']= $theme->fetch( 'dash_technorati' ); return $module; } public function theme_technorati_stats() { if ( Cache::has( array( Site::get_url( 'habari' ), 'technorati_stats' ) ) ) { $stats = Cache::get( array( Site::get_url( 'habari' ), 'technorati_stats' ) ); } else { $stats = $this->get_technorati_stats(); if ( count( $stats ) ) { Cache::set( array( Site::get_url( 'habari' ), 'technorati_stats' ), $stats ); } else { $stats['Technorati is not available at this time'] = ''; } } return $stats; } public function get_technorati_stats() { $technorati_stats = array(); $technorati_url = 'http://api.technorati.com/bloginfo?key=' . Options::get( 'technorati__apikey' ) . '&url='. Site::get_url('habari'); $response = RemoteRequest::get_contents( $technorati_url ); if( $response !== FALSE ) { $xml = new SimpleXMLElement( $response ); if( isset( $xml->document->result->weblog ) ) { $technorati_inbound_blogs = (int)$xml->document->result->weblog[0]->inboundblogs; $technorati_inbound_links = (int)$xml->document->result->weblog[0]->inboundlinks; $technorati_rank = (int)$xml->document->result->weblog[0]->rank; $technorati_stats['Rank'] = $technorati_rank; $technorati_stats['Inbound Links'] = $technorati_inbound_links; $technorati_stats['Inbound Blogs'] = $technorati_inbound_blogs; } } return $technorati_stats; } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Technorati', '24205fa0-38f4-11dd-ae16-0800200c9a66', $this->info->version ); } } ?> <file_sep><?php /* * XSPF Mini Plugin for Habari * Embeds an audio player in posts * @version $Id$ * @copyright 2008 */ Class XSPFMini extends Plugin { public function info() { return array( 'name'=>'XSPF Mini', 'version'=>'0.1', 'url'=>'http://habariproject.org/', 'author'=>'Habari Community', 'authorurl'=>'http://habariproject.org/', 'license'=>'ASL 2.0', 'description'=>'An audio player using the xspf slim player.' ); } public function action_update_check() { Update::add( 'XSPF Mini', '0DE511F0-7890-11DD-9F6E-3D7356D89593', $this->info->version ); } public function filter_post_content_out( $content ) { preg_match_all( '/<!-- file:(.*) -->/i', $content, $matches, PREG_PATTERN_ORDER ); $matches_obj = new ArrayObject( $matches[1] ); for( $it = $matches_obj->getIterator(); $it->valid(); $it->next() ){ $content = str_ireplace( '<!-- file:' . $it->current() . ' -->', $this->embed_player( $it->current() ), $content ); } return $content; } public function embed_player( $file ) { $player = '<p><object width="300" height="20">'; $player .= '<param name="movie" value="' . $this->get_url() . '/xspf_player_slim.swf?song_url=' . $file . '&song_title=' . basename( $file, '.mp3' ) . '&player_title=' . htmlspecialchars( Options::get( 'title' ), ENT_COMPAT, 'UTF-8' ) . '" />'; $player .= '<param name="wmode" value="transparent" />'; $player .= '<embed src="' . $this->get_url() . '/xspf_player_slim.swf?song_url=' . $file . '&song_title=' . basename( $file, '.mp3' ). '&player_title=' . htmlspecialchars( Options::get( 'title' ), ENT_COMPAT, 'UTF-8' ) . '" type="application/x-shockwave-flash" wmode="transparent" width="300" height="20"></embed>'; $player .= '</object></p>'; return $player; } public function action_admin_header_after( $theme ) { echo <<< XSPFMINI <script type="text/javascript"> $.extend(habari.media.output.audio_mpeg3, { add_xspfmini_player: function(fileindex, fileobj) { habari.editor.insertSelection('<!-- file:'+fileobj.url+' -->'); }}); </script> XSPFMINI; } } ?><file_sep><?php class LoginRedirect extends Plugin { public function filter_login_redirect_dest( $login_dest, $user, $login_session ) { if(isset($login_session) && $user->info->login_redirect != '') { $login_dest = $user->info->login_redirect; } return $login_dest; } /** * Add the configuration to the user page **/ public function action_form_user( $form, $user ) { $fieldset = $form->append( 'wrapper', 'login_redirect_fieldset', 'Login Redirect' ); $fieldset->class = 'container settings'; $fieldset->append( 'static', 'login_redirect_title', '<h2>Login Redirect</h2>' ); $activate = $fieldset->append( 'text', 'login_redirect', 'null:null', _t('Redirect to this URL after login:') ); $activate->class[] = 'item clear'; $activate->value = $user->info->login_redirect; $form->move_before( $fieldset, $form->page_controls ); } /** * Save authentication fields **/ public function filter_adminhandler_post_user_fields( $fields ) { $fields[] = 'login_redirect'; return $fields; } } ?><file_sep><?php /** * Populate the database with users, groups and tokens to see how admin theme * and templates render, and check management functionality. * * @author ilo * **/ class Populate extends Plugin { /** * Habari integration functions. */ /** * Plugin activation function. Populate tables with random data using * default values. * @param string $file the plugin being activated. */ function action_plugin_activation( $file ) { if(Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__)) { // Set default options for the module. Options::set( 'populate__tokens', 15); Options::set( 'populate__groups', 5); Options::set( 'populate__users', 25); // Avoid breaking in the middle of the operation $time_limit = ini_get('time_limit'); ini_set( 'time_limit', 0); // Create random data $this->populate_tokens_add(); $this->populate_groups_add(); $this->populate_users_add(); ini_set( 'time_limit', $time_limit); } } /** * Plugin activation function. Remove all information created by this plugin. * @param string $file the plugin being activated. */ function action_plugin_deactivation( $file ) { if(Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__)) { // Avoid breaking in the middle of the operation $time_limit = ini_get('time_limit'); ini_set( 'time_limit', 0); // Destroy all data $this->populate_users_remove(); $this->populate_groups_remove(); $this->populate_tokens_remove(); ini_set( 'time_limit', $time_limit); // Delete all options created by this plugin. Options::delete( 'populate__tokens' ); Options::delete( 'populate__groups' ); Options::delete( 'populate__users' ); } } /** * Adds a Configure action to the plugin * * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The id of a plugin * @return array The array of actions */ public function filter_plugin_config( $actions, $plugin_id ) { if ( $this->plugin_id() == $plugin_id ){ $actions[]= 'Configure'; } return $actions; } /** * Handler for the user interface action. * @param string $plugin_id The id of a plugin. * @param array $actions An array of actions that apply to this plugin. * @return FormUI */ public function action_plugin_ui( $plugin_id, $action ) { if ( $this->plugin_id() == $plugin_id && $action=='Configure' ) { return $this->form_ui_configure_form(); } } /** * User interface functions. */ /** * Builds the configuration form. * return @FormUI */ private function form_ui_configure_form() { $form = new FormUI( strtolower(get_class( $this ) ) ); $form->append( 'text', 'tokens', 'option:populate__tokens', _t('Number of Tokens:')); $form->append( 'text', 'groups', 'option:populate__groups', _t('Number of user Groups:')); $form->append( 'text', 'users', 'option:populate__users', _t('Number of Users:')); $form->tokens->add_validator( 'validate_required' ); $form->groups->add_validator( 'validate_required' ); $form->users->add_validator( 'validate_required' ); $form->tokens->add_validator( 'validate_range', -1, 200 ); $form->groups->add_validator( 'validate_range', -1, 200 ); $form->users->add_validator( 'validate_range', -1, 200 ); $form->append( 'submit', 'save', _t( 'Save' ) ); $form->on_success( array( $this, 'form_ui_configure_success' ) ); $form->out(); } /** * Automatically update the number of tokens, users and groups to the new * configuration values. This function will add or remove items according to * the configured values. * @param FormUI $ui the form being submitted */ public function form_ui_configure_success( $ui ) { // Avoid breaking in the middle of the operation $time_limit = ini_get('time_limit'); ini_set( 'time_limit', 0); // Fix the number of tokens. $tokens_diff = $ui->tokens->value - count( $this->populate_tokens_get()) ; if ( $tokens_diff > 0) { $this->populate_tokens_add( $tokens_diff ); } else if ( $tokens_diff < 0) { $this->populate_tokens_remove( abs($tokens_diff) ); } // Fix the number of groups. $groups_diff = $ui->groups->value - count( $this->populate_groups_get()); if ( $groups_diff > 0) { $this->populate_groups_add( $groups_diff ); } else if ( $groups_diff < 0) { $this->populate_groups_remove( abs($groups_diff) ); } // Fix the number of groups. $users_diff = $ui->users->value - count( $this->populate_users_get()); if ( $users_diff > 0) { $this->populate_users_add( $users_diff ); } else if ( $users_diff < 0) { $this->populate_users_remove( abs($users_diff) ); } ini_set( 'time_limit', $time_limit); SEssion::notice( _t( 'Finished updating populated data.' ) ); } /** * API functions */ /** * Add tokens to the tokens table * @param integer $num number of tokens to add, or configured value if null. */ private function populate_tokens_add( $num = null) { if ( !isset( $num ) ) { $num = Options::get('populate__tokens'); } // Add all these tokens. $count = 0; while ( $count++ < $num ) { // Create an ACL token. ACL::create_token( 'populate_token_' . strtolower( $this->helper_random_name(9)), 'Populate ' . $this->helper_random_name(), 'Administration', rand(0, 1) ); } return; } /** * Get tokens created by this module. * @param integer $num number of tokens to get, or all if not specified. * @return array tokens found. */ private function populate_tokens_get( $num = null ) { // get all tokens $alltokens = ACL::all_tokens(); // internal loop to get only our tokens. $tokens = array(); $count = 0; foreach ( $alltokens as $id => $token) { if ( strpos( $token->name, 'opulate_' ) ) { $tokens[] = $token; if ( isset( $num ) && $num == ++$count ) break; } } return $tokens; } /** * Remove tokens from the tokens table. * @param integer $num number of tokens to remove, or configured value if null. */ private function populate_tokens_remove( $num = null ) { // Get our own tokens. $tokens = $this->populate_tokens_get( $num ); // clean these tokens foreach ( $tokens as $id => $token) { ACL::destroy_token($token->id); } return; } /** * Add user groups to the groups table, randomly assign them existing tokens. * @param integer $num number of groups to add, or configured value if null. */ private function populate_groups_add( $num = null ) { if ( !isset( $num ) ) { $num = Options::get('populate__groups'); } // Get all tokens that we have created. $tokens = $this->populate_tokens_get(); // Add all these groups. $count = 0; while ( $count++ < $num ) { // Create a new group. $group = Usergroup::create( array( 'name' => 'populate_' . $this->helper_random_name() ) ); // assign tokens to this new group. $max_tokens = count( $tokens ) - 1 ; $num_tokens = rand( 0, $max_tokens ); while ($num_tokens-- > 0) { $token = rand(0, $max_tokens ); ACL::grant_group( $group->id, $tokens[$token]->id ); } } return; } /** * Get groups created by this module. * @param integer $num number of groups to get, or all if not specified. * @return array groups found. */ private function populate_groups_get( $num = null ) { // get all tokens $allgroups = Usergroups::get_all(); // internal loop to get only our groups. $groups = array(); $count = 0; foreach ( $allgroups as $id => $group) { if ( strpos( $group->name, 'opulate_' ) ) { $groups[] = $group; if ( isset( $num ) && $num == ++$count ) break; } } return $groups; } /** * Remove user groups to the groups table. * @param integer $num number of groups to remove, or configured value if null. */ private function populate_groups_remove( $num = null ) { // Get our own groups. $groups = $this->populate_groups_get( $num ); // clean these groups. foreach ( $groups as $id => $group ) { $group->delete(); } return; } /** * Add users to the users table, randomly assign them to existing groups. * @param integer $num number of users to add, or configured value if null. */ private function populate_users_add( $num = null ) { if ( !isset( $num ) ) { $num = Options::get('populate__users'); } // Get all groups. $groups = $this->populate_groups_get(); // Add all these users. $count = 0; while ( $count++ < $num ) { $name = $this->helper_random_name(); $user = User::create(array ( 'username' => 'populate_' . $name, 'email' => $name . '@example.com', 'password' => md5('q' . <PASSWORD>(0,65535)), )); // Assign this user to groups. $max_groups = count( $groups ) - 1; $num_groups = rand( 0, $max_groups ); while ($num_groups-- > 0) { $group = rand(0, $max_groups ); $user->add_to_group($groups[$group]->id); } } return; } /** * Get users created by this module. * @param integer $num number of users to get, or all if not specified. * @return array users found. */ private function populate_users_get( $num = null ) { // get all tokens $allusers = Users::get_all(); // internal loop to get only our users. $users = array(); $count = 0; foreach ( $allusers as $id => $user) { if ( strpos( $user->username, 'opulate_' ) ) { $users[] = $user; if ( isset( $num ) && $num == ++$count ) break; } } return $users; } /** * Remove users from the users table. * @param integer $num number of users to remove, or configured value if null. */ private function populate_users_remove( $num = null ) { // Get our own users. $users = $this->populate_users_get( $num ); // clean these users. foreach ( $users as $id => $user ) { $user->delete(); } return; } /* * Helper functions */ /** * Generates a random string containing letters and numbers. * * The string will always start with a letter. The letters may be upper or * lower case. * * @param $length * Length of random string to generate. * @return * Randomly generated string. */ public function helper_random_name ( $length = 12 ) { $values = array_merge(range(65, 90), range(97, 122), range(48, 57)); $max = count($values) - 1; $str = chr(mt_rand(97, 122)); for ($i = 1; $i < $length; $i++) { $str .= chr($values[mt_rand(0, $max)]); } return $str; } } ?> <file_sep><?php //Check if file is writable if(!is_writable($_POST['file'])){die("<span style=\"color:#B00;font-weight:bold;\">File not writable.</span>");} $contents = $_POST['contents']; //Write to file file_put_contents($_POST['file'],$contents) or die("<span style=\"color:#B00;font-weight:bold;\">Failed to write to file.</span>"); //Send success signal echo "<span style=\"color:#0B0;font-weight:bold;\">File saved Successfully.</span>"; ?> <file_sep><?php class ViewBlog extends Plugin { const VERSION = '1.0'; /** * Required plugin info() implementation provides info to Habari about this plugin. */ public function info() { return array( 'name' => 'View Blog Menu Item', 'url' => 'http://blog.voodoolabs.net/', 'author' =>'<NAME>', 'authorurl' => 'http://blog.voodoolabs.net/', 'version' => self::VERSION, 'description' => 'Adds an extra menu item for viewing the blog', 'license' => 'Apache License 2.0', ); } public function filter_adminhandler_post_loadplugins_main_menu($mainmenus) { $mainmenus['view'] = array( 'url' => Site::get_url('habari'), 'title' => _t('View blog'), 'text' => _t('View Blog'), 'hotkey' => 'V', 'selected' => ''); return $mainmenus; } } ?> <file_sep><?php /** * traffic_sources_overview.php * Template for Traffic Sources Overview dashboard module * * If you need to override the options, do it here. **/ ?> <div class="pct90" id="div_<?php echo $slug; ?>"></div> <script type="text/javascript"> var opts = { <?php echo $js_opts; ?> }; <?php echo $js_data; ?> <?php echo $js_draw; ?> </script> <file_sep><?php class lastfmAPI { function __construct() { $this->key = '<KEY>'; $this->secret = 'b8b8288e69ea9b7bae5be0fb0449f522'; $this->endpoint = 'http://ws.audioscrobbler.com/2.0/'; $this->conntimeout = 20; } function fetch($method, $params = array(), $tokenize = false, $debug = false) { $url = $this->endpoint; $url.= '?method=' . strtolower($method); foreach($params as $key => $val) { $url.= '&' . $key . '=' . $val; } $url.= '&api_key=' . $this->key; if($debug) { print_r($url); } $contents = RemoteRequest::get_contents($url); $data = new SimpleXMLElement($contents); if($data['status'] == 'ok') { return $data; } else { return FALSE; } } function tags() { return $this->fetch('user.getTopTags', array('user' => User::identify()->info->lastfm__username)); } /* this SHOULD fetch all tracks from a user's library. except it is recursive and insanely processor intensive. use at your own risk */ function tracks($page) { $tracks = $this->fetch('library.getTracks', array('user' => User::identify()->info->lastfm__username, 'page' => $page)); $results = array(); foreach($tracks->tracks->track as $track) { $props = array(); $props['title'] = (string)$track->name; $props['url'] = (string)$track->url; $props['icon'] = (string)$track->image[1]; $props['thumbnail_url'] = (string)$track->image[1]; $props['image_url'] = (string)$track->image[2]; $props['filetype'] = 'lastfm'; $results[] = new MediaAsset( lastfmSilo::SILO_NAME . '/songs/'. (string)$track->title, false, $props ); } if($tracks->tracks['page'] != $tracks->tracks['totalPages']) { $results = array_merge($results, $this->tracks($page + 1)); } return $results; } } /** * last.fm Silo */ class lastfmSilo extends Plugin implements MediaSilo { const SILO_NAME = 'Last.fm'; static $cache = array(); /** * Provide plugin info to the system */ public function info() { return array('name' => 'Last.fm Media Silo', 'version' => '1.0', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Allows data from last.fm to be inserted into posts', 'copyright' => '2008', ); } public function action_admin_footer() { echo '<script type="text/javascript">'; require('lastfm.js'); echo '</script>'; } /** * Initialize some internal values when plugin initializes */ public function action_init() { $this->api = new lastfmAPI(); } /** * Return basic information about this silo * name- The name of the silo, used as the root directory for media in this silo * icon- An icon to represent the silo */ public function silo_info() { if(User::identify()->info->lastfm__username != '') { return array('name' => self::SILO_NAME, 'icon' => URL::get_from_filesystem(__FILE__) . '/icon.png'); } else { return array(); } } /** * Add actions to the plugin page for this plugin * The authorization should probably be done per-user. * * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id */ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()){ $actions[] = 'Configure'; } return $actions; } /** * Respond to the user selecting an action on the plugin page * * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook */ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id == $this->plugin_id()){ switch ($action){ case _t('Configure') : $ui = new FormUI( strtolower( get_class( $this ) ) ); $ui->append( 'text', 'username', 'user:lastfm__username', _t('User:') ); $ui->append('submit', 'save', _t( 'Save' ) ); $ui->set_option('success_message', _t('Options saved')); $ui->out(); break; } } } /** * Return directory contents for the silo path * * @param string $path The path to retrieve the contents of * @return array An array of MediaAssets describing the contents of the directory */ public function silo_dir($path) { $results = array(); $user = User::identify()->info->lastfm_username; $section = strtok($path, '/'); switch($section) { case 'tags': $selected = strtok('/'); if($selected) { if($artist = strtok('/')) { if($level = strtok('/')) { if($level == 'albums') { $albums = $this->api->fetch('artist.getTopAlbums', array('artist' => $artist)); foreach($albums->topalbums->album as $album) { $props = array(); $props['title'] = (string)$album->name; $props['url'] = (string)$album->url; $props['icon'] = (string)$album->image[1]; $props['thumbnail_url'] = (string)$album->image[1]; $props['image_url'] = (string)$album->image[2]; $props['filetype'] = 'lastfm'; $results[] = new MediaAsset( self::SILO_NAME . '/tags/' . $selected . '/' . $artist . '/' . (string)$album->mbid, false, $props ); } } elseif($level == 'songs') { $tracks = $this->api->fetch('artist.getTopTracks', array('artist' => $artist)); foreach($tracks->toptracks->track as $track) { $props = array(); $props['title'] = (string)$track->name; $props['url'] = (string)$track->url; $props['icon'] = (string)$track->image[1]; $props['thumbnail_url'] = (string)$track->image[1]; $props['image_url'] = (string)$track->image[2]; $props['filetype'] = 'lastfm'; $results[] = new MediaAsset( self::SILO_NAME . '/tags/' . $selected . '/' . $artist . '/' . (string)$track->name, false, $props ); } } } else { $results[] = new MediaAsset( self::SILO_NAME . '/tags/' . $selected . '/' . $artist . '/albums', true, array('title' => 'Albums') ); $results[] = new MediaAsset( self::SILO_NAME . '/tags/' . $selected . '/' . $artist . '/songs', true, array('title' => 'Songs') ); } } else { $artists = $this->api->fetch('tag.getTopArtists', array('tag' => $selected)); foreach($artists->topartists->artist as $artist) { $results[] = new MediaAsset( self::SILO_NAME . '/tags/' . $selected . '/' . (string)$artist->name, true, array('title' => (string)$artist->name) ); } } } else { $tags = $this->api->tags(); foreach($tags->toptags->tag as $tag) { $results[] = new MediaAsset( self::SILO_NAME . '/tags/' . (string)$tag->name, true, array('title' => (string)$tag->name) ); } } break; case 'artists': if($artist = strtok('/')) { if($level = strtok('/')) { if($level == 'albums') { $albums = $this->api->fetch('artist.getTopAlbums', array('artist' => $artist)); foreach($albums->topalbums->album as $album) { $props = array(); $props['title'] = (string)$album->name; $props['url'] = (string)$album->url; $props['icon'] = (string)$album->image[1]; $props['thumbnail_url'] = (string)$album->image[1]; $props['image_url'] = (string)$album->image[2]; $props['filetype'] = 'lastfm'; $results[] = new MediaAsset( self::SILO_NAME . '/artists/' . $artist . '/' . (string)$album->mbid, false, $props ); } } elseif($level == 'songs') { $tracks = $this->api->fetch('artist.getTopTracks', array('artist' => $artist)); foreach($tracks->toptracks->track as $track) { $props = array(); $props['title'] = (string)$track->name; $props['url'] = (string)$track->url; $props['icon'] = (string)$track->image[1]; $props['thumbnail_url'] = (string)$track->image[1]; $props['image_url'] = (string)$track->image[2]; $props['filetype'] = 'lastfm'; $results[] = new MediaAsset( self::SILO_NAME . '/artists/' . $artist . '/' . (string)$track->name, false, $props ); } } } else { $results[] = new MediaAsset( self::SILO_NAME . '/artists/' . $artist . '/albums', true, array('title' => 'Albums') ); $results[] = new MediaAsset( self::SILO_NAME . '/artists/' . $artist . '/songs', true, array('title' => 'Songs') ); } } else { $artists = $this->api->fetch('user.getTopArtists', array('user' => User::identify()->info->lastfm__username)); foreach($artists->topartists->artist as $artist) { $results[] = new MediaAsset( self::SILO_NAME . '/artists/' . (string)$artist->name, true, array('title' => (string)$artist->name) ); } } break; case 'albums': $albums = $this->api->fetch('library.getAlbums', array('user' => User::identify()->info->lastfm__username)); foreach($albums->albums->album as $album) { $props = array(); $props['title'] = (string)$album->name; $props['url'] = (string)$album->url; $props['icon'] = (string)$album->image[1]; $props['thumbnail_url'] = (string)$album->image[1]; $props['image_url'] = (string)$album->image[2]; $props['filetype'] = 'lastfm'; $results[] = new MediaAsset( self::SILO_NAME . '/albums/'. (string)$album->mbid, false, $props ); } break; case 'songs': $tracks = $this->api->fetch('user.getTopTracks', array('user' => User::identify()->info->lastfm__username)); foreach($tracks->toptracks->track as $track) { $props = array(); $props['title'] = (string)$track->name; $props['url'] = (string)$track->url; $props['icon'] = (string)$track->image[1]; $props['thumbnail_url'] = (string)$track->image[1]; $props['image_url'] = (string)$track->image[2]; $props['filetype'] = 'lastfm'; $results[] = new MediaAsset( self::SILO_NAME . '/songs/'. (string)$track->url, false, $props ); } break; case 'recent': $tracks = $this->api->fetch('user.getRecentTracks', array('user' => User::identify()->info->lastfm__username)); foreach($tracks->recenttracks->track as $track) { $props = array(); $props['title'] = (string)$track->name; $props['url'] = (string)$track->url; $props['icon'] = (string)$track->image[1]; $props['thumbnail_url'] = (string)$track->image[1]; $props['image_url'] = (string)$track->image[2]; $props['filetype'] = 'lastfm'; $results[] = new MediaAsset( self::SILO_NAME . '/recent/'. (string)$track->url, false, $props ); } break; case 'favorites': $tracks = $this->api->fetch('user.getLovedTracks', array('user' => User::identify()->info->lastfm__username)); foreach($tracks->lovedtracks->track as $track) { $props = array(); $props['title'] = (string)$track->name; $props['url'] = (string)$track->url; $props['icon'] = (string)$track->image[1]; $props['thumbnail_url'] = (string)$track->image[1]; $props['image_url'] = (string)$track->image[2]; $props['filetype'] = 'lastfm'; $results[] = new MediaAsset( self::SILO_NAME . '/favorites/'. (string)$track->url, false, $props ); } break; case '': $results[] = new MediaAsset( self::SILO_NAME . '/tags', true, array('title' => 'Tags') ); $results[] = new MediaAsset( self::SILO_NAME . '/artists', true, array('title' => 'Artists') ); $results[] = new MediaAsset( self::SILO_NAME . '/albums', true, array('title' => 'Albums') ); $results[] = new MediaAsset( self::SILO_NAME . '/songs', true, array('title' => 'Songs') ); $results[] = new MediaAsset( self::SILO_NAME . '/recent', true, array('title' => 'Recent Songs') ); $results[] = new MediaAsset( self::SILO_NAME . '/favorites', true, array('title' => 'Favorites') ); break; } return $results; } /** * Provide controls for the media control bar * * @param array $controls Incoming controls from other plugins * @param MediaSilo $silo An instance of a MediaSilo * @param string $path The path to get controls for * @param string $panelname The name of the requested panel, if none then emptystring * @return array The altered $controls array with new (or removed) controls * * @todo This should really use FormUI, but FormUI needs a way to submit forms via ajax */ public function filter_media_controls( $controls, $silo, $path, $panelname ) { $controls = array(); return $controls; } public function silo_upload_form() { } /** * Get the file from the specified path * * @param string $path The path of the file to retrieve * @param array $qualities Qualities that specify the version of the file to retrieve. * @return MediaAsset The requested asset */ public function silo_get($path, $qualities = null) { } /** * Get the direct URL of the file of the specified path * * @param string $path The path of the file to retrieve * @param array $qualities Qualities that specify the version of the file to retrieve. * @return string The requested url */ public function silo_url($path, $qualities = null) { } /** * Create a new asset instance for the specified path * * @param string $path The path of the new file to create * @return MediaAsset The requested asset */ public function silo_new($path) { } /** * Store the specified media at the specified path * * @param string $path The path of the file to retrieve * @param MediaAsset $ The asset to store */ public function silo_put($path, $filedata) { } /** * Delete the file at the specified path * * @param string $path The path of the file to retrieve */ public function silo_delete($path) { } /** * Retrieve a set of highlights from this silo * This would include things like recently uploaded assets, or top downloads * * @return array An array of MediaAssets to highlihgt from this silo */ public function silo_highlights() { } /** * Retrieve the permissions for the current user to access the specified path * * @param string $path The path to retrieve permissions for * @return array An array of permissions constants (MediaSilo::PERM_READ, MediaSilo::PERM_WRITE) */ public function silo_permissions($path) { } /** * Return directory contents for the silo path * * @param string $path The path to retrieve the contents of * @return array An array of MediaAssets describing the contents of the directory */ public function silo_contents() { } } ?> <file_sep><?php /** * Credit Due plugin, allows output of theme and plugin information for Habari sites. */ class CreditDue extends Plugin { /** * function info * Returns information about this plugin * @return array Plugin info array **/ function info() { return array ( 'name' => 'Credit Due', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'version' => '0.2', 'description' => 'Allows for output of information for active themes and plugins', 'license' => 'Apache License 2.0', ); } /** * function theme_show_credits * retrieves information about the active theme and returns it for display by a theme. * * Usage: This function is called using <?php $theme->show_credits(); ?> * This loads the template creditdue.php (which can be copied to the theme directory and customized) and shows the theme and plugins in unordered lists */ public function theme_show_credits( $theme ) { $theme_credits = Themes::get_active(); $plugin_credits = Plugins::get_active(); #Utils::debug($theme_credits); #Utils::debug($plugin_credits); $theme->theme_credits = $theme_credits; $theme->plugin_credits = $plugin_credits; return $theme->fetch( 'creditdue' ); } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'CreditDue', 'fb0b8460-38f2-11dd-ae16-0800200c9a66', $this->info->version ); } /** * On plugin init, add the template included with this plugin to the available templates in the theme */ public function action_init() { $this->add_template('creditdue', dirname(__FILE__) . '/creditdue.php'); } } ?> <file_sep><?php class MarkUp extends Plugin { /** * Required Plugin Information **/ public function info() { return array( 'name' => 'markUp', 'license' => 'Apache License 2.0', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'version' => '0.4', 'description' => 'Adds easy html, markdown, or textile tag insertion to Habari\'s editor', 'copyright' => '2008' ); } /** * Set options to defaults */ public function action_plugin_activation( $file ) { if ( realpath( $file ) == __FILE__ ) { $type = Options::get( 'Markup__markup_type' ); if ( empty( $type ) ) { Options::set( 'Markup__markup_type', 'html' ); } $skin = Options::get( 'Markup__skin' ); if( empty( $skin ) ) { Options::set( 'Markup__skin', 'simple' ); } } } public function action_init() { spl_autoload_register( array( __CLASS__, '_autoload' ) ); } public static function _autoload( $class ) { if( strtolower( $class ) == 'textile' ) { require( 'markitup/parsers/textile/classTextile.php' ); } elseif( strtolower( $class ) == 'markdown_parser' ) { require( 'markitup/parsers/markdown/markdown.php' ); } } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t( 'Configure' ); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { $types = array( 'html' => 'html', 'markdown' => 'markdown', 'textile' => 'textile', ); $skins = array( 'simple' => 'Simple', 'markitup' => 'MarkItUp', ); if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t( 'Configure' ): $form = new FormUI( 'markup' ); $form->append( 'select', 'markup_type', 'Markup__markup_type', _t( 'Markup Type ' ) ); $form->markup_type->options = $types; $form->append( 'select', 'skin', 'Markup__skin', _t( 'Editor Skin&nbsp;&nbsp;&nbsp; ' ) ); $form->skin->options = $skins; $form->append( 'submit', 'save', _t( 'Save' ) ); $form->on_success( array( $this, 'config_success' ) ); $form->out(); break; } } } public static function config_success( $ui ) { $ui->save(); Session::notice( 'Markup settings updated.' ); } public function action_admin_header( $theme ) { if ( $theme->page == 'publish' ) { $set = Options::get( 'Markup__markup_type' ); switch( $set ) { case 'markdown': $dir = 'markdown'; break; case 'textile': $dir = 'textile'; break; case 'html': default: $dir = 'html'; } $skin = Options::get( 'Markup__skin' ); Stack::add( 'admin_header_javascript', $this->get_url() . '/markitup/jquery.markitup.pack.js', 'markitup', 'jquery' ); Stack::add( 'admin_header_javascript', $this->get_url() . '/markitup/sets/' . $dir . '/set.js', 'markitup_set', 'jquery' ); Stack::add( 'admin_stylesheet', array( $this->get_url() . '/markitup/skins/' . $skin . '/style.css', 'screen' ) ); Stack::add( 'admin_stylesheet', array( $this->get_url() . '/markitup/sets/' . $dir . '/style.css', 'screen' ) ); } } public function alias() { return array( 'do_markup' => array( 'filter_post_content_out', 'filter_post_content_excerpt', 'filter_post_content_summary' ) ); } public function do_markup( $content, $post ) { static $textile; static $markdown; $markup = Options::get( 'Markup__markup_type' ); switch( $markup ) { case 'markdown': // return Markdown( $content ); if( !isset( $markdown ) ) { $markdown = new Markdown_Parser; } return $markdown->transform( $content ); break; case 'textile': if( !isset( $textile) ) { $textile = new Textile(); } return $textile->TextileThis( $content ); break; case 'html': default: return $content; } } public function action_admin_footer($theme) { if ( $theme->page == 'publish' ) { $skin = Options::get( 'Markup__skin' ); $set = ( ( 'markitup' == $skin ) ? Options::get( 'Markup__markup_type' ) : '' ); $path = $this->get_url(); $markup = <<<MARKITUP $(document).ready(function() { mySettings.nameSpace = '$set'; mySettings.resizeHandle= false; mySettings.markupSet.push({separator:'---------------' }); mySettings.markupSet.push({ name: 'Full Screen', className: 'fullScreen', key: "F", call: function(){ if (\$('.markItUp').hasClass('fullScreen')) { \$('.markItUp').removeClass('fullScreen'); \$('textarea#content').css( 'height', markItUpTextareaOGHeight + "px" ); } else { markItUpTextareaOGHeight = \$('textarea#content').innerHeight(); \$('.markItUp').addClass('fullScreen'); \$('.markItUp.fullScreen textarea#content').css( 'height', (\$('.markItUp.fullScreen').innerHeight() - 90) + "px" ); } } }); $("#content").markItUp(mySettings); $('label[for=content].overcontent').attr('style', 'margin-top:30px;margin-left:5px;'); $('#content').focus(function(){ $('label[for=content]').removeAttr('style'); }).blur(function(){ if ($('#content').val() == '') { $('label[for=content]').attr('style', 'margin-top:30px;margin-left:5px;'); } else { $('label[for=content]').removeAttr('style'); } }); }); MARKITUP; Stack::add( 'admin_footer_javascript', $markup, 'markup_footer', 'jquery' ); echo <<<STYLE <style type="text/css"> .markItUp.fullScreen { position: absolute; top: 0; left: 0; height: 100%; width: 100%; z-index: 9999; margin: 0; background: #f0f0f0; } .markItUp.fullScreen .markItUpContainer{ padding: 20px 40px 40px; } .markItUp li.fullScreen { background: transparent url($path/fullscreen.png) no-repeat; } .markItUp.fullScreen li.fullScreen { background: transparent url($path/normalscreen.png) no-repeat; } </style> STYLE; } } public function action_update_check() { Update::add( 'markUp', 'F695D390-2687-11DD-B5E1-2D6F55D89593', $this->info->version ); } } ?><file_sep><!-- Sidebar menu div --> <div id="menu"> <?php Plugins::act( 'theme_sidebar_top' ); ?> <ul> <?php if ($this->request->display_search) { ; ?> <li id="search"> <?php _e('Search results for \'%s', array( htmlspecialchars( $criteria ) ) ); ?>'</li> <?php } ?> <div id="sidebar_area"> <?php $theme->area('sidebar'); ?> </div> <li class="user"><?php _e('User'); ?><ul> <?php $theme->display ( 'loginform' ); ?> </ul></li> <?php if ( User::identify()->loggedin ) { $theme->switcher(); } ?> </ul> <?php Plugins::act( 'theme_sidebar_bottom' ); ?> </div> <file_sep><?php /** * Twitter Silo */ class TwitterSilo extends Plugin implements MediaSilo { const SILO_NAME = 'Twitter'; protected $Twitter; /** * Return basic information about this silo * name- The name of the silo, used as the root directory for media in this silo * icon- An icon to represent the silo */ public function silo_info() { return array( 'name' => self::SILO_NAME ); } /** * Return directory contents for the silo path * @param string $path The path to retrieve the contents of * @return array An array of MediaAssets describing the contents of the directory **/ public function silo_dir( $path ) { switch ( strtok( $path, '/' ) ) { case '': return array( new MediaAsset(self::SILO_NAME . '/mine/', true), new MediaAsset(self::SILO_NAME . '/friends/', true), new MediaAsset(self::SILO_NAME . '/custom/', true), ); break; // (for good measure) case 'custom': return array( new MediaAsset( self::SILO_NAME . '/mine/custom', false, array( 'url' => 'http://twitter.com/home', 'filetype' => 'twittertweetcustom', ) ), ); break; // (for good measure) case 'mine': return $this->get_mine(); break; // (for good measure) case 'friends': $friend = strtok( '/' ); if ( $friend === false ) { return $this->get_friends(); } else { return $this->get_friend_tweets( $friend ); } break; // (for good measure) } } /** * Get the file from the specified path * @param string $path The path of the file to retrieve * @param array $qualities Qualities that specify the version of the file to retrieve. * @return MediaAsset The requested asset **/ public function silo_get( $path, $qualities = null ) { return MediaAsset('foo', false); } /** * Store the specified media at the specified path * @param string $path The path of the file to retrieve * @param MediaAsset The asset to store **/ public function silo_put( $path, $filedata ) {} /** * Delete the file at the specified path * @param string $path The path of the file to retrieve **/ public function silo_delete( $path ) {} /** * Retrieve a set of highlights from this silo * This would include things like recently uploaded assets, or top downloads * @return array An array of MediaAssets to highlihgt from this silo **/ public function silo_highlights() {} /** * Retrieve the permissions for the current user to access the specified path * @param string $path The path to retrieve permissions for * @return array An array of permissions constants (MediaSilo::PERM_READ, MediaSilo::PERM_WRITE) **/ public function silo_permissions( $path ) {} public function action_admin_footer( $theme ) { if ( Controller::get_var( 'page' ) == 'publish' ) { ?><script type="text/javascript"> function inject_tweet(text, url, user, img) { habari.editor.insertSelection('<!-- TWEET --><div class="twitter-tweet"><div class="tweet-text"><a href="' + url + '"><img src="' + img + '" class="tweet-image" /></a>' + text + '</div><div class="tweet-author"><a href="' + url + '">' + user + '</a></div></div><!-- /TWEET -->'); } //$('.media_controls').css('display', 'none'); habari.media.output.twittertweet = {'Insert': function(fileindex, fileobj) { inject_tweet(fileobj.tweet_text, fileobj.url, fileobj.tweet_user, fileobj.tweet_user_img); }} habari.media.preview.twittertweet = function(fileindex, fileobj) { return '<div class="mediatitle"><a href="' + fileobj.url + '" target="_new" class="medialink">media</a>' + fileobj.tweet_user_screen_name + '</div>' + fileobj.tweet_text_short; } habari.media.output.twittertweetcustom = {'Insert': function(fileindex, fileobj) { $.get("/auth_ajax/tweetcustom?tweet=" + escape($('#tweetcustom').val()), function( data ){ if (data) { inject_tweet(data.text, 'http://twitter.com/' + escape(data.user.screen_name) + '/statuses/' + escape(data.id), data.user.screen_name, data.user.profile_image_url); } }, {}, 'json' ); }} habari.media.preview.twittertweetcustom = function(fileindex, fileobj) { return '<div class="mediatitle">CUSTOM</div>Tweet ID/URL: <input id="tweetcustom" type="text" />'; } </script><?php } } public function action_auth_ajax_tweetcustom( $handler ) { $tweet = isset( $_GET['tweet'] ) ? $_GET['tweet'] : ''; $tweet = preg_replace( '@http://(www\.)?twitter.com/([^/]+)/([^/]+)/([0-9]+)@', '$4', $tweet ); if ( ctype_digit( $tweet ) ) { $ret = self::twitter_status( $tweet ); } else { $ret = false; } echo json_encode( $ret ); } public function theme_header() { // add CSS return '<link rel="stylesheet" type="text/css" media="screen" href="' . $this->get_url( true ) . 'twittersilo.css" />'; } protected function get_mine() { return $this->to_assets( self::twitter_mine(), 'mine' ); } protected function get_friend_tweets ( $id ) { return $this->to_assets( self::twitter_friend_tweets( $id ), 'friends' ); } protected function get_friends() { $friends = array(); $friendsObj = self::twitter_friends(); foreach ($friendsObj as $friend) { $friends[] = new MediaAsset(self::SILO_NAME . '/friends/' . $friend->screen_name, true); } return $friends; } protected function to_assets( $objs, $type ) { foreach ($objs as $obj) { $tweets[] = new MediaAsset( self::SILO_NAME . '/' . $type . '/' . $obj->user->name . '/' . $obj->id, false, array( 'tweet_id' => $obj->id, 'url' => 'http://twitter.com/' . $obj->user->screen_name . '/statuses/' . $obj->id, 'tweet_user' => (string) $obj->user->name, 'tweet_user_img' => (string) $obj->user->profile_image_url, 'tweet_user_screen_name' => (string) $obj->user->screen_name, 'tweet_text_short' => substr( $obj->text, 0, 20 ) . ( strlen( $obj->text ) > 20 ? '...' : '' ), 'tweet_text' => (string) $obj->text, 'filetype' => 'twittertweet', ) ); } return $tweets; } /** * Add actions to the plugin page for this plugin * The authorization should probably be done per-user. * * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id */ public function filter_plugin_config($actions, $plugin_id) { $actions[] = 'Configure'; return $actions; } /** * Respond to the user selecting an action on the plugin page * * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook */ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id == $this->plugin_id()){ switch ($action){ case 'Configure': $ui = new FormUI( strtolower( get_class( $this ) ) ); $ui->append( 'text', 'twitter_user', 'option:twittersilo__user', _t( 'Twitter Username:' ) ); $ui->append( 'password', '<PASSWORD>', 'option:twittersilo__pass', _t( 'Twitter Password:' ) ); $ui->append('submit', 'save', _t( 'Save' ) ); $ui->set_option('success_message', _t('Options saved')); $ui->out(); break; } } } protected static function twitter_fetch ( $url ) { if ( $user = Options::get( 'twittersilo__user' ) ) { // cheap hack: $tweetURL = preg_replace( '@^(https?)://@', '$1://' . urlencode( $user ) . ':' . Options::get('twittersilo__pass') .'@', $url ); } else { $tweetURL = $url; } if ( $result = @file_get_contents( $tweetURL ) ) { return json_decode( $result ); } else { return false; } } protected static function twitter_status( $id ) { return self::twitter_fetch( 'http://twitter.com/statuses/show/' . ((int)$id) . '.json' ); } protected static function twitter_mine( ) { return self::twitter_fetch( 'http://twitter.com/statuses/user_timeline.json' ); } protected static function twitter_friend_tweets( $id ) { return self::twitter_fetch( 'http://twitter.com/statuses/user_timeline/'. urlencode( $id ) .'.json' ); } protected static function twitter_friends( ) { return self::twitter_fetch( 'http://twitter.com/statuses/friends.json' ); } } ?> <file_sep><?php class Lilliputian extends Plugin { /* public function action_plugin_activation( $file ) { if ( realpath( $file ) == __FILE__ ) { // establish our max id counter, but don't clobber // any existing value if ( ! Options::get( 'lilliputian__max' ) ){ Options::set( 'lilliputian__max', 0 ); } } } */ /* public function action_init() */ public function filter_rewrite_rules( $rules ) { if ( Options::get( 'lilliputian__service' ) == 'internal' ) { $redirect= RewriteRule::create_url_rule( '"r"/url', 'UserThemeHandler', 'redirect' ); $shorten= RewriteRule::create_url_rule( '"s"/url', 'UserThemeHandler', 'shorten' ); $rules[]= $redirect; $rules[]= $shorten; } return $rules; } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t('Configure'); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _('Configure') : $ui = new FormUI( strtolower( get_class( $this ) ) ); // present the user with a list of // URL shortening services $service= $ui->append( 'select', 'service', 'lilliputian__service', _t('The URL shortening service to use: ') ); $services= array(); $services['internal']= 'internal'; $list= Utils::glob( dirname(__FILE__) . '/*.helper.php' ); if ( count( $list ) > 0 ) { foreach ( $list as $item ) { $item= basename( $item, '.helper.php' ); $services[$item]= $item; } } $service->options= $services; if ( Options::get( 'lilliputian__service' ) == 'internal' ) { $secret= $ui->append( 'text', 'secret', 'lilliputian__secret', _t('The secret word that must be passed when generating short URLs. May be blank to disable this security feature.' ) ); } $ui->append( 'submit', 'save', _t('Save' ) ); $ui->out(); break; } } } public function action_post_update_content( $post, $old, $new ) { $service= Options::get('lilliputian__service'); if ( 'internal' != $service ) { include_once( dirname( __FILE__ ) . '/' . $service . '.helper.php' ); } $count= preg_match_all( '/href=[\'"]([^\'"]+)[\'"]/', $new, $urls ); if ( $count ) { $update= false; foreach ( $urls[1] as $url ) { // see if this URL is already stored if ( isset( $post->info->$url ) ) { continue; } if ( 'internal' == $service ) { $tiny= $this->internal_check( $url ); if ( ! $tiny ) { $tiny= $this->internal_shrink( $url ); } } else { $tiny= shrink( $url ); } $post->info->$url= $tiny; $update= true; } // update the list of links as needed if ( $update ) { $post->info->url_list= $urls[1]; $post->info->commit(); } } } public function filter_post_content_out( $content, $post ) { $urls= $post->info->url_list; if ( $urls ) { foreach( $urls as $url ) { $content= str_replace( $url, $post->info->$url, $content ); } } return $content; } /** * given a short URL, redirect to the corresponding long URL **/ public function action_handler_redirect( $vars ) { $shorturl= Site::get_url('habari') . '/r/' . substr( $vars['entire_match'], 2 ); $url= DB::get_value( 'SELECT name FROM {postinfo} WHERE value = ?', array( $shorturl ) ); if ( $url ) { Utils::redirect( $url ); } else { die ('Error'); } exit; } /** * given a long URL in a query string or HTTP POST, generate and * return a short URL **/ public function action_handler_shorten( $vars ) { $secret= Options::get( 'lilliputian__secret' ); list( $junk, $pass, $url )= explode( '/', $vars['entire_match'], 3 ); if ( ( $secret ) && ( $pass == $secret ) ) { $tiny= $this->internal_check( $url ); if ( ! $tiny ) { $tiny= $this->internal_shrink( $url ); $result= DB::query( 'INSERT INTO {postinfo} (post_id, name, value) VALUES (?, ?, ?)', array( 0, $url, $tiny ) ); } echo $tiny; die; } echo 'Go away'; die; } public function internal_check( $url ) { $check= DB::get_value( 'SELECT value FROM {postinfo} WHERE name=?', array( $url ) ); if ( $check ) { return $check; } } public function internal_shrink( $url ) { $max= Options::get( 'lilliputian__max' ) + 1; $shorturl = Site::get_url( 'habari' ) . '/r/' . base_convert($max, 10, 36); Options::set( 'lilliputian__max', $max ); return $shorturl; } } ?> <file_sep><?php class PasswdLogins extends Plugin { public function filter_plugin_config ( $actions, $plugin_id ) { $actions['configure'] = _t('Configure', 'passwdlogins'); return $actions; } public function action_plugin_ui_configure ( ) { // get the groups list for the drop-down $ugs = UserGroups::get_all(); $groups = array(); foreach ( $ugs as $group ) { $groups[ $group->name ] = $group->name; } // remove anonymous - that would be pointless unset( $groups['anonymous'] ); $ui = new FormUI('plugin_directory'); $ui->append( 'text', 'passwdfile', 'passwdlogins__file', _t( 'Passwd File', 'passwdlogins' ) ); $ui->append( 'checkbox', 'createusers', 'passwdlogins__create', _t( 'Create users on successful login', 'passwdlogins' ) ); $select = $ui->append( 'select', 'defaultgroup', 'passwdlogins__group', _t( 'Group to create new users in', 'passwdlogins' ) ); $select->default = 'authenticated'; // emulate $default until it actually works if ( $select->value == null ) { $select->value = $select->default; } $select->options = $groups; $ui->append( 'submit', 'save', _t( 'Save' ) ); $ui->out(); } public function filter_user_authenticate($user, $username, $password) { $passwdfile = Options::get('passwdlogins__file'); if ( !$passwdfile ) { EventLog::log( _t('No passwd file configured!'), 'err', 'passwdlogins', 'passwdlogins' ); return false; } if ( !file_exists( $passwdfile ) ) { EventLog::log( _t('Passwd file does not exist: %1$s', array( $passwdfile ) ), 'err', 'passwdlogins', 'passwdlogins' ); return false; } // go ahead and trim the user and password $username = trim( $username ); $password = trim( $password ); // blank usernames and passwords are not allowed if ( $username == '' || $password == '' ) { return false; } $users = $this->parse_htpasswd( $passwdfile ); if ( isset( $users[ $username ] ) ) { $crypt_pass = $users[ $username ]; if ( $crypt_pass{0} == '{' ) { // figure out the algorithm used for this password $algo = MultiByte::strtolower( MultiByte::substr( $crypt_pass, 1, MultiByte::strpos( $crypt_pass, '}', 1 ) - 1 ) ); $passok = false; switch ( $algo ) { case 'ssha': $hash = base64_decode( MultiByte::substr( $crypt_pass, 6 ) ); $passok = MultiByte::substr( $hash, 0, 20 ) == pack( "H*", sha1( $password . MultiByte::substr( $hash, 20 ) ) ); break; case 'sha': $passok = '{SHA}' . base64_encode( pack( "H*", sha1( $password ) ) ) == $crypt_pass; break; } } else { // it's plain crypt $passok = crypt( $password, MultiByte::substr( $crypt_pass, 0, CRYPT_SALT_LENGTH ) ) == $crypt_pass; } if ( $passok == true ) { return $this->get_user( $username ); } } // returning $user would continue the login check through other plugins and core - we want to force passwd logins return false; } public function parse_htpasswd ( $passwdfile ) { $lines = file( $passwdfile ); $users = array(); $i = 0; foreach ( $lines as $line ) { // if there is no :, assume this is a username with a newline if ( MultiByte::strpos( $line, ':' ) === false ) { // append the next line to it $line = $line . $lines[ $i + 1 ]; // unset the next line unset( $lines[ $i + 1 ] ); } list( $username, $password ) = explode( ':', $line ); // trim the username and password $username = trim( $username ); $password = trim( $password ); if ( $username == '' || $password == '' ) { continue; } $users[ $username ] = $password; $i++; } return $users; } private function get_user ( $username ) { // should we create users if they don't exist? default to false $create = Options::get( 'passwdlogins__create', false ); $group = Options::get( 'passwdlogins__group' ); $user = User::get_by_name( $username ); // if the user doesn't exist if ( $user == false ) { // do we want to create it? if ( $create == true ) { $user = User::create( array( 'username' => $username, 'password' => Utils::random_password( 200 ), ) ); // add them to the default group, if one has been selected - otherwise it'll just default to authenticated anyway if ( $group ) { $user->add_to_group( $group ); } return $user; } else { // don't create it, it doesn't exist, so fail return false; } } else { // the user already exists, return it return $user; } } } ?> <file_sep><hr class="hide" /> <div id="footer"> <div class="inside"> <p class="attributes"> <a title="Atom Feed for Posts" href="<?php URL::out( 'atom_feed', array( 'index' => '1' ) ); ?>">Entries Feed</a> <a title="Atom Feed for Comments" href="<?php URL::out( 'atom_feed_comments', array( 'page' => '1' ) ); ?>">Comments Feed</a> </p> </div> </div> <!-- / #footer --> <div id="live-search"> <div class="inside"> <div id="search"> <form id="sform" method="get" action="<?php URL::out( 'display_search' ); ?>"> <img src="<?php Site::out_url('theme'); ?>/images/search.gif" alt="Search:" /> <input type="text" id="q" value="<?php _e('Search'); ?>" name="criteria" size="15" /> </form> </div> </div> </div> <?php $theme->footer(); ?> </body> </html> <file_sep><!-- This file can be copied and modified in a theme directory --> <div id="laconicabox"> <ul> <?php foreach ($notices as $notice) : ?> <li> <img src="<?php echo htmlspecialchars( $notice->image_url ); ?>" alt="<?php echo urlencode( Options::get( 'laconica__username' )); ?>"> <?php echo $notice->text . ' @ ' . $notice->time; ?> </li> <?php endforeach; ?> </ul> <p><small>via <a href="http://<?php echo Options::get('laconica__svc'); ?>/index.php?action=showstream&amp;nickname=<?php echo urlencode( Options::get( 'laconica__username' )); ?>"><?php echo Options::get('laconica__svc'); ?></a></small></p> </div> <file_sep><h3>Pages</h3> <ul><?php foreach($content->menupages as $page) : ?> <li class="<?php echo $page->activeclass; ?> block-<?php echo Utils::slugify($content->title); ?>"><a href="<?php echo $page->permalink; ?>"><?php echo $page->title; ?></a></li> <?php endforeach; ?></ul> <file_sep> <li id="widget-audioscrobbler" class="widget"> <h3><?php _e('Listening', 'demorgan'); ?></h3> <p> <?php if ($track instanceof SimpleXMLElement) { printf('“<a href="%1$s">%2$s</a>” performed by %3$s', $track->url, $track->name, $track->artist); } else { echo $track; } ?> </p> </li> <file_sep><?php /** * ResurrectionTheme is a custom Theme class for teh Resurrection theme * * @package Habari */ /** * A custom theme for Resurrection output */ class GrayTheme extends Theme { /** * On theme activation, activate some default blocks */ public function action_theme_activated() { $blocks = $this->get_blocks('primary', '', $this); if(count($blocks) == 0) { $block = new Block(array( 'title' => _t('Posts'), 'type' => 'grayposts', )); $block->add_to_area('primary'); Session::notice(_t('Added default blocks to theme areas.')); } } /** * Add default output filters **/ public function action_init_theme() { // Apply Format::autop() to post content... Format::apply( 'autop', 'post_content_out' ); // Apply Format::autop() to comment content... Format::apply( 'autop', 'comment_content_out' ); // Apply Format::tag_and_list() to post tags... Format::apply( 'tag_and_list', 'post_tags_out' ); // Apply Format::nice_date() to post date... Format::apply( 'format_date', 'post_pubdate_out', '{F} {j}, {Y} {g}:{i}{a}' ); // Apply Format::more to post content... Plugins::register( array($this, 'more'), 'filter', 'post_content_out'); // Apply Format::search_highlight to post content... Format::apply( 'search_highlight', 'post_content_out' ); //Session::error('Sample error', 'sample'); } public function filter_post_pubdate_ago($pubdate) { $days_ago = round((HabariDateTime::date_create()->int - $pubdate->int) / 86400); return "{$days_ago} days ago"; } public function more($content, $post) { $more_text = 'Read the rest &#8594;'; $max_paragraphs = 1; $showmore = false; $matches = preg_split( '/<!--\s*more\s*-->/is', $content, 2, PREG_SPLIT_NO_EMPTY ); if ( count($matches) > 1 ) { $summary = $matches[0]; $remainder = $matches[1]; if(trim($remainder) != '') { $showmore = true; } } else { $ht = new HtmlTokenizer($content, false); $set = $ht->parse(); $stack = array(); $para = 0; $token = $set->current(); $summary = new HTMLTokenSet(false); $remainder = new HTMLTokenSet(false); $set->rewind(); for($token = $set->current(); $set->valid(); $token = $set->next() ) { if($token['type'] == HTMLTokenizer::NODE_TYPE_ELEMENT_OPEN) { $stack[$token['name']] = $token['name']; } if($para < $max_paragraphs) { $summary[] = $token; } if($para >= $max_paragraphs) { $remainder[] = $token; $showmore = true; } if($token['type'] == HTMLTokenizer::NODE_TYPE_ELEMENT_CLOSE) { if(isset($stack[$token['name']])) { while(end($stack) != $token['name']) { array_pop($stack); } array_pop($stack); } if(count($stack) == 0) { $para++; } } } } if ( $post->slug == Controller::get_var('slug') ) { $content = $summary . '<div id="more" class="moreanchor">'. 'Continues here &#8594;' .'</div>' . $remainder; } elseif( $showmore == true ) { $content = $summary . '<p class="more"><a href="' . $post->permalink . '#more">' . $more_text . '</a></p>'; } else { $content = $summary . $remainder; } return $content; } /** * Add additional template variables to the template output. */ public function action_add_template_vars($theme) { // Set an SEO-friendly page title $this->page_title = (isset($this->post) && ($this->request->display_entry || $this->request->display_page)) ? $this->post->title . ' - ' . Options::get( 'title' ) : Options::get( 'title' ) ; // Set the site title $this->site_title = Options::get('title'); // Set the YUI class for layout $this->yui_class = Options::get('yui_class', 'yui-t1'); $this->yui_id = Options::get('yui_id', 'doc'); $this->align_class = Options::get('align_class', 'doc-center'); if($this->yui_id == 'doc3') { $this->align_class = 'doc-center'; } /* // Make posts an instance of Posts if it's just one if($this->posts instanceof Post) { $this->posts = new Posts(array($this->posts)); $this->show_page_selector = false; } else { $this->show_page_selector = true; } */ // Add javascript support files Stack::add('template_header_javascript', Site::get_url('scripts', '/jquery.js') , 'jquery' ); // Add the stylesheets Stack::add('template_stylesheet', array('http://yui.yahooapis.com/2.8.1/build/reset-fonts-grids/reset-fonts-grids.css', 'screen,projection'), 'yahoo'); Stack::add('template_stylesheet', array(Site::get_url( 'theme', '/print.css' ) , 'print'), 'print'); Stack::add('template_stylesheet', array('@import url(http://fonts.googleapis.com/css?family=Vollkorn&subset=latin);' , 'screen,projection'), 'font', 'yahoo'); Stack::add('template_stylesheet', array(Site::get_url( 'theme', '/style.css' ) , 'screen,projection'), 'theme', 'yahoo'); } public function filter_submit_comment_form($result, $form) { var_dump($form->get_values()); return $result; } /** * Respond to the user selecting 'configure' on the themes page */ public function action_theme_ui() { $form = new FormUI( 'gray_theme' ); $form->append('fieldset', 'yui_fs', 'YUI Grid Settings'); $form->yui_fs->append( 'select', 'yui_id', 'yui_id', 'Page width:' ); $form->yui_id->options = array( 'doc' => _t('750px', 'gray'), 'doc2' => _t('950px', 'gray'), 'doc3' => _t('100%', 'gray'), 'doc4' => _t('974px', 'gray'), ); $form->yui_fs->append( 'select', 'yui_class', 'yui_class', 'Sidebar size and position:' ); $form->yui_class->options = array( 'yui-t1' => _t('160px on left', 'gray'), 'yui-t2' => _t('180px on left', 'gray'), 'yui-t3' => _t('300px on left', 'gray'), 'yui-t4' => _t('180px on right', 'gray'), 'yui-t5' => _t('240px on right', 'gray'), 'yui-t6' => _t('300px on right', 'gray'), ); $form->yui_fs->append( 'select', 'align_class', 'align_class', 'Page Alignment:' ); $form->align_class->options = array( 'doc-left' => _t('Left', 'gray'), 'doc-center' => _t('Centered', 'gray'), 'doc-right' => _t('Right', 'gray'), ); $form->append( 'submit', 'save', _t( 'Save' ) ); $form->set_option( 'success_message', _t( 'Configuration saved.', 'gray' ) ); $form->out(); } public function filter_block_list($block_list) { $block_list['grayposts'] = _t('Posts (From Gray)'); return $block_list; } public function action_block_content_grayposts($block, $theme) { $criteria = new SuperGlobal(array()); if ( User::identify()->loggedin ) { $criteria['status'] = isset( $_GET['preview'] ) ? Post::status( 'any' ) : Post::status( 'published' ); } else { $criteria['status'] = Post::status( 'published' ); } if($block->content_type != '') { $criteria['content_type'] = $block->content_type; if($block->content_type == 0) { unset($criteria['content_type']); } } if($block->limit != '') { $criteria['limit'] = $block->limit; } if($block->offset != '') { $criteria['offset'] = $block->offset; } if($block->tag != '') { $criteria['tag'] = $block->tag; } if($block->main) { $where_filters = Controller::get_handler()->handler_vars->filter_keys( $this->valid_filters ); if ( array_key_exists( 'tag', $where_filters ) ) { $where_filters['tag_slug'] = Utils::slugify($where_filters['tag']); unset( $where_filters['tag'] ); } $where_filters = Plugins::filter( 'template_where_filters', $where_filters ); $criteria = $criteria->merge($where_filters); } $block->posts = Posts::get($criteria); //$block->posts = Posts::get('limit=5&status=2&content_type=0'); $block->criteria = $criteria; } public function action_block_form_grayposts($form, $block) { $form->append('select', 'content_type', $block, 'Content Type:', array_flip(Post::list_active_post_types())); $form->append('text', 'limit', $block, 'Limit:'); $form->limit->add_validator('validate_range', 1, 999); $form->append('text', 'offset', $block, 'Offset:'); $form->offset->add_validator('validate_range', 0, 999); $form->append('text', 'tag', $block, 'Tag:'); $form->append('checkbox', 'main', $block, 'This block changes based on URL paramters.'); $form->append('submit', 'save', 'Save'); } public function filter_get_scopes($scopes) { /* $rules = RewriteRules::get_active(); $scopeid = 40000; foreach($rules as $rule) { $scope = new StdClass(); $scope->id = $scopeid++; $scope->name = $rule->name; $scope->priority = 15; $scope->criteria = array( array('request', $rule->name), ); $scopes[] = $scope; } */ return $scopes; } public function action_upgrade($oldversion) { Utils::debug('upgrade ' . $oldversion);die(); } } ?> <file_sep><h3>Twitter</h3> <ul> <?php foreach ( $content->tweets as $tweet ) : ?> <li> <?php echo $tweet->text . ' <small>@ ' . $tweet->time; ?></small> </li> <?php endforeach; ?> <li>via <a href="http://twitter.com/<?php echo urlencode( $content->username ); ?>">Twitter</a></li> </ul> <file_sep><?php $theme->display( 'header'); ?> <!-- single --> <div class="entry"> <div id="left-col"> <h2><?php echo $post->title_out; ?></h2> <p class="details"><?php echo $post->pubdate_out; ?> &bull; Posted by <?php echo $post->author->displayname; ?> &bull; <a href="<?php echo $post->permalink; ?>#comments"><?php echo $post->comments->approved->count; ?> <?php echo _n( 'Comment', 'Comments', $post->comments->approved->count ); ?></a></p> <?php echo $post->content_out; ?> <p class="bottom"> <?php if ( count( $post->tags ) ) { ?> <strong>Tags:</strong> <?php echo $post->tags_out; ?> <?php } ?> </p> <?php $theme->display ('comments'); ?> </div> <div id="right-col"> <?php $theme->display ( 'sidebar' ); ?> </div> </div> <!-- /single --> <?php $theme->display ('footer'); ?> <file_sep><?php include HABARI_PATH . '/system/admin/header.php'; ?> <div class="container"> <h2><?php _e( 'Manage Blogroll', 'blogroll' ); ?></h2> <p> <?php _e( 'Below you can view and edit blogroll links. You can also import links from an OPML file.', 'blogroll' ); ?> <?php printf( _t( 'Or you can <a href="%s">Publish a new Blogroll link</a>.', 'blogroll' ), URL::get( 'admin', 'page=blogroll_publish' ) ); ?> </p> </div> <form name="form_blogroll" enctype="multipart/form-data" id="form_blogroll" action="<?php URL::out('admin', 'page=blogroll_manage'); ?>" method="post"> <div class="pagesplitter"> <ul class="tabcontrol tabs"> <li class="import_opml_blogroll first" ><a href="#import_opml_blogroll" style="width: 125px;"><?php _e( 'Import/Export OPML', 'blogroll' ); ?></a></li><li class="bookmarklets_blogroll last"><a href="#bookmarklets_blogroll"><?php _e( 'Bookmarklets', 'blogroll' ); ?></a></li> </ul> <div id="import_opml_blogroll" class="splitter"> <div class="splitterinside publish"> <div class="container"> <h2><?php _e( 'Import', 'blogroll' ); ?></h2> <p><?php _e( 'Upload or enter the URL of the OPML file to import.', 'blogroll' ); ?></p> <div> <p><label for="opml_file" class="incontent"><?php _e( 'URL', 'blogroll' ); ?></label> <input type="text" id="opml_file" name="opml_file" size="100%" value="" class="styledformelement"></p> <p><input type="file" id="userfile" name="userfile" size="50%" value="" class="styledformelement"></p> </div> <p><input type="submit" id="import_opml" name="import_opml" value="<?php _e( 'Import', 'blogroll' ); ?>"></p> </div> <hr> <div class="container"> <h2><?php _e( 'Export', 'blogroll' ); ?></h2> <div class=""> <ul class="prepend-1"> <li><a href="<?php URL::out( 'blogroll_opml' ); ?>"><?php _e( 'Export as OPML 1.1', 'blogroll' ); ?></a></li> <li><p>Export as OPML 2.0 with ponies attached. OMG PONIES! (coming soon)</p></li> </ul> </div> </div> </div> </div> <div id="bookmarklets_blogroll" class="splitter"> <div class="splitterinside publish"> <div class="container"> <p><?php _e( 'Add the following "Bookmarklets" to your browsers bookmarks, for easy Blogrolling of your favourite sites.', 'blogroll' ); ?></p> <div> <ul class="prepend-1"> <li><a href="<?php printf( "javascript:location.href='%s?url='+encodeURIComponent(location.href)+'&name='+encodeURIComponent(document.title)", URL::get( 'admin', 'page=blogroll_publish' ) ); ?>"><?php _e ( 'Add to Blogroll', 'blogroll' ); ?></a></li> <li><a href="<?php printf( "javascript:location.href='%s?quick_link_bookmarklet='+encodeURIComponent(location.href)", URL::get( 'admin', 'page=blogroll_publish' ) ); ?>"><?php _e ( 'Quick Link Blogroll', 'blogroll' ); ?></a></li> </ul> </div> </div> </div> </div> </div> <div class="container"> <div> </div> <table id="post-data-published" width="100%" cellspacing="0"> <thead> <tr> <th align="right"> </th> <th align="left"><?php _e( 'Name', 'blogroll' ); ?></th> <th align="left"> </th> <th align="left"><?php _e( 'Owner', 'blogroll' ); ?></th> <th align="left"><?php _e( 'Description', 'blogroll' ); ?></th> <th align="center"> </th> </tr> </thead> <tr><td colspan="6" class="first last"> <a href="#" onclick="$('.blog_ids').attr('checked', 'checked');return false;"><?php _e('Check All', 'blogroll'); ?></a> | <a href="#" onclick="$('.blog_ids').attr('checked', '');return false;"><?php _e('Uncheck All', 'blogroll'); ?></a> </td></tr> <?php foreach ( Blogs::get() as $blog ) : ?> <tr> <td class="span-1 first"><input type="checkbox" class="blog_ids" name="blog_ids[]" value="<?php echo $blog->id; ?>"></td> <td class="span-4"><?php echo '<a href="' . $blog->url . '">' . Utils::truncate( $blog->name, 32, false ) . '</a>'; ?></td> <td class="span-1"><?php if ( $blog->feed ) : ?><a href="<?php echo $blog->feed; ?>"><img style="padding:0; margin:0 1em;" src="<?php echo $feed_icon; ?>"></a><?php endif; ?></td> <td class="span-4"><?php echo $blog->owner ?></td> <td class="span-10"><?php echo Utils::truncate( $blog->description, 128, false ); ?></td> <td class="span-2 last"> <a class="link_as_button" href="<?php URL::out('admin', 'page=blogroll_publish&id=' . $blog->id); ?>" title="Edit this entry"> <?php _e( 'Edit', 'blogroll' ); ?> </a> </td> </tr> <?php endforeach; ?> <tr><td colspan="6" class="first last"> <?php _e( 'Selected blogs: ', 'blogroll' ); ?>&nbsp;&nbsp;<select name="change" class="longselect"> <option value="delete"><?php _e( 'Delete', 'blogroll' ); ?></option> <option value="auto_update"><?php _e( 'Auto Update', 'blogroll' ); ?></option> </select> <input type="submit" name="do_update" value="<?php _e( 'Update', 'blogroll' ); ?>"> </td></tr> </table> </div> </form> <?php include HABARI_PATH . '/system/admin/footer.php'; ?> <file_sep><?php /** * Auto Keyword Generator * Version: 1.0 * Author: <NAME> <http://www.xvolter.com> * Copyright: Copyright (C) 2008, <NAME> * License: MIT License */ class AutoKeyword extends Plugin { /** * Return plugin information */ public function info() { return array( 'name' => 'AutoKeyword', 'version' => '1.0', 'url' => 'http://www.xvolter.com/project/autokeyword', 'author' => '<NAME>', 'authorurl' => 'http://www.xvolter.com/', 'license' => 'MIT', 'description' => 'Auto generate keywords for posts and pages.' ); } /** * Enable the ability for */ function action_update_check() { Update::add( 'AutoKeyword', '210D3BF6-AF6B-11DD-97B3-B85A56D89593', $this->info->version ); } /** * Add default options when plugin is activated */ public function action_plugin_activation( $file ) { if ( realpath( $file ) == __FILE__ ) { // language Options::set( 'autokeyword__lang', 'en' ); // single words Options::set( 'autokeyword__min_1word_length', '5' ); Options::set( 'autokeyword__min_1word_occur', '2' ); // two word phrases Options::set( 'autokeyword__min_2word_length', '3' ); Options::set( 'autokeyword__min_2phrase_length', '6' ); Options::set( 'autokeyword__min_2phrase_occur', '2' ); // three word phrases Options::set( 'autokeyword__min_3word_word_length', '3' ); Options::set( 'autokeyword__min_3phrase_length', '9' ); Options::set( 'autokeyword__min_3phrase_occur', '2' ); } } /** * Add configure tab to action list */ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) $actions[]= _t( 'Configure' ); return $actions; } /** * Create the configuration FromUI */ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t( 'Configure' ): $ui= new FormUI( strtolower( get_class( $this ) ) ); // add language selector $ui->append( 'select', 'lang', 'option:autokeyword__lang', _t( 'Language' ), array( // TODO: Get some more languages, // Please help me here thee who speakith other // languages :) 'en' => 'English' ) ); // add single word entries $ui->append( 'text', 'min_1word_length', 'option:autokeyword__min_1word_length', _t('Minimum length for one word keywords')); $ui->append( 'text', 'min_1word_occur', 'option:autokeyword__min_1word_occur', _t('Minimum occurance for one word keywords')); // add two word phrase entries $ui->append( 'text', 'min_2word_length', 'option:autokeyword__min_2word_length', _t('Minimum length for single words in two word phrases')); $ui->append( 'text', 'min_2phrase_length', 'option:autokeyword__min_2phrase_length', _t('Minimum length for entire two word phrase')); $ui->append( 'text', 'min_2phrase_occur', 'option:autokeyword__min_2phrase_occur', _t('Minimum occurance for entire two word phrase')); // add three word phrase entries $ui->append( 'text', 'min_3word_length', 'option:autokeyword__min_3word_length', _t('Minimum length for single words in three word phrases')); $ui->append( 'text', 'min_3phrase_length', 'option:autokeyword__min_3phrase_length', _t('Minimum length for entire three word phrase')); $ui->append( 'text', 'min_3phrase_occur', 'option:autokeyword__min_3phrase_occur', _t('Minimum occurance for entire three word phrase')); // misc $ui->append( 'submit', 'save', 'Save' ); $ui->on_success( array( $this, 'updated_config' ) ); $ui->out(); break; } } } /** * Save options */ public function updated_config( $ui ) { $ui->save(); return false; } /** * Change how we save project, client, and tasks * Get rid of unneeded items and add to info */ public function action_publish_post( &$post, &$form ) { // save post keywords $post->info->keywords = self::get_keywords( $post->content ); } /** * Get the keywords for a group of text * @param String content to process * @return String of keywords separated by commas (,) */ public static function get_keywords($content) { // pre process content $segments = self::pre_proccess( $content ); // return keywords in a more usable variable return implode(", ", // merge all keywords into one array array_merge( self::parse_words($segments), self::parse_2words($segments), self::parse_3words($segments) ) ); } /** * Turn a mass of words into a usable variable. */ private static function pre_proccess($content) { // remove HTML .. TODO: Process bolded words and headers $content = strip_tags( strtolower($content) ); // remove punctuation $punctuations = array( ',', ')', '(', '.', "'", '"', '<', '>', ';', '!', '?', '/', '-', '_', '[', ']', ':', '+', '=', '#', '$', '&quot;', '&copy;', '&gt;', '&lt;', chr(10), chr(13), chr(9)); $content = str_replace($punctuations, " ", $content); // replace wide gaps with smaller ones $content = preg_replace('/\s{2,}/si', " ", $content); return explode(" ", $content); } /** * Find commonly used words */ public static function parse_words( $segments ) { // load common words from language file $file = dirname(__FILE__) . "/words/" . Options::get('autokeyword__lang') . ".txt"; $common = file_exists($file) ? file( $file ) : array(); $keywords = array(); $min_word_length = Options::get('autokeyword__min_1word_length'); foreach( $segments as $word ) { $word = trim($word); if ( strlen($word) >= $min_word_length && !in_array($word, $common) && // skip common words completely !is_numeric($word) // dont process numbers as a keyword ) $keywords[] = $word; } return self::filter($keywords, Options::get('autokeyword__min_1word_occur')); } /** * Finds two word phrases */ public static function parse_2words( $segments ) { $keywords = array(); $min_word_length = Options::get('autokeyword__min_2word_length'); $min_phrase_length = Options::get('autokeyword__min_2phrase_length'); for ($i=0; $i < count( $segments ) - 1; $i++) { $var1 = trim( $segments[ $i ] ); $var2 = trim( $segments[ $i+1 ] ); $var3 = "$var1 $var2"; if ( strlen($var1) >= $min_word_length && strlen($var2) >= $min_word_length && strlen($var3) >= $min_phrase_length ) $keywords[] = $var3; } return self::filter($keywords, Options::get('autokeyword__min_2phrase_occur')); } /** * Find three word phrases */ public static function parse_3words( $segments ) { $keywords = array(); $min_word_length = Options::get('autokeyword__min_3word_word_length'); $min_phrase_length = Options::get('autokeyword__min_3phrase_length'); for ($i=0; $i < count( $segments ) - 2; $i++) { $var1 = trim( $segments[ $i ] ); $var2 = trim( $segments[ $i+1 ] ); $var3 = trim( $segments[ $i+2 ] ); $var4 = "$var1 $var2 $var3"; if ( strlen($var1) >= $min_word_length && strlen($var2) >= $min_word_length && strlen($var3) >= $min_word_length && strlen($var4) >= $min_phrase_length ) $keywords[] = $var4; } return self::filter( $keywords, Options::get('autokeyword__min_3phrase_occur') ); } /** * Process arrays of words with counts and * returns the words that match the occurance * requirement, then sort the words. */ private static function filter($array, $min) { $array = array_count_values($array); $filtered = array(); foreach ($array as $word => $occured) if ($occured >= $min) $filtered[] = $word; arsort( $filtered ); return $filtered; } } ?> <file_sep>var RateIt = { init: function() { $('.rateit a').click(function(e){ var stars = $(this).parent().parent(); var id = stars.attr('id').split('-'); if (id[0] == 'rateit') { RateIt.rating(id[2], $(this).text()); } return false; }); }, rating: function(post_id, rating) { $('#rateit-loading-' + post_id).show(); var query= {}; query['post_id'] = post_id; query['rating'] = rating; $.post(rateit_habari_url + '/rateit/rating', query, function(result) { $('#rateit-loading-' + post_id).hide(); if (result.error == 0) { $('#rateit-' + post_id).html(result.html); } alert(result.message); }, 'json'); } } $(document).ready(function(){ RateIt.init(); }); <file_sep><?php if (count($years) > 0) { echo '<ul id="breezy-chronology-archive">'; foreach ($years as $year => $months) { printf('<li class="year"><a href="%1$s" rel="archives">%2$s</a><ul class="breezy-yearly-archive">', URL::get('display_entries_by_date', array('year' => $year)), $year); if ($show_monthly_post_count) { foreach ($months as $month => $count) { if ($count > 0) { printf('<li class="month"><a href="%1$s" rel="archives">%2$s</a> <span class="post-count" title="%3$s">%4$d</span></li>', URL::get('display_entries_by_date', array('year' => $year, 'month' => $month)), Utils::locale_date($month_format, mktime(0,0,0,$month,1)), sprintf(_n('%1$d Post', '%1$d Posts', $count, $this->class_name), $count), $count); } else { printf('<li class="month"><span>%1$s</span> <span class="post-count" title="%2$s">%3$d</span></li>', Utils::locale_date($month_format, mktime(0,0,0,$month,1)), sprintf(_n('%1$d Post', '%1$d Posts', $count, $this->class_name), $count), $count); } } } else { foreach ($months as $month => $count) { if ($count > 0) { printf('<li class="month"><a href="%1$s" rel="archives">%2$s</a></li>', URL::get('display_entries_by_date', array('year' => $year, 'month' => $month)), Utils::locale_date($month_format, mktime(0,0,0,$month,1))); } else { printf('<li class="month"><span>%1$s</span></li>', Utils::locale_date($month_format, mktime(0,0,0,$month,1))); } } } echo '</ul></li>'; } echo '</ul>'; } ?><file_sep><div class="amazon-item"> <div class="amazon-image" style="width: 160px; float: left;"> <a href="<?php echo (string)$item->DetailPageURL; ?>"><img src="<?php echo (string)$item->MediumImage->URL; ?>" style="width: <?php echo (int)$xml->Items->Item->MediumImage->Width; ?>; height: <?php echo (int)$item->MediumImage->Height; ?>px; border: 0px;" alt="<?php echo (string)$item->ItemAttributes->Title; ?>" /></a> </div> <div class="amazon-detail" style="float: left; margin-left: 8px;"> <div class="amazon-title"><a href="<?php echo (string)$xml->Items->Item->DetailPageURL; ?>"><?php echo (string)$item->ItemAttributes->Title; ?></a></div> <?php if ( isset( $item->ItemAttributes->Creator[0] ) ) echo (string)$item->ItemAttributes->Creator[0] . '<br />'; if ( isset( $item->ItemAttributes->Publisher ) ) echo (string)$item->ItemAttributes->Publisher . '<br />'; if ( isset( $item->SalesRank ) ) echo _t('Sales Rank: ') . (int)$item->SalesRank . '<br />'; if ( isset( $item->CustomerReviews->AverageRating ) ) { echo '<br />'; echo _t('Average Rating: ') . $this->ratingToStarImage( (float)$item->CustomerReviews->AverageRating ) . '<br />'; for ( $i = 0; $i < 5; $i++ ) { if ( !isset( $item->CustomerReviews->Review[$i]) ) break; echo $this->ratingToStarImage( (int)$item->CustomerReviews->Review[$i]->Rating ) . ' ' . (string)$item->CustomerReviews->Review[$i]->Summary . '<br />'; } } ?> </div> <div class="amazon-clear" style="clear: both;"></div> </div><file_sep><?php define( 'IMPORT_BATCH', 100 ); /** * Habari Importer - Imports data from another Habari database * */ class HabariImport extends Plugin implements Importer { private $supported_importers = array(); const TYPE_MYSQL = 0; const TYPE_SQLITE = 1; const TYPE_PGSQL = 2; /** * Return plugin metadata for this plugin * * @return array Plugin metadata */ public function info() { return array( 'name' => 'Habari Importer', 'version' => '0.3', 'url' => 'http://habariproject.org/', 'author' => 'The Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Import Habari 0.6-0.7 database.', 'copyright' => '2010' ); } /** * Initialize plugin. * Set the supported importers. **/ public function action_init() { $this->supported_importers = array( _t( 'Habari Database' ) ); } /** * Return a list of names of things that this importer imports * * @return array List of importables. */ public function filter_import_names( $import_names ) { return array_merge( $import_names, $this->supported_importers ); } /** * Plugin filter that supplies the UI for the Habari importer * * @param string $stageoutput The output stage UI * @param string $import_name The name of the selected importer * @param string $stage The stage of the import in progress * @param string $step The step of the stage in progress * @return output for this stage of the import */ public function filter_import_stage( $stageoutput, $import_name, $stage, $step ) { // Only act on this filter if the import_name is one we handle... if( !in_array( $import_name, $this->supported_importers ) ) { // Must return $stageoutput as it may contain the stage HTML of another importer return $stageoutput; } $inputs = array(); // Validate input from various stages... switch( $stage ) { case 1: if( count( $_POST ) ) { $inputs = $_POST->filter_keys( 'db_type', 'db_name','db_host','db_user','db_pass','db_prefix', 'tag_import' ); foreach ( $inputs as $key => $value ) { $$key = $value; } $connect_string = $this->get_connect_string( $db_type, $db_host, $db_name ); if( $this->hab_connect( $connect_string, $db_user, $db_pass, $db_prefix ) ) { $stage = 2; } else { $inputs['warning']= _t( 'Could not connect to the Habari database using the values supplied. Please correct them and try again.' ); } } break; } // Based on the stage of the import we're on, do different things... switch( $stage ) { case 1: default: $output = $this->stage1( $inputs ); break; case 2: $output = $this->stage2( $inputs ); } return $output; } /** * Create the UI for stage one of the import process * * @param array $inputs Inputs received via $_POST to the importer * @return string The UI for the first stage of the import process */ private function stage1( $inputs ) { $default_values = array( 'db_type' => self::TYPE_MYSQL, 'db_name' => '', 'db_host' => 'localhost', 'db_user' => '', 'db_pass' => '', 'db_prefix' => 'habari_', 'warning' => '', 'tag_import' => 1, ); $inputs = array_merge( $default_values, $inputs ); extract( $inputs ); if( $warning != '' ) { $warning = "<p class=\"warning\">{$warning}</p>"; } $output = <<< HAB_IMPORT_STAGE1 <p>Habari will attempt to import from another Habari Database.</p> {$warning} <p>Please provide the connection details for an existing Habari database:</p> <div class="item clear"> <span class="pct25"><label for="db_type">Database Type</label></span> <span> <input type="radio" name="db_type" value="0" tab index="1" checked />MySQL <input type="radio" name="db_type" value="1" tab index="2" />SQLite <input type="radio" name="db_type" value="2" tab index="3" />PostgreSQL </span> </div> <div class="item clear"> <span class="pct25"><label for="db_name">Database Name</label></span><span class="pct40"><input type="text" name="db_name" value="{$db_name}" tab index="4"></span> </div> <div class="item clear"> <span class="pct25"><label for="db_host">Database Host</label></span><span class="pct40"><input type="text" name="db_host" value="{$db_host}" tab index="5"></span> </div> <div class="item clear"> <span class="pct25"><label for="db_user">Database User</label></span><span class="pct40"><input type="text" name="db_user" value="{$db_user}" tab index="6"></span> </div> <div class="item clear"> <span class="pct25"><label for="db_pass">Database Password</label></span><span class="pct40"><input type="password" name="db_pass" value="{$db_pass}" tab index="7"></span> </div> <div class="item clear"> <span class="pct25"><label for="db_prefix">Table Prefix</label></span><span class="pct40"><input type="text" name="db_prefix" value="{$db_prefix}" tab index="8"></span> </div> <div class="item clear"> <span class="pct25"><label for="tag_import">Import Tags</label></span><span class="pct40"><input type="checkbox" name="tag_import" value="1" checked></span> </div> <div class="clear"></div> <input type="hidden" name="stage" value="1"> </div> <div <div class="container transparent" <input type="submit" class="button" name="import" value="Import" /> </div> HAB_IMPORT_STAGE1; return $output; } /** * Create the UI for stage two of the import process * This stage kicks off the ajax import. * * @param array $inputs Inputs received via $_POST to the importer * @return string The UI for the second stage of the import process */ private function stage2( $inputs ) { $inputs = $inputs->filter_keys( 'db_type', 'db_name','db_host','db_user','db_pass','db_prefix', 'tag_import' ); foreach ( $inputs as $key => $value ) { $$key = $value; } if ( ! isset( $tag_import ) ) { $tag_import = 0; } $ajax_url = URL::get( 'auth_ajax', array( 'context' => 'hab_import_users' ) ); EventLog::log( sprintf( _t('Starting import from "%s"'), $db_name ) ); Options::set( 'import_errors', array() ); $vars = Utils::addslashes( array( 'host' => $db_host, 'name' => $db_name, 'user' => $db_user, 'pass' => $inputs['db_pass'], 'prefix' => $db_prefix ) ); $output = <<< HAB_IMPORT_STAGE2 <p>Import In Progress</p> <div id="import_progress">Starting Import...</div> <script type="text/javascript"> // A lot of ajax stuff goes here. $( document ).ready( function(){ $( '#import_progress' ).load( "{$ajax_url}", { db_type: "{$db_type}", db_host: "{$vars['host']}", db_name: "{$vars['name']}", db_user: "{$vars['user']}", db_pass: "{$vars['pass']}", db_prefix: "{$vars['prefix']}", tag_import: "{$tag_import}", userindex: 0 } ); } ); </script> HAB_IMPORT_STAGE2; return $output; } /** * Attempt to connect to the Habari database * * @param string $connect_string The connection string of the Habari database * @param string $db_user The user of the database * @param string $db_pass The user's password for the database * @param string $db_prefix The table prefix in the database * @return mixed false on failure, DatabseConnection on success */ private function hab_connect( $connect_string, $db_user, $db_pass ) { // Connect to the database or return false try { $db = DatabaseConnection::ConnectionFactory( $connect_string );; $db->connect( $connect_string, $db_user, $db_pass ); return $db; } catch( Exception $e ) { return false; } } private function get_connect_string( $db_type, $db_host, $db_name ) { switch ( $db_type ) { case self::TYPE_MYSQL: $connect_string = "mysql:host={$db_host};dbname={$db_name}"; break; case self::TYPE_SQLITE: $connect_string = "sqlite:{$db_name}"; break; case self::TYPE_PGSQL: $connect_string = "pgsql:host={$db_host} dbname={$db_name}"; break; } return $connect_string; } /** * The plugin sink for the auth_ajax_hab_import_posts hook. * Responds via authenticated ajax to requests for post importing. * * @param AjaxHandler $handler The handler that handled the request, contains $_POST info */ public function action_auth_ajax_hab_import_posts( $handler ) { $inputs = $_POST->filter_keys( 'db_type', 'db_name','db_host','db_user','db_pass','db_prefix','postindex', 'tag_import' ); foreach ( $inputs as $key => $value ) { $$key = $value; } if ( ! isset( $tag_import ) ) { $tag_import = 0; } $connect_string = $this->get_connect_string( $db_type, $db_host, $db_name ); $db = $this->hab_connect( $connect_string, $db_user, $db_pass ); if( $db ) { DB::begin_transaction(); $old_db_version = (int)$db->get_value( "SELECT value FROM {$db_prefix}options WHERE name = ?", array( 'db_version' ) ); $postcount = $db->get_value( "SELECT count( id ) FROM {$db_prefix}posts;" ); $min = $postindex * IMPORT_BATCH + ( $postindex == 0 ? 0 : 1 ); $max = min( ( $postindex + 1 ) * IMPORT_BATCH, $postcount ); $user_map = array(); $user_info = DB::get_results( "SELECT user_id, value FROM {userinfo} WHERE name= 'old_id';" ); foreach( $user_info as $info ) { $user_map[$info->value]= $info->user_id; } echo "<p>Importing posts {$min}-{$max} of {$postcount}.</p>"; $posts = $db->get_results( " SELECT content, id, title, slug, user_id, guid, pubdate, updated, modified, status, content_type FROM {$db_prefix}posts ORDER BY id DESC LIMIT {$min}, " . IMPORT_BATCH , array(), 'Post' ); $post_map = DB::get_column( "SELECT value FROM {postinfo} WHERE name='old_id';"); foreach( $posts as $post ) { if(in_array($post->id, $post_map)) { continue; } if ($tag_import == 1 ) { // Import tags if( $old_db_version < 3749 ) { $tags = $db->get_column( "SELECT tag_text FROM {$db_prefix}tags INNER JOIN {$db_prefix}tag2post ON {$db_prefix}tags.id = {$db_prefix}tag2post.tag_id WHERE post_id = {$post->id}" ); } else { $tags = $db->get_column( "SELECT term_display FROM {$db_prefix}terms INNER JOIN {$db_prefix}object_terms ON {$db_prefix}terms.id = {$db_prefix}object_terms.term_id WHERE object_id = ? AND object_type_id = ?", array( $post->id, Vocabulary::object_type_id( 'post' ) ) ); } } else { $tags = array(); } $tags = implode( ',', $tags ); $post_array = $post->to_array(); $p = new Post( $post_array ); $p->slug = $post->slug; if(isset($user_map[$p->user_id])) { $p->user_id = $user_map[$p->user_id]; } else { $errors = Options::get('import_errors'); $errors[] = _t('Post author id %s was not found in the external database, assigning post "%s" (external post id #%d) to current user.', array($p->user_id, $p->title,$post_array['id']) ); Options::set('import_errors', $errors); $p->user_id = User::identify()->id; } $p->guid = $p->guid; // Looks fishy, but actually causes the guid to be set. $p->tags = $tags; $infos = $db->get_results("SELECT name, value, type FROM {$db_prefix}postinfo WHERE post_id = ?", array( $post_array['id'] ) ); $p->info->old_id = $post_array['id']; // Store the old post id in the post_info table for later try { $p->insert(); $p->updated = $post_array['updated']; $p->update(); foreach ( $infos as $info ) { $fields = $info->get_url_args(); $fields['post_id'] = $p->id; DB::insert( DB::table( 'postinfo'), $fields ); } } catch( Exception $e ) { EventLog::log($e->getMessage(), 'err', null, null, print_r(array($p, $e), 1)); Session::error( $e->getMessage() ); $errors = Options::get('import_errors'); $errors[] = $p->title . ' : ' . $e->getMessage(); Options::set('import_errors', $errors); } } if( DB::in_transaction() ) DB::commit(); if( $max < $postcount ) { $ajax_url = URL::get( 'auth_ajax', array( 'context' => 'hab_import_posts' ) ); $postindex++; $vars = Utils::addslashes( array( 'host' => $db_host, 'name' => $db_name, 'user' => $db_user, 'pass' => $db_pass, 'prefix' => $db_prefix ) ); echo <<< HAB_IMPORT_POSTS <script type="text/javascript"> $( '#import_progress' ).load( "{$ajax_url}", { db_type: "{$db_type}", db_host: "{$vars['host']}", db_name: "{$vars['name']}", db_user: "{$vars['user']}", db_pass: "{$vars['pass']}", db_prefix: "{$vars['prefix']}", tag_import: "{$tag_import}", postindex: {$postindex} } ); </script> HAB_IMPORT_POSTS; } else { $ajax_url = URL::get( 'auth_ajax', array( 'context' => 'hab_import_comments' ) ); $vars = Utils::addslashes( array( 'host' => $db_host, 'name' => $db_name, 'user' => $db_user, 'pass' => $db_pass, 'prefix' => $db_prefix ) ); echo <<< HAB_IMPORT_COMMENTS <script type="text/javascript"> $( '#import_progress' ).load( "{$ajax_url}", { db_type: "{$db_type}", db_host: "{$vars['host']}", db_name: "{$vars['name']}", db_user: "{$vars['user']}", db_pass: "{$vars['pass']}", db_prefix: "{$vars['prefix']}", tag_import: "{$tag_import}", commentindex: 0 } ); </script> HAB_IMPORT_COMMENTS; } } else { EventLog::log(sprintf(_t('Failed to import from "%s"'), $db_name), 'crit'); Session::error( $e->getMessage() ); echo '<p>'._t( 'The database connection details have failed to connect.' ).'</p>'; } } /** * The plugin sink for the auth_ajax_wp_import_posts hook. * Responds via authenticated ajax to requests for post importing. * * @param mixed $handler * @return */ public function action_auth_ajax_hab_import_users( $handler ) { $inputs = $_POST->filter_keys( 'db_type', 'db_name','db_host','db_user','db_pass','db_prefix','userindex', 'tag_import' ); foreach ( $inputs as $key => $value ) { $$key = $value; } $connect_string = $this->get_connect_string( $db_type, $db_host, $db_name ); $db = $this->hab_connect( $connect_string, $db_user, $db_pass ); if( $db ) { DB::begin_transaction(); $new_users = $db->get_results( " SELECT username, password, email, {$db_prefix}users.id as old_id FROM {$db_prefix}users INNER JOIN {$db_prefix}posts ON {$db_prefix}posts.user_id = {$db_prefix}users.id GROUP BY {$db_prefix}users.id ", array(), 'User' ); $usercount = 0; _e('<p>Importing users...</p>'); foreach($new_users as $user) { $habari_user = User::get_by_name($user->username); // If username exists if($habari_user instanceof User) { $habari_user->info->old_id = $user->old_id; $habari_user->update(); } else { try { $user->info->old_id = $user->old_id; // This should probably remain commented until we implement ACL more, // or any imported user will be able to log in and edit stuff //$user->password = <PASSWORD>}' . $user->password; $user->exclude_fields( array( 'old_id' ) ); $user->insert(); $usercount++; } catch( Exception $e ) { EventLog::log($e->getMessage(), 'err', null, null, print_r(array($user, $e), 1)); Session::error( $e->getMessage() ); $errors = Options::get('import_errors'); $errors[] = $user->username . ' : ' . $e->getMessage(); Options::set('import_errors', $errors); } } } if( DB::in_transaction()) DB::commit(); $ajax_url = URL::get( 'auth_ajax', array( 'context' => 'hab_import_posts' ) ); $vars = Utils::addslashes( array( 'type' => $db_type, 'host' => $db_host, 'name' => $db_name, 'user' => $db_user, 'pass' => $db_<PASSWORD>, 'prefix' => $db_prefix ) ); echo <<< HAB_IMPORT_POSTS <script type="text/javascript"> // A lot of ajax stuff goes here. $( document ).ready( function(){ $( '#import_progress' ).load( "{$ajax_url}", { db_type: "{$db_type}", db_host: "{$vars['host']}", db_name: "{$vars['name']}", db_user: "{$vars['user']}", db_pass: "{$vars['pass']}", db_prefix: "{$vars['prefix']}", tag_import: "{$tag_import}", postindex: 0 } ); } ); </script> HAB_IMPORT_POSTS; } else { EventLog::log(sprintf(_t('Failed to import from "%s"'), $db_name), 'crit'); Session::error( $e->getMessage() ); echo '<p>'._t( 'Failed to connect using the given database connection details.' ).'</p>'; } } /** * The plugin sink for the auth_ajax_hab_import_comments hook. * Responds via authenticated ajax to requests for comment importing. * * @param AjaxHandler $handler The handler that handled the request, contains $_POST info */ public function action_auth_ajax_hab_import_comments( $handler ) { $inputs = $_POST->filter_keys( 'db_type', 'db_name','db_host','db_user','db_pass','db_prefix','commentindex', 'tag_import' ); foreach ( $inputs as $key => $value ) { $$key = $value; } $connect_string = $this->get_connect_string( $db_type, $db_host, $db_name ); $db = $this->hab_connect( $connect_string, $db_user, $db_pass ); if( $db ) { DB::begin_transaction(); $commentcount = $db->get_value( "SELECT count( id ) FROM {$db_prefix}comments;" ); $min = $commentindex * IMPORT_BATCH + 1; $max = min( ( $commentindex + 1 ) * IMPORT_BATCH, $commentcount ); echo "<p>Importing comments {$min}-{$max} of {$commentcount}.</p>"; $post_info = DB::get_results( "SELECT post_id, value FROM {postinfo} WHERE name= 'old_id';" ); foreach( $post_info as $info ) { $post_map[$info->value] = $info->post_id; } $comments = $db->get_results( " SELECT c.id, c.content, c.name, c.email, c.url, c.ip, c.status, c.date, c.type, c.post_id as old_post_id FROM {$db_prefix}comments c INNER JOIN {$db_prefix}posts on {$db_prefix}posts.id = c.post_id LIMIT {$min}, " . IMPORT_BATCH , array(), 'Comment' ); foreach( $comments as $comment ) { $carray = $comment->to_array(); if( isset( $post_map[$carray['old_post_id']] ) ) { $carray['post_id']= $post_map[$carray['old_post_id']]; unset( $carray['old_post_id'] ); $c = new Comment( $carray ); $infos = $db->get_results("SELECT name, value, type FROM {$db_prefix}commentinfo WHERE comment_id = ?", array( $carray['id'] ) ); try{ $c->insert(); foreach ( $infos as $info ) { $fields = $info->get_url_args(); $fields['comment_id'] = $c->id; DB::insert( DB::table( 'commentinfo'), $fields ); } } catch( Exception $e ) { EventLog::log($e->getMessage(), 'err', null, null, print_r(array($c, $e), 1)); Session::error( $e->getMessage() ); $errors = Options::get('import_errors'); $errors[] = $e->getMessage(); Options::set('import_errors', $errors); } } } if( DB::in_transaction() ) DB::commit(); if( $max < $commentcount ) { $ajax_url = URL::get( 'auth_ajax', array( 'context' => 'hab_import_comments' ) ); $commentindex++; $vars = Utils::addslashes( array( 'host' => $db_host, 'name' => $db_name, 'user' => $db_user, 'pass' => $db_pass, 'prefix' => $db_prefix ) ); echo <<< HAB_IMPORT_COMMENTS1 <script type="text/javascript"> $( '#import_progress' ).load( "{$ajax_url}", { db_type: "{$db_type}", db_host: "{$vars['host']}", db_name: "{$vars['name']}", db_user: "{$vars['user']}", db_pass: "{$vars['<PASSWORD>']}", db_prefix: "{$vars['prefix']}", tag_import: "{$tag_import}", commentindex: {$commentindex} } ); </script> HAB_IMPORT_COMMENTS1; } else { EventLog::log('Import complete from "'. $db_name .'"'); echo '<p>' . _t( 'Import is complete.' ) . '</p>'; $errors = Options::get('import_errors'); if(count($errors) > 0 ) { echo '<p>' . _t( 'There were errors during import:' ) . '</p>'; echo '<ul>'; foreach($errors as $error) { echo '<li>' . $error . '</li>'; } echo '</ul>'; } } } else { EventLog::log(sprintf(_t('Failed to import from "%s"'), $db_name), 'crit'); Session::error( $e->getMessage() ); echo '<p>'._t( 'Failed to connect using the given database connection details.' ).'</p>'; } } } ?> <file_sep><!-- comments --> <?php // Do not delete these lines if ( ! defined('HABARI_PATH' ) ) { die( _t('Please do not load this page directly. Thanks!') ); } ?> <div id="comments"> <h3 id="responses"><?php echo $post->comments->moderated->count; ?> Responses to &lsquo;<?php echo $post->title; ?>&rsquo;</h4> <p class="comment-feed"><a href="<?php echo $post->comment_feed_link; ?>">Atom feed for this entry.</a></p> <ol> <?php if ($post->comments->moderated->count) { $comment_count = 0; foreach ($post->comments->moderated as $comment) { ?> <li> <span id="count"><?php $comment_count++; echo $comment_count; ?></span> <h6><a href="<?php echo $comment->url; ?>" rel="external" target="_blank"><?php echo $comment->name; ?></a><span> // <?php echo $comment->date; ?><?php if ( $comment->status == Comment::STATUS_UNAPPROVED ) : ?> (In moderation)<?php endif; ?></span></h6> <div class="comment-content"> <?php echo $comment->content_out; ?> </div> </li> <?php } } else { ?> <li id="no-comments">There are currently no comments.</li> <?php } ?> </ol> <h3 id="replay">Leave a Reply</h3> <form action="<?php URL::out( 'submit_feedback', array( 'id' => $post->id ) ); ?>" method="post" id="commentform"> <div id="comment-details"> <p> <input type="text" name="name" id="name" value="<?php echo $commenter_name; ?>" size="22" tabindex="1"> <label for="name"><strong><?php _e('Name'); ?></strong><?php if (Options::get('comments_require_id') == 1) : ?> *Required<?php endif; ?></label> </p> <p> <input type="text" name="email" id="email" value="<?php echo $commenter_email; ?>" size="22" tabindex="2"> <label for="email"><strong><?php _e('Mail'); ?></strong> (will not be published)</small><span class="required"><?php if (Options::get('comments_require_id') == 1) : ?> *Required<?php endif; ?></span></label> </p> <p> <input type="text" name="url" id="url" value="<?php echo $commenter_url; ?>" size="22" tabindex="3"> <label for="url"><strong><?php _e('Website'); ?></strong></label> </p> </div> <p><textarea name="content" id="content" cols="100" rows="10" tabindex="4"><?php echo $commenter_content; ?></textarea></p> <p><input name="submit" type="submit" id="btn" tabindex="5" value="Submit"></p> </form> </div> <!-- /comments --> <file_sep><div id="post-<?php echo $content->id; ?>" class="entry <?php echo $content->statusname; ?>"> <div class="entry-head"> <h2 class="entry-title"><a href="<?php echo $content->permalink; ?>" title="<?php echo $content->title; ?>"><?php echo $content->title_out; ?></a></h2> </div> </div><file_sep><?php class SimpleGallery extends Plugin { function __get( $name ) { switch ($name) { case 'base': $base = Options::get('simplegallery_base'); if ( null == $base ) { $base = 'gallery'; } return $base; default: return NULL; } } /** * Do some checking and setting up. */ public function action_plugin_activation( $file ) { // Don't bother loading if the gd library isn't active if ( !function_exists( 'imagecreatefromjpeg' ) ) { Session::error( _t( "Simple Gallery activation failed. PHP has not loaded the gd imaging library." ) ); Plugins::deactivate_plugin( __FILE__ ); } else { /* $this->silo = new HabariSilo(); $this->silo->action_init(); $this->silo->mkdir('simplegallery'); */ } } /** * Add the necessary template and create the silo to access files and directories * **/ function action_init() { $this->add_template( 'simplegallery', dirname(__FILE__) . '/simplegallery.php' ); $this->silo = new HabariSilo(); $this->silo->action_init(); } public function filter_rewrite_rules( $rules ) { $rules[]= new RewriteRule( array( 'name' => 'simplegallery', 'parse_regex' => '%^' . $this->base . '(?:/?$|/(?P<gallerypath>.*))/?$%i', 'build_str' => $this->base . '/({$gallerypath})', 'handler' => 'PluginHandler', 'action' => 'display_gallery', 'priority' => 6, 'is_active' => 1, 'description' => 'Respond to requests for the simple gallery.', 'parameters' => serialize( array( 'require_match' => array('SimpleGallery', 'rewrite_match_gallery') ) ) ) ); return $rules; } /** * Check the requested gallery exists * @param RewriteRule $rule The matched rewrite rule * @param string The URL stub requested * @param array $params Some stuff **/ public static function rewrite_match_gallery( $rule, $stub, $params ) { // TODO It would be better to use the silo, but there's no way to check if a path is valid // $silo->get_dir() always returns at least an empty array, even for invalid paths $base = Site::get_dir('user') . '/files/simplegallery/'; // Strip the base URL from the front of the stub, and add it to the base to get the full path. $sg = new SimpleGallery(); $path = $base . substr($stub, strlen($sg->base)); return file_exists($path); } public function action_plugin_act_display_gallery( $handler ) { $gallery_path = $handler->handler_vars['gallerypath']; // Check if it's an image file is being requested $image = $this->silo->silo_get('simplegallery/' . $gallery_path); if ( $image && in_array($image->filetype, array('image_gif', 'image_png', 'image_jpeg') ) ) { header('Content-type: ' . $image->filetype); echo $image->content; exit; } // It must be a directory $assets = $this->silo->silo_dir('simplegallery/' . $gallery_path); $theme = Controller::get_handler()->theme; $theme->css = $this->get_url() . '/simplegallery.css'; $dirs = array(); $images = array(); if ( 0 != count($assets) ) { foreach ($assets as $asset) { // Need to decode twice to keep the /, because URL::get() callse RewriteRule::build() which urlencodes. $asset->url = urldecode(urldecode( URL::get( 'simplegallery', array( 'gallerypath' => $gallery_path . '/'. ($asset->title) ) ) )); $asset->pretty_title = $this->pretty_title($asset->title); if ( $asset->is_dir ) { $dirs[] = $asset; } else if ( in_array($asset->filetype, array('image_gif', 'image_png', 'image_jpeg') ) ) { $images[] = $asset; } } } // Make a breadcrumb array // TODO Just horrible. There must be a nicer way to do this. $breadcrumbs = array($this->base); if ( '' != $gallery_path ) { $breadcrumbs = array_merge($breadcrumbs, explode('/', trim($this->pretty_title($gallery_path), '/'))); } $theme->breadcrumbs = $breadcrumbs; $theme->title = $breadcrumbs[count($breadcrumbs) - 1]; $theme->dirs = $dirs; $theme->images = $images; return $theme->display('simplegallery'); } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t( 'Configure' ); } return $actions; } /** * Respond to the user selecting an action on the plugin page * * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook */ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case 'Configure' : $form = new FormUI( 'simplegallery' ); $form->append( 'text', 'base', 'option:simplegallery_base', _t( 'Gallery location: ', 'simplegallery' ) . Site::get_url('habari') . '/' ); $form->base->value = $this->base; $form->append( 'submit', 'submit', _t( 'Submit' ) ); $form->out(); break; } } } public function help() { return "The Simple Gallery plugin looks for directories and files in the <code>user/files/simplegallery</code> directory. You must create this directory with permissions that let the web server read it. You can then configure the location of the gallery on your site."; } private function pretty_title($title) { // Strip any extension $pretty_title = basename($title, '.' . pathinfo($title, PATHINFO_EXTENSION) ); // Turn underscores or hyphens into spaces $pretty_title = strtr($pretty_title, '_-', ' '); return $pretty_title; } } ?> <file_sep><?php /** * Lockdown plugin */ class LockdownPlugin extends Plugin { /** * function info * Returns information about this plugin * @return array Plugin info array **/ function info() { return array ( 'name' => 'Lockdown', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'version' => '1.0', 'description' => 'Prevents users from making changes that would disable a demo install', 'license' => 'Apache License 2.0', ); } /** * Prevent users who are the demo user from being deleted * * @param boolean $allow true to allow the deletion of this user * @param User $user The user object requested to delete * @return boolea true to allow the deletion of this user, false to deny */ function filter_user_delete_allow( $allow, $user ) { if($user->username == 'demo') { Session::notice('To maintain the integrity of the demo, the demo user account can\'t be deleted.', 'lockdown_user_delete'); return false; } return $allow; } /** * Prevent users who are the demo user from being updated * * @param boolean $allow true to allow the update of this user * @param User $user The user object requested to update * @return boolea true to allow the update of this user, false to deny */ function filter_user_update_allow( $allow, $user ) { if($user->username == 'demo') { Session::notice('To maintain the integrity of the demo, the demo user account can\'t be updated.', 'lockdown_user_update'); return false; } return $allow; } /** * Permit only certain options to be updated. * * @param mixed $value The value of the option * @param string $name The name of the option * @param mixed $oldvalue The original value of the option * @return */ function filter_option_set_value( $value, $name, $oldvalue ) { switch($name) { case 'theme_dir': case 'theme_name': case 'cron_running': return $value; break; default: Session::notice('To maintain the integrity of the demo, option values can\'t be set.', 'lockdown_options'); Session::notice('Option to set: '.$name); return $oldvalue; } } /** * Prevent plugins from being activated * * @param boolean $ok true if it's ok to activate this plugin * @param string $file The filename of the plugin * @return boolean false to prevent plugins from being activated */ function filter_activate_plugin( $ok, $file ) { Session::notice('To maintain the integrity of the demo, plugins can\'t be activated.', 'lockdown_plugin'); return false; } /** * Prevent plugins from being deactivated * * @param boolean $ok true if it's ok to deactivate this plugin * @param string $file The filename of the plugin * @return boolean false to prevent plugins from being deactivated */ function filter_deactivate_plugin( $ok, $file ) { Session::notice('To maintain the integrity of the demo, plugins can\'t be deactivated.', 'lockdown_plugin'); return false; } /** * Prevent certain published content from causing problems. **/ function filter_post_content( $content ) { $newcontent = InputFilter::filter($content); if($content != $newcontent) { Session::notice('Certain content is filtered from posts to maintain the integrity of the demo.', 'lockdown_plugin'); } return $newcontent; } /** * Filter title, slug, and tags fields for HTML content **/ function action_publish_post( $post, $form ) { $post->title = htmlentities($post->title); $post->slug = urlencode($post->slug); $post->tags = htmlentities($form->tags); } } ?><file_sep><?php $theme->display('header'); ?> <!-- single --> <div id="content" class="hfeed"> <div id="entry-<?php echo $post->slug; ?>" class="hentry entry <?php echo $post->statusname , ' ' , $post->tags_class; ?>"> <div class="entry-head"> <h1 class="entry-title"><a href="<?php echo $post->permalink; ?>" title="<?php echo strip_tags($post->title); ?>" rel="bookmark"><?php echo $post->title_out; ?></a></h1> <ul class="entry-meta"> <li class="entry-date"><abbr class="published" title="<?php echo $post->pubdate->out(HabariDateTime::ISO8601); ?>"><?php echo $post->pubdate->out('F j, Y'); ?></abbr></li> <li class="entry-time"><abbr class="published" title="<?php echo $post->pubdate->out(HabariDateTime::ISO8601); ?>"><?php echo $post->pubdate->out('g:i a'); ?></abbr></li> <li class="comments-link"><a href="<?php echo $post->permalink; ?>#comments" title="<?php _e('Comments to this post', 'binadamu') ?>"><?php printf(_n('%1$d Comment', '%1$d Comments', $post->comments->approved->count, 'binadamu'), $post->comments->approved->count); ?></a></li> <?php if ($post->tags) { ?> <li class="entry-tags"><?php echo $post->tags_out; ?></li> <?php } ?> <?php if ($loggedin) { ?> <li class="entry-edit"><a href="<?php echo $post->editlink; ?>" title="<?php _e('Edit post', 'binadamu') ?>"><?php _e('Edit', 'binadamu') ?></a></li> <?php } ?> </ul> </div> <div class="entry-content"> <?php echo $post->content_out; ?> </div> </div> <div id="pager"> <?php if ($previous = $post->descend()): ?> <a class="previous" href="<?php echo $previous->permalink ?>" title="<?php echo $previous->title; ?>"><?php echo $previous->title; ?></a> <?php endif; ?> <?php if ($next = $post->ascend()): ?> <a class="next" href="<?php echo $next->permalink ?>" title="<?php echo $next->title; ?>"><?php echo $next->title; ?></a> <?php endif; ?> </div> <?php $theme->display('comments'); ?> </div> <hr /> <!-- /single --> <?php $theme->display('sidebar.single'); ?> <?php $theme->display('footer'); ?> <file_sep><?php $theme->display ('header'); ?> <div class="page" id="post-<?php echo $post->id; ?>"> <h2><?php echo $post->title_out; ?></h2> <?php echo $post->content_out; ?> <?php if ( $loggedin ) { ?><p><a href="<?php echo $post->editlink; ?>"><?php _e('Edit'); ?> "<?php echo $post->title_out; ?>"</a></p><?php } ?> </div> <div class="clear"></div> </div> <?php $theme->display ( 'sidebar' ); ?> <?php $theme->display ( 'footer' ); ?><file_sep><?php class Fontdeck extends Plugin { public function info() { return array( 'name' => 'Fontdeck', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'version' => '1.0', 'description' => 'Embeds <a href="http://www.fontdeck.com" title="Fontdeck">Fontdeck</a> typefaces in headers without needing any theme modifications.', 'license' => 'Apache License 2.0', ); } public function help() { return "Once configured, the CSS code generated for your Fontdeck fonts will be added to your headers, as long as your theme calls <code>&lt;?php $theme->header(); ?&gt;</code>"; } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Fontdeck', '483f2c57-3e38-48cc-87c1-f38c28aec691', $this->info->version ); } /** * Set priority to move inserted tags nearer to the end * @return array **/ public function set_priorities() { return array( 'theme_header' => 11, ); } /** * Simple plugin configuration * @return FormUI The configuration form **/ public function configure() { $ui = new FormUI( 'fontdeck' ); $code = $ui->append( 'textarea', 'code', 'fontdeck__code', _t( 'Header code.<p>From the textarea "Paste this code into the <code>&lt;head&gt;</code> of your web page:"</p>', 'fontdeck' ) ); $code->rows = 4; $code->cols = 50; $code->raw = true; $code->add_validator( 'validate_required' ); $embed = $ui->append( 'textarea', 'stack', 'fontdeck__stack', _t( 'Selectors and font stacks.<p>From the textarea "Paste these CSS rules into your stylesheet and adapt the selectors as you need to:"</p>', 'fontdeck' ) ); $embed->rows = 4; $embed->cols = 50; $embed->raw = true; $embed->add_validator( 'validate_required' ); $ui->on_success( array( $this, 'updated_config' ) ); $ui->append( 'submit', 'save', 'save' ); return $ui; // should probably do this in Twitter?? } /** * Give the user a session message to confirm options were saved. **/ public function updated_config( $ui ) { Session::notice( _t( 'Fontdeck CSS saved.', 'fontdeck' ) ); $ui->save(); } /** * Add tags to headers. * @return array **/ public function theme_header( $theme ) { return $this->get_fonts() ."\n". $this->get_css(); } /** * Generate tags for adding to headers. * @return string Tags to add to headers. **/ private function get_fonts() { return Options::get( 'fontdeck__code' ); } /** * Generate header style. * @return string text to add to headers. **/ private function get_css() { $stack = Options::get( 'fontdeck__stack' ); return "<style type=\"text/css\">\n$stack</style>\n"; } } ?> <file_sep><?php include 'header.php'; ?> <?php include 'sidebar.php'; ?> <div id="content"> <div class="post" id="post-<?php echo $post->id; ?>"> <div class="post_head"> <h2><a href="<?php echo $post->permalink; ?>" title="<?php echo $post->title; ?>"><?php echo $post->title_out; ?></a></h2> <p class="post_head_meta"><?php echo $post->author->info->displayname; ?> &middot; <?php echo $post->pubdate_out; ?></p> </div> <div class="post_content"> <?php echo $post->content_out; ?> </div> <div class="post_meta"> <p>This entry was posted on <span class="date"><?php echo $post->pubdate_out; ?></span> <?php if ( is_array( $post->tags ) ) { ?>and is filed under <?php echo $post->tags_out; ?><?php } ?>. There is <a href="<?php echo $post->permalink; ?>#comments" title="Comments to this post"><?php echo $post->comments->approved->count; ?> <?php echo _n( 'Comment', 'Comments', $post->comments->approved->count ); ?></a> on this post. You can follow any responses to this entry through the <a href="<?php echo $post->comment_feed_link; ?>">comment feed</a>.</p> </div> </div> <?php include 'comments.php'; ?> </div> <?php include 'footer.php'; ?><file_sep><?php include'header.php'; ?> <div id="content_wrap"> <div id="content"> <h2><?php echo $post->title; ?></h2> <?php echo $post->content_out; ?> <?php if ( $user ) { ?> | <a href="<?php echo $post->editlink; ?>" title="Edit post">Edit</a> | <?php } ?> </div> <?php include'sidebar.php'; ?> </div> <?php include'footer.php'; ?><file_sep><?php // Display Habari header $theme->display('header'); // Set file to work with if(!isset($_GET['file'])){ // If no file selected, set default theme's // home page as edit file $file=Site::get_dir("theme")."/home.php"; }else{ // Otherwise set the chosen file $file=$_GET['file']; } // Get Javascripts include('fileman.js.php'); // Get CSS include('fileman.css.php'); ?> <div class="container"> <h2>File Manager</h2> <table class="fileman"> <tr> <td class="editor"> <div class="fileman"> <form class="fileman"> <p style="margin-bottom:7px;">Currently editing: <?php echo $file; ?></p> <p class="status">Status: <span>File not saved.</span></p> <textarea name="contents"><?php echo htmlspecialchars(file_get_contents($file)); ?></textarea> <p><input type="submit" name="submit" value="Save Changes" /><?php if(!is_writable($file)){echo " &nbsp; <span style=\"color:#B00;font-weight:bold;\">File not writable!</span>";} ?></p> <input type="hidden" name="file" class="file" value="<?php echo $file; ?>" /> </form> </div> </td> <td class="browser"> <div class="fileman"> <p>Base Dir: <?php Site::out_url("user"); ?></p><br /> <div id="jQueryFileTree"></div> </div> </td> </tr> </table> <p style="text-align:center;color:#555;font-size:10px;">FileMan Plugin for <a href="http://habariproject.org">Habari</a> made by <a href="http://mattsd.com">Matt-SD</a></p> </div> <?php $theme->display('footer'); //Get Habari footer ?> <file_sep><?php include 'header.php'; ?> <div id="primary" class="single-post"> <div class="inside"> <div class="primary"> <?php if ( $posts ): ?> <h1>Search Results</h1> <ul class="dates"> <div> <b class="spiffy"> <b class="spiffy1"><b></b></b> <b class="spiffy2"><b></b></b> <b class="spiffy3"></b> <b class="spiffy4"></b> <b class="spiffy5"></b> </b> <div class="spiffy_content"> <?php foreach ( $posts as $post ): ?> <li> <span class="date"><?php echo Format::nice_date($post->pubdate, 'Y.j.n') ?></span> <a href="<?php echo $post->permalink ?>"><?php echo $post->title; ?></a> <?php if ( is_array($post->tags) ) { echo " posted in {$post->tags_out}"; } ?> </li> <?php endforeach; ?> </div> <b class="spiffy"> <b class="spiffy5"></b> <b class="spiffy4"></b> <b class="spiffy3"></b> <b class="spiffy2"><b></b></b> <b class="spiffy1"><b></b></b> </b> </div> </ul> <div class="navigation"> <!-- Todo: Need to add with navigation --> <div class="left"><?php //next_posts_link('&laquo; Previous Entries') ?></div> <div class="right"><?php //previous_posts_link('Next Entries &raquo;') ?></div> </div> <?php else: ?> <h1>No posts found. Try a different search?</h1> <?php endif; ?> </div> <div class="secondary"> <h2>Search</h2> <div class="featured"> <p>You searched for &ldquo;<?php echo htmlspecialchars( $criteria ); ?>&rdquo; at <?php Options::out('title'); ?>. There were <?php if (!$posts) echo "no results, better luck next time."; elseif (1 == count($posts)) echo "one result found. It must be your lucky day."; else echo count($posts) . " results found."; ?> </p> </div> </div> <div class="clear"></div> </div> </div> <?php include 'sidebar.php'; ?> <?php include 'footer.php'; ?> <file_sep> <li id="widget-jaiku" class="widget"> <h3><?php _e('Soliloquy', 'demorgan'); ?></h3> <ul> <?php if (is_array($presences)) { foreach ($presences as $presence) { printf('<li class="jaiku-message">%1$s <a href="%2$s"><abbr title="%3$s">%4$s</abbr></a> (<a href="%2$s#comments">%5$s</a>)</li>', $presence->message_out, $presence->url, $presence->created_at, $presence->created_at_relative, count($presence->comments)); } printf('<li class="jaiku-more"><a href="%s">' . _t('Read more…', 'demorgan') . '</a></li>', $presences[0]->user->url); } else { echo '<li class="jaiku-error">' . $presences . '</li>'; } ?> </ul> </li><file_sep><?php include 'header.php'; ?> <div id="content_wrap"> <div id="content"> <h2>Error 404 - Page not found!</h2> <p>The page you trying to reach does not exist, or has been moved. Please use the menus or the search box to find what you are looking for.</p> </div> <?php include 'sidebar.php'; ?> </div> <?php include 'footer.php'; ?><file_sep><!-- footer --> <br class="clear" /> <div id="footer"> <p> <?php printf( _t('%1$s is powered by %2$s and %3$s theme.', 'demorgan'), Options::get('title'), '<a href="http://www.habariproject.org/" title="Habari">Habari</a>', '<a href="http://blog.bcse.info/de-morgan/"><NAME></a>' ); ?> </p> </div> <?php $theme->footer(); ?> </div> </body> </html> <!-- /footer --> <file_sep><?php require_once 'breezyarchiveshandler.php'; class BreezyArchives extends Plugin { private $config = array(); private $class_name = ''; private $cache_name = ''; private function default_options() { return array ( /* Chronology */ 'chronology_title' => _t('Chronology', $this->class_name), 'month_format' => 'M', 'show_monthly_post_count' => TRUE, /* Taxonomy */ 'taxonomy_title' => _t('Taxonomy', $this->class_name), 'show_tag_post_count' => TRUE, 'excluded_tags' => array(), /* Pagination */ 'posts_per_page' => 15, 'next_page_text' => _t('Older →', $this->class_name), 'prev_page_text' => _t('← Newer', $this->class_name), /* General */ 'show_newest_first' => TRUE, 'show_comment_count' => TRUE ); } public function info() { return array( 'name' => 'Breezy Archives', 'version' => '0.3', 'url' => 'http://code.google.com/p/bcse/wiki/BreezyArchives', 'author' => '<NAME>', 'authorurl' => 'http://blog.bcse.info/', 'license' => 'Apache License 2.0', 'description' => _t('An archives plugin which mimics ‘Live Archives’ on WordPress. When JavaScript is not available, it will graceful degrade to a ‘Clean Archives’.', $this->class_name) ); } /** * On plugin activation, set the default options */ public function action_plugin_activation($file) { if (realpath($file) === __FILE__) { $this->class_name = strtolower(get_class($this)); $this->cache_name = Site::get_url('host') . ':' . $this->class_name; foreach (self::default_options() as $name => $value) { $current_value = Options::get($this->class_name . '__' . $name); if (is_null($current_value)) { Options::set($this->class_name . '__' . $name, $value); } } } } /** * On plugin init, add the template included with this plugin to the available templates in the theme */ public function action_init() { $this->class_name = strtolower(get_class($this)); foreach (self::default_options() as $name => $value) { $this->config[$name] = Options::get($this->class_name . '__' . $name); } $this->load_text_domain($this->class_name); $this->add_template($this->class_name, dirname(__FILE__) . '/breezyarchives.php'); $this->add_template('breezyarchives_chrono', dirname(__FILE__) . '/breezyarchives_chrono.php'); $this->add_template('breezyarchives_month', dirname(__FILE__) . '/breezyarchives_month.php'); $this->add_template('breezyarchives_tags', dirname(__FILE__) . '/breezyarchives_tags.php'); $this->add_template('breezyarchives_tag', dirname(__FILE__) . '/breezyarchives_tag.php'); $this->add_template('breezyarchives_js', dirname(__FILE__) . '/breezyarchives.js'); } /** * Add update beacon support **/ public function action_update_check() { Update::add('Breezy Archives', '2f6d8d49-1e93-4c46-924f-af8a351af10a', $this->info->version); } /** * Add actions to the plugin page for this plugin * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id **/ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id === $this->plugin_id()) { $actions[] = _t('Configure', $this->class_name); } return $actions; } /** * Respond to the user selecting an action on the plugin page * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook **/ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id === $this->plugin_id()) { switch ($action) { case _t('Configure', $this->class_name): $ui = new FormUI($this->class_name); $ui->append('fieldset', 'chronology', _t('Chronology', $this->class_name)); $ui->chronology->append('text', 'chronology_title', 'option:' . $this->class_name . '__chronology_title', _t('Title for Chronology Archives', $this->class_name)); $ui->chronology->chronology_title->add_validator('validate_required'); $ui->chronology->append( 'select', 'month_format', 'option:' . $this->class_name . '__month_format', _t('Month Format', $this->class_name), array( 'F' => _t('Full name (January – December)', $this->class_name), '%B' => sprintf(_t('Full name according to the current system locale (%1$s – %2$s)', $this->class_name), strftime('%B', mktime(0,0,0,1,1)), strftime('%B', mktime(0,0,0,12,1))), 'M' => _t('Abbreviation (Jan – Dec)', $this->class_name), '%b' => sprintf(_t('Abbreviation according to the current system locale (%1$s – %2$s)', $this->class_name), strftime('%b', mktime(0,0,0,1,1)), strftime('%b', mktime(0,0,0,12,1))), 'm' => _t('Number with leading zero (01 – 12)', $this->class_name), 'n' => _t('Number without leading zero (1 – 12)', $this->class_name) ) ); $ui->chronology->append('checkbox', 'show_monthly_post_count', 'option:' . $this->class_name . '__show_monthly_post_count', _t('Show Monthly Posts Count', $this->class_name)); $ui->append('fieldset', 'taxonomy', _t('Taxonomy', $this->class_name)); $ui->taxonomy->append('text', 'taxonomy_title', 'option:' . $this->class_name . '__taxonomy_title', _t('Title for Taxonomy Archives', $this->class_name)); $ui->taxonomy->taxonomy_title->add_validator('validate_required'); $ui->taxonomy->append('checkbox', 'show_tag_post_count', 'option:' . $this->class_name . '__show_tag_post_count', _t('Show Tagged Posts Count', $this->class_name)); $ui->taxonomy->append('textmulti', 'excluded_tags', 'option:' . $this->class_name . '__excluded_tags', _t('Excluded Tags', $this->class_name)); $ui->append('fieldset', 'pagination', _t('Pagination', $this->class_name)); $ui->pagination->append('text', 'posts_per_page', 'option:' . $this->class_name . '__posts_per_page', _t('&#8470; of Posts per Page', $this->class_name)); $ui->pagination->posts_per_page->add_validator('validate_uint'); $ui->pagination->posts_per_page->add_validator('validate_required'); $ui->pagination->append('text', 'next_page_text', 'option:' . $this->class_name . '__next_page_text', _t('Next Page Link Text', $this->class_name)); $ui->pagination->next_page_text->add_validator('validate_required'); $ui->pagination->append('text', 'prev_page_text', 'option:' . $this->class_name . '__prev_page_text', _t('Previous Page Link Text', $this->class_name)); $ui->pagination->prev_page_text->add_validator('validate_required'); $ui->append('fieldset', 'general', _t('General', $this->class_name)); $ui->general->append('checkbox', 'show_newest_first', 'option:' . $this->class_name . '__show_newest_first', _t('Show Newest First', $this->class_name)); $ui->general->append('checkbox', 'show_comment_count', 'option:' . $this->class_name . '__show_comment_count', _t('Show &#8470; of Comments', $this->class_name)); /* $ui->taxonomy->append( 'select', 'displayed_tags', 'option:' . $this->class_name . '__displayed_tags', _t('Displayed Tags', $this->class_name), array( 'all' => 'Show all tags', 'fave' => 'Show the first N most-used tags', 'big' => 'Show tags with more than N posts' ) ); $ui->general->append('text', 'loading_content', 'option:' . $this->class_name . '__loading_content', _t('Loading Content', $this->class_name)); */ // When the form is successfully completed, call $this->updated_config() $ui->append('submit', 'save', _t('Save', $this->class_name)); $ui->set_option('success_message', _t('Options saved', $this->class_name)); $ui->out(); break; } } } public function validate_uint($value) { if (!ctype_digit($value) || strstr($value, '.') || $value < 0) { return array(_t('This field must be positive integer.', $this->class_name)); } return array(); } /** * Returns true if plugin config form values defined in action_plugin_ui should be stored in options by Habari * @return bool True if options should be stored **/ public function updated_config($ui) { return true; } public function filter_rewrite_rules($rules) { $rules[] = new RewriteRule(array( 'name' => 'display_breezyarchives_by_month', 'parse_regex' => '%^(?P<class_name>' . $this->class_name . ')/(?P<year>[1,2]{1}[\d]{3})/(?P<month>[\d]{2})(?:/page/(?P<page>\d+))?/?$%i', 'build_str' => '{$class_name}/{$year}/{$month}(/page/{$page})', 'handler' => 'BreezyArchivesHandler', 'action' => 'display_breezyarchives_by_month', 'rule_class' => RewriteRule::RULE_PLUGIN, 'is_active' => 1, 'description' => 'Displays Breezy Archives for a specific month.' )); $rules[] = new RewriteRule(array( 'name' => 'display_breezyarchives_by_tag', 'parse_regex' => '%^(?P<class_name>' . $this->class_name . ')/tag/(?P<tag_slug>[^/]*)(?:/page/(?P<page>\d+))?/?$%i', 'build_str' => '{$class_name}/tag/{$tag_slug}(/page/{$page})', 'handler' => 'BreezyArchivesHandler', 'action' => 'display_breezyarchives_by_tag', 'rule_class' => RewriteRule::RULE_PLUGIN, 'is_active' => 1, 'description' => 'Displays Breezy Archives for a specific tag.' )); $rules[] = new RewriteRule(array( 'name' => 'display_breezyarchives_js', 'parse_regex' => '%^scripts/jquery.(?P<class_name>' . $this->class_name . ')_(?P<config>[0-9a-f]{32}).js$%i', 'build_str' => 'scripts/jquery.{$class_name}_{$config}.js', 'handler' => 'BreezyArchivesHandler', 'action' => 'display_breezyarchives_js', 'rule_class' => RewriteRule::RULE_PLUGIN, 'is_active' => 1, 'description' => 'Displays Breezy Archives JavaScript content.' )); return $rules; } public function theme_header($theme) { if ($theme->template_exists($this->class_name . '.css')) { $css_path = $theme->get_url(TRUE) . $this->class_name . '.css'; } else { $css_path = $this->get_url(TRUE) . $this->class_name . '.css'; } Stack::add('template_stylesheet', array($css_path, 'screen'), $this->class_name); } public function theme_breezyarchives($theme) { Stack::add('template_footer_javascript', 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', 'jquery'); Stack::add('template_footer_javascript', Site::get_url('scripts') . '/jquery.spinner.js', 'jquery.spinner', 'jquery'); Stack::add('template_footer_javascript', URL::get('display_breezyarchives_js', array('class_name' => $this->class_name, 'config' => md5(serialize($this->config)))), 'jquery.breezyarchives', 'jquery'); if (Cache::has($this->cache_name)) { return Cache::get($this->cache_name); } else { $theme->chronology_title = $this->config['chronology_title']; $theme->taxonomy_title = $this->config['taxonomy_title']; $ret = $theme->fetch($this->class_name); Cache::set($this->cache_name, $ret); return $ret; } } public function theme_chronology_archives($theme) { $sql = 'SELECT YEAR(FROM_UNIXTIME(pubdate)) AS year, MONTH(FROM_UNIXTIME(pubdate)) AS month, COUNT(id) AS count FROM {posts} WHERE content_type = ' . Post::type('entry') . ' AND status = ' . Post::status('published') . ' GROUP BY year, month ORDER BY year DESC, month DESC'; $months = DB::get_results($sql); $years = array(); $year_first = $months[0]->year; $year_last = end($months)->year; $years = array_fill_keys(range($year_first, $year_last), array()); if ($this->config['show_newest_first']) { foreach ($years as &$y) { $y = array_fill_keys(array('12', '11', '10', '09', '08', '07', '06', '05', '04', '03', '02', '01'), 0); } } else { foreach ($years as &$y) { $y = array_fill_keys(array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'), 0); } } foreach ($months as $m) { $years[$m->year][str_pad($m->month, 2, '0', STR_PAD_LEFT)] = $m->count; } $theme->years = $years; $theme->show_monthly_post_count = $this->config['show_monthly_post_count']; $theme->month_format = $this->config['month_format']; return $theme->fetch('breezyarchives_chrono'); } public function theme_taxonomy_archives($theme) { $where = ''; if (count($this->config['excluded_tags']) > 0) { $where = 'WHERE t.tag_slug NOT IN ("' . implode('","', $this->config['excluded_tags']) . '")'; } $sql = sprintf( 'SELECT t.id AS id, t.tag_text AS tag, t.tag_slug AS slug, COUNT(tp.tag_id) AS count FROM {tags} t LEFT JOIN {tag2post} tp ON t.id=tp.tag_id %1$s GROUP BY id, tag, slug HAVING count > 0 ORDER BY tag ASC', $where); $theme->tags = DB::get_results($sql); $theme->show_tag_post_count = $this->config['show_tag_post_count']; return $theme->fetch('breezyarchives_tags'); } public function action_post_update_status($post, $old_value, $new_value) { if ((Post::status_name($old_value) == 'published' && Post::status_name($new_value) != 'published') || (Post::status_name($old_value) != 'published' && Post::status_name($new_value) == 'published')) { Cache::expire($this->cache_name); } } public function action_post_update_slug($post, $old_value, $new_value) { if (Post::status_name($post->status) == 'published') { Cache::expire($this->cache_name); } } public function action_post_update_title($post, $old_value, $new_value) { if (Post::status_name($post->status) == 'published') { Cache::expire($this->cache_name); } } public function action_post_delete_after($post) { if (Post::status_name($post->status) == 'published') { Cache::expire($this->cache_name); } } } ?> <file_sep><?php define('TRAC_DB_PATH', '/var/www/sites/habariproject/trac/habari/db/trac.db'); class TracFeed extends Plugin { public function info() { return array ( 'name' => 'TracFeed', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'version' => '1.0', 'description' => 'Produces a feed from the Trac database', 'license' => 'Apache License 2.0', ); } public function filter_rewrite_rules( $rules ) { $rules[] = new RewriteRule(array( 'name' => 'item', 'parse_regex' => '%feed/dev/?$%i', 'build_str' => 'feed/dev', 'handler' => 'UserThemeHandler', 'action' => 'dev_feed', 'priority' => 7, 'is_active' => 1, )); return $rules; } public function action_handler_dev_feed($handler_vars) { $xml= RSS::create_rss_wrapper(); $db = DatabaseConnection::ConnectionFactory('sqlite:' . TRAC_DB_PATH); $db->connect('sqlite:' . TRAC_DB_PATH, '', ''); $times = $db->get_column('SELECT time from ticket_change group by time order by time desc limit 15;'); $mintime = array_reduce($times, 'min', reset($times)); $comments = $db->get_results(" SELECT *, ticket_change.time as changetime from ticket_change INNER JOIN ticket on ticket.id = ticket_change.ticket where changetime >= ? and not (field ='comment' and newvalue = '') order by ticket_change.time DESC; ", array($mintime)); $posts = array(); foreach($comments as $comment) { $post_id = md5($comment->ticket . ':' . $comment->changetime . ':' . $comment->author); if(!array_key_exists($post_id, $posts)) { $post = new Post(); $post->title = "Ticket #{$comment->ticket}: {$comment->summary}"; $post->content = "Changes by {$comment->author} on ticket <a href=\"http://trac.habariproject.org/habari/ticket/{$comment->ticket}\">#{$comment->ticket}</a>.\n<br>\n<br>"; $post->guid = 'tag:' . Site::get_url( 'hostname' ) . ',trac_comment,' . $post_id; $post->content_type = 'dev_feed'; $post->slug = "http://trac.habariproject.org/habari/ticket/{$comment->ticket}"; $post->pubdate = date('Y-m-d H:i:s', $comment->changetime); $posts[$post_id] = $post; } else { $post = $posts[$post_id]; } switch($comment->field) { case 'comment': $content = $comment->newvalue; $content = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]/i', '<a href="$0">[link]</a>', $content); $content = preg_replace('%\br([0-9]+)\b%', '<a href="http://trac.habariproject.org/habari/changeset/$1">r$1</a>', $content); $content = preg_replace('%\b#([0-9]+)\b%', '<a href="http://trac.habariproject.org/habari/ticket/$1">$1</a>', $content); $post->content .= "Comment #{$comment->oldvalue} by {$comment->author}:\n<blockquote><pre>{$content}</pre></blockquote>\n<br>"; break; default: if(trim($comment->oldvalue) == '') { $post->content .= "Set <b>{$comment->field}</b> to: {$comment->newvalue}\n<br>"; } else { $post->content .= "Changed <b>{$comment->field}</b> from: {$comment->oldvalue}\n<br> To: {$comment->newvalue}\n<br>"; } break; } } $xml= RSS::add_posts($xml, $posts ); ob_clean(); header( 'Content-Type: application/xml' ); echo $xml->asXML(); exit; } function filter_post_permalink($permalink, $post) { if($post->content_type == 'dev_feed') { return $post->slug; } return $permalink; } } ?> <file_sep><?php /** * Live Help Plugin * **/ class LiveHelp extends Plugin { /** * function info * Returns information about this plugin * @return array Plugin info array **/ function info() { return array ( 'name' => 'Live Help', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'version' => '0.11', 'description' => 'Allows users to connect to #habari on IRC from within the admin.', 'license' => 'Apache License 2.0', ); } /** * Add the Live Help page to the admin menu * * @param array $menus The main admin menu * @return array The altered admin menu */ function filter_adminhandler_post_loadplugins_main_menu( $menus ) { $menus['livehelp'] = array( 'url' => URL::get( 'admin', 'page=livehelp'), 'title' => _t('Live Help'), 'text' => _t('Live Help'), 'selected' => false ); return $menus; } /** * On plugin init, add the admin_livehelp template to the admin theme */ function action_init() { $this->add_template('livehelp', dirname(__FILE__) . '/livehelp.php'); } public function action_add_template_vars( $theme ) { if ($theme->admin_page == 'livehelp') { $user = User::identify(); $nick = $user->username; $nick = $nick == 'admin' ? substr($user->email, 0, strpos($user->email, '@')) : $nick; $theme->assign('nick', $nick); } } public function action_admin_header( $theme ) { if ($theme->admin_page == 'livehelp') { Stack::add('admin_stylesheet', array($this->get_url() . '/livehelp.css', 'screen')); } } /** * Implement the update notification feature */ public function action_update_check() { Update::add( 'Live Help', 'c2413ab2-7c79-4f92-b008-18e3d8e05b64', $this->info->version ); } } ?> <file_sep><?php /** * User Profile Exposure Plugin Class * **/ class UPX extends Plugin { /** * function info * Returns information about this plugin * @return array Plugin info array **/ function info() { return array ( 'name' => 'UPX', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'version' => '1.0', 'description' => 'Exposes user profile information via xml entrypoint', 'license' => 'Apache License 2.0', ); } public function filter_rewrite_rules( $rules ) { $rules[] = new RewriteRule(array( 'name' => 'upx', 'parse_regex' => '/^upx\/(?P<username>[^\/]+)\/?$/i', 'build_str' => 'upx/{$username}', 'handler' => 'UPX', 'action' => 'display_user', 'priority' => 7, 'is_active' => 1, )); return $rules; } public function action_handler_display_user($params) { $users = Users::get(array('info' => array('ircnick'=>$params['username']))); //Utils::debug($user->info); switch(count($users)) { case 0: $xml = new SimpleXMLElement('<error>No user with that IRC nickname.</error>'); break; default: $xml = new SimpleXMLElement('<error>More than one user is registered under that nickname!</error>'); break; case 1: $user = reset($users); $xml = new SimpleXMLElement('<userinfo></userinfo>'); $xml['nickname'] = $params['username']; $xml->blog = $user->info->blog; break; } header('Content-type: text/plain'); echo $xml->asXML(); } } ?><file_sep><?php class FreeStyle extends Plugin { function info() { return array( 'url' => 'http://iamgraham.net/plugins', 'name' => 'FreeStyle', 'description' => 'Allows you to inject arbitrary CSS into themes.', 'license' => 'Apache License 2.0', 'author' => '<NAME>', 'authorurl' => 'http://iamgraham.net/', 'version' => '0.1' ); } public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()) { $actions[] = _t('Configure'); } return $actions; } public function action_plugin_ui($plugin_id, $action) { if ($plugin_id == $this->plugin_id()) { switch ($action) { case _t('Configure'): $ui = new FormUI(strtolower(get_class($this))); $clientcode = $ui->add('textarea', 'css', _t('FreeStyle CSS')); $ui->on_success(array($this, 'updated_config')); $ui->out(); break; } } } public function updated_config($ui) { return true; } private static function getvar($var) { return Options::get('freestyle:'.$var); } function action_template_header() { echo '<style type="text/css">'."\n"; echo self::getvar('css')."\n"; echo '</style>'."\n"; } } ?> <file_sep> <li id="widget-feeds" class="widget"> <h3><?php _e('Subscribe', 'binadamu'); ?></h3> <ul> <li><a href="<?php URL::out('atom_feed', array('index' => '1')); ?>"><?php _e('All posts', 'binadamu'); ?></a></li> <li><a href="<?php URL::out('atom_feed_comments'); ?>"><?php _e('All comments', 'binadamu'); ?></a></li> </ul> </li> <file_sep>#!/bin/bash # setup tmp files from tar.gz's cd /home/matt/habari-locales/bzr/ bzr merge bzr add locale/* bzr commit -m "lp sync" cd ../ # check fo .po for d in `ls bzr/locale/*.po`; do if [[ $d =~ bzr/locale/(.*).po ]] then if [ ! -d ${BASH_REMATCH[1]} ] then mkdir ${BASH_REMATCH[1]} mkdir ${BASH_REMATCH[1]}/trunk mkdir ${BASH_REMATCH[1]}/trunk/LC_MESSAGES mkdir ${BASH_REMATCH[1]}/trunk/dist fi echo "moving ${BASH_REMATCH[1]}.po" cp bzr/locale/${BASH_REMATCH[1]}.po ${BASH_REMATCH[1]}/trunk/LC_MESSAGES/habari.po echo "generating mo file" msgfmt -o ${BASH_REMATCH[1]}/trunk/LC_MESSAGES/habari.mo ${BASH_REMATCH[1]}/trunk/LC_MESSAGES/habari.po svn add -q ${BASH_REMATCH[1]} ${BASH_REMATCH[1]}/trunk/LC_MESSAGES/habari.po ${BASH_REMATCH[1]}/trunk/LC_MESSAGES/habari.mo fi done # remove tmp files rm -rf tmp svn ci -m"launchpad sync" echo "done!" <file_sep><?php class BeaconHandler extends ActionHandler { public function __construct ( ) { } public function act_request ( ) { /* * @todo refactor this so we Posts::get() only those GUIDs requested: * array( ... 'info:any' => array( 'guid1', 'guid2', ... ) ); * @todo potentially cache individual plugins seperately, or eliminate caching all together * * @todo check against the versioin passed with guid, to only output updated version info. */ if ( Cache::has( 'plugin_directory:plugins' ) && false ) { $plugins = Cache::get( 'plugin_directory:plugins' ); $from_cache = true; } else { // get the entire list of plugins from our directory based on their custom content type $plugins = Posts::get( array( 'content_type' => 'plugin', 'nolimit' => true ) ); $from_cache = false; } // build the xml output $xml = new SimpleXMLElement( '<updates></updates>' ); foreach ( $plugins as $plugin ) { if ( !$plugin->versions ) { continue; } // create the beacon's node $beacon_node = $xml->addChild( 'beacon' ); $beacon_node->addAttribute( 'id', $plugin->info->guid ); $beacon_node->addAttribute( 'name', $plugin->title ); foreach ( $plugin->versions as $version ) { // create an update node for the beacon with the status' message $update_node = $beacon_node->addChild( 'update', $version->description ); $update_node->addAttribute( 'severity', $version->status ); $update_node->addAttribute( 'version', $version->version ); $update_node->addAttribute( 'habari_version', $version->habari_version ); $update_node->addAttribute( 'url', $version->url ); } } //Utils::debug($plugins, 'Plugins'); // only cache this set of plugins if it wasn't already from the cache if ( $from_cache == false ) { Cache::set( 'plugin_directory:plugins', $plugins ); } $xml = Plugins::filter( 'plugin_directory_beacon_xml', $xml, $this->handler_vars ); $xml = $xml->asXML(); // @todo uncomment when we're actually outputting xml again ob_clean(); header( 'Content-Type: application/xml' ); echo $xml; } } ?> <file_sep><?php /* * Unfortunately Google's GeoMap doesn't correctly fit to the width of the containing DIV. * To get around this, we need to add the options for the map here in the template so that * we can get the current div width and add it to our options. */ ?> <div id="div_<?php echo $slug; ?>"></div> <script type="text/javascript"> // Get the actual width of the div var divWidth = document.getElementById("div_<?php echo $slug; ?>").offsetWidth; // Load up our GeoMap options var opts = { height: 200, width: divWidth, showLegend: false }; <?php echo $js_data; ?> <?php echo $js_draw; ?> </script> <file_sep><!-- commentsform --> <h3 id="respond">Leave a Reply</h3> <?php if ( Session::has_errors() ) { Session::messages_out(); } ?> <form action="<?php URL::out( 'submit_feedback', array( 'id' => $post->id ) ); ?>" method="post" id="commentform"> <p> <input type="text" name="name" id="name" value="<?php echo $commenter_name; ?>" size="22" tabindex="1" /> <label for="name"><small>Name (required)</small></label> </p> <p> <input type="text" name="email" id="email" value="<?php echo $commenter_email; ?>" size="22" tabindex="2" /> <label for="email"><small>Mail (will not be published) (required)</small></label> </p> <p> <input type="text" name="url" id="url" value="<?php echo $commenter_url; ?>" size="22" tabindex="3" /> <label for="url"><small>Website</small></label> </p> <p> <textarea name="content" id="comment" cols="100%" rows="10" tabindex="4"></textarea> </p> <p> <input name="submit" type="submit" id="submit" tabindex="5" value="Submit Comment" /> </p> </form> <!-- commentsform --> <file_sep>#!/bin/bash # setup tmp files from tar.gz's mkdir tmp for d in `ls launchpad-export*.tar.gz`; do mv $d tmp/$d cd tmp tar zxf $d cd .. done # check for .mo for d in `ls tmp`; do if [ -f tmp/$d/LC_MESSAGES/habari.mo ] then if [ ! -d $d ] then mkdir $d/trunk mkdir $d/trunk/LC_MESSAGES mkdir $d/trunk/dist mkdir $d/tags mkdir $d/braches fi echo "moving $d.mo" mv tmp/$d/LC_MESSAGES/habari.mo $d/trunk/LC_MESSAGES/habari.mo svn add -q $d $d/trunk/LC_MESSAGES/habari.mo fi done # check fo .po for d in `ls tmp/habari-*.po`; do if [[ $d =~ habari-(.*).po ]] then if [ ! -d ${BASH_REMATCH[1]} ] then mkdir ${BASH_REMATCH[1]}/trunk mkdir ${BASH_REMATCH[1]}/trunk/LC_MESSAGES mkdir ${BASH_REMATCH[1]}/trunk/dist mkdir ${BASH_REMATCH[1]}/tags mkdir ${BASH_REMATCH[1]}/braches fi echo "moving ${BASH_REMATCH[1]}.po" mv tmp/habari-${BASH_REMATCH[1]}.po ${BASH_REMATCH[1]}/trunk/LC_MESSAGES/habari.po svn add -q ${BASH_REMATCH[1]} ${BASH_REMATCH[1]}/trunk/LC_MESSAGES/habari.po fi done # remove tmp files rm -rf tmp svn ci -m"launchpad sync" echo "done!" <file_sep><?php $theme->display ('header'); ?> <!-- page.single --> <div class="page"> <div id="primary"> <?php $theme->display('magicarchives'); ?> </div> <hr> <div class="secondary"> <?php $theme->display ('sidebar'); ?> </div> <div class="clear"></div> </div> <!-- /page.single --> <?php $theme->display ( 'footer' ); ?> <file_sep><?php include 'header.php'; ?> <!-- entry.multiple --> <div id="content"> <?php $first= true; foreach ( $posts as $post ) { include 'entry.php'; $first= false; } ?> <div class="navigation"> Page: <?php echo Utils::page_selector( $page, Utils::archive_pages( $posts->count_all() ) ); ?> </div> </div> <!-- #content --> <?php include 'sidebar.php'; ?> <!-- /entry.multiple --> <?php include 'footer.php'; ?> <file_sep><?php /** * Post Fields - A plugin to display additional fields on the publish page **/ class postfields extends Plugin { /** * Required Plugin Information */ public function info() { return array( 'name' => 'Post Fields', 'version' => '1.0', 'url' => 'http://habariproject.org', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org', 'license' => 'Apache License 2.0', 'description' => 'Display additional fields on the post page in the tabs to let authors add additional metadata to their posts.', 'copyright' => '2008' ); } /** * Add actions to the plugin page for this plugin * * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id */ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()){ $actions[] = 'Configure'; } return $actions; } /** * Respond to the user selecting an action on the plugin page * * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook */ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id == $this->plugin_id()){ switch ($action){ case 'Configure' : $ui = new FormUI('postfields'); $ui->append('textmulti', 'fields', 'postfields__fields', 'Additional Fields:'); $ui->append('submit', 'submit', 'Submit'); $ui->out(); break; } } } /** * Add additional controls to the publish page tab * * @param FormUI $form The form that is used on the publish page * @param Post $post The post being edited **/ public function action_form_publish($form, $post) { $fields = Options::get('postfields__fields'); $output = ''; $control_id = 0; $postfields = $form->publish_controls->append('fieldset', 'postfields', 'Additional Fields'); foreach($fields as $field) { $control_id = md5($field); $fieldname = "postfield_{$control_id}"; $customfield = $postfields->append('text', $fieldname, 'null:null', $field); $customfield->value = isset($post->info->{$field}) ? $post->info->{$field} : ''; $customfield->template = 'tabcontrol_text'; } } /** * Modify a post before it is updated * * @param Post $post The post being saved, by reference * @param FormUI $form The form that was submitted on the publish page */ public function action_publish_post($post, $form) { $fields = Options::get('postfields__fields'); foreach($fields as $field) { $control_id = md5($field); $fieldname = "postfield_{$control_id}"; $customfield = $form->$fieldname; $post->info->{$field} = $customfield->value; } } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Postfields', '228D6060-38F0-11DD-AE16-0800200C9A66', $this->info->version ); } } ?><file_sep><?php /** * Keep Login plugin * **/ class KeepLogin extends Plugin { /** * Add output in the admin header * Adds the necessary javascript to make periodic ajax calls to the admin. */ public function action_admin_header() { $ajaxurl = URL::get('auth_ajax', array('context'=>'keep_session')); $script = <<< HEADER_JS $(document).ready(function(){ window.setInterval( function(){ $.post('$ajaxurl'); }, 1000 * 60 * 5 // 5 minutes ); }); HEADER_JS; Stack::add( 'admin_header_javascript', $script, 'keep_login', array('jquery') ); } public function action_auth_ajax_keep_session() { echo time(); } } ?> <file_sep><?php require_once "defensioapi.php"; class Defensio extends Plugin { private $defensio; public function info() { return array( 'name' => 'Defensio', 'author' => 'Habari Community', 'description' => 'Provides the Defensio spam filter webservice to Habari comments.', 'url' => 'http://habariproject.org', 'version' => '0.4', 'license' => 'Apache License 2.0' ); } public function set_priorities() { return array( 'action_comment_insert_before' => 1 ); } public function action_plugin_activation( $file ) { if ( realpath( $file ) == __FILE__ ) { Modules::add( 'Defensio' ); Session::notice( _t('Please set your Defensio API Key in the configuration.', 'defensio') ); Options::set( 'defensio__api_key', '' ); Options::set( 'defensio__announce_posts', 'yes' ); } } public function action_plugin_deactivation( $file ) { if ( realpath( $file ) == __FILE__ ) { Modules::remove_by_name( 'Defensio' ); } } public function filter_dash_modules( $modules ) { $modules[] = 'Defensio'; $this->add_template( 'dash_defensio', dirname( __FILE__ ) . '/dash_defensio.php' ); return $modules; } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t('Configure', 'defensio'); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure', 'defensio') : $ui = new FormUI( 'defensio' ); // Add a text control for the address you want the email sent to $api_key = $ui->append( 'text', 'api_key', 'option:defensio__api_key', _t('Defensio API Key: ', 'defensio') ); $api_key->add_validator( 'validate_required' ); $api_key->add_validator( array( $this, 'validate_api_key' ) ); $announce_posts = $ui->append( 'select', 'announce_posts', 'option:defensio__announce_posts', _t('Announce New Posts To Defensio: ', 'defensio') ); $announce_posts->options = array( 'yes' => _t('Yes', 'defensio'), 'no' => _t('No', 'defensio') ); $announce_posts->add_validator( 'validate_required' ); $register = $ui->append( 'static', 'register', '<a href="http://defensio.com/signup">' . _t('Get A New Defensio API Key.', 'defensio') . '</a>' ); $ui->append( 'submit', 'save', _t( 'Save', 'defensio' ) ); $ui->set_option( 'success_message', _t( 'Configuration saved', 'defensio' ) ); $ui->out(); break; } } } public function validate_api_key( $key ) { try { DefensioAPI::validate_api_key( $key, Site::get_url( 'habari' ) ); } catch ( Exception $e ) { return array( sprintf( _t('Sorry, the Defensio API key <b>%s</b> is invalid. Please check to make sure the key is entered correctly and is <b>registered for this site (%s)</b>.', 'defensio'), $key, Site::get_url( 'habari' ) ) ); } return array(); } public function action_init() { $this->defensio = new DefensioAPI( Options::get( 'defensio__api_key' ), Site::get_url( 'habari' ) ); $this->load_text_domain( 'defensio' ); $this->add_template( 'defensio', dirname(__FILE__) . '/moderate.php' ); } function action_admin_theme_get_spam( $handler, $theme ) { $handler->fetch_comments( array( 'status' => 2, 'limit' => 60 ) ); $theme->display( 'defensio' ); exit; } function action_admin_theme_post_spam( $handler, $theme ) { $this->action_admin_theme_get_spam( $handler, $theme ); } function filter_adminhandler_post_loadplugins_main_menu( $menu ) { $menu['spam'] = array( 'url' => URL::get( 'admin', 'page=spam' ), 'title' => _t('Manage all spam in the spam vault','defensio'), 'text' => _t('Spam Vault','defensio'), 'hotkey' => 'S', 'selected' => false ); return $menu; } public function filter_dash_module_defensio( $module, $module_id, $theme ) { $stats = $this->theme_defensio_stats(); // Show an error in the dashboard if Defensio returns a bad response. if ( !$stats ) { $module['title'] = '<a href="' . Site::get_url('admin') . '/spam">' . _t('Defensio') . '</a>'; $module['content'] = '<ul class=items"><li class="item clear">' . _t('Bad Response From Server') . '</li></ul>'; return $module; } $theme->accuracy = sprintf( '%.2f', $stats->accuracy * 100 ); $theme->spam = $stats->spam; $theme->ham = $stats->ham; $theme->false_negatives = $stats->false_negatives; $theme->false_positives = $stats->false_positives; $module['title'] = '<a href="' . Site::get_url('admin') . '/spam">' . _t('Defensio') . '</a>'; $module['content'] = $theme->fetch( 'dash_defensio' ); return $module; } public function theme_defensio_stats() { if ( Cache::has( 'defensio_stats' ) ) { $stats = Cache::get( 'defensio_stats' ); } else { try { $stats = $this->defensio->get_stats(); Cache::set( 'defensio_stats', $stats ); } catch ( Exception $e ) { EventLog::log( $e->getMessage(), 'notice', 'theme', 'Defensio' ); return null; } } return $stats; } public function action_comment_insert_before( $comment ) { $user = User::identify(); $params = array( 'user-ip' => long2ip( $comment->ip ), 'article-date' => date( 'Y/m/d', strtotime( $comment->post->pubdate ) ), 'comment-author' => $comment->name, 'comment-type' => strtolower( Comment::type_name( $comment->type ) ), 'comment-content' => $comment->content_out, 'comment-author-email' => $comment->email ? $comment->email : null, 'comment-author-url' => $comment->url ? $comment->url : null, 'permalink' => $comment->post->permalink, 'referrer' => isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : null, ); if ( $user instanceof User ) { $params['user-logged-in'] = $user instanceof User; // test for administrator, editor, etc. as well $params['trusted-user'] = $user instanceof User; if ( $user->info->openid_url ) { $params['openid'] = $user->info->openid_url; } } try { $result = $this->defensio->audit_comment( $params ); if ( $result->spam == true ) { $comment->status = 'spam'; $comment->info->spamcheck = array_unique(array_merge((array) $comment->info->spamcheck, array( _t('Flagged as Spam by Defensio', 'defensio')))); } $comment->info->defensio_signature = $result->signature; $comment->info->defensio_spaminess = $result->spaminess; } catch ( Exception $e ) { EventLog::log( $e->getMessage(), 'notice', 'comment', 'Defensio' ); } } public function action_admin_moderate_comments( $action, $comments, $handler ) { $false_positives = array(); $false_negatives = array(); foreach ( $comments as $comment ) { switch ( $action ) { case 'spam': if ( ( $comment->status == Comment::STATUS_APPROVED || $comment->status == Comment::STATUS_UNAPPROVED ) && isset($comment->info->defensio_signature) ) { $false_negatives[] = $comment->info->defensio_signature; Cache::expire('defensio_stats'); } break; case 'approve': if ( $comment->status == Comment::STATUS_SPAM && isset($comment->info->defensio_signature) ) { $false_positives[] = $comment->info->defensio_signature; Cache::expire('defensio_stats'); } break; } } try { if ( $false_positives ) { $this->defensio->report_false_positives( array( 'signatures' => $false_positives ) ); Session::notice( sprintf( _t('Reported %d false positives to Defensio', 'defensio'), count($false_positives) ) ); } if ( $false_negatives ) { $this->defensio->report_false_negatives( array( 'signatures' => $false_negatives ) ); Session::notice( sprintf( _t('Reported %d false negatives to Defensio', 'defensio'), count($false_negatives) ) ); } } catch ( Exception $e ) { EventLog::log( $e->getMessage(), 'notice', 'comment', 'Defensio' ); } } public function action_post_insert_after( $post ) { if ( Options::get( 'defensio__announce_posts' ) == 'yes' && $post->statusname == 'published' ) { $params = array( 'article-author' => $post->author->username, 'article-author-email' => $post->author->email, 'article-title' => $post->title, 'article-content' => $post->content, 'permalink' => $post->permalink ); try { $result = $this->defensio->announce_article( $params ); } catch ( Exception $e ) { EventLog::log( $e->getMessage(), 'notice', 'content', 'Defensio' ); } } } public static function get_spaminess_style( $comment ) { if ( isset($comment->info->defensio_spaminess) ) { switch ( $comment->info->defensio_spaminess ) { case $comment->info->defensio_spaminess > 0.6: return 'background:#faa;'; case $comment->info->defensio_spaminess > 0.3: return 'background:#fca;'; case $comment->info->defensio_spaminess > 0.1: return 'background:#fea;'; } } return 'background:#e2dbe3;'; } public static function sort_by_spaminess( $a, $b ) { if ( isset($a->info->defensio_spaminess) && isset($b->info->defensio_spaminess) ) { if ( $a->info->defensio_spaminess == $b->info->defensio_spaminess ) { return 0; } return $a->info->defensio_spaminess > $b->info->defensio_spaminess ? -1 : 1; } elseif ( isset($a->info->defensio_spaminess) ) { return 0; } else { return 1; } } } ?> <file_sep><h3>Tag Archives</h3> <ul> <?php $tags = $content->tags; foreach( $tags as $tag ): ?> <li> <a href="<?php echo $tag[ 'url' ]; ?>" title="View entries tagged '<?php echo $tag[ 'tag' ]; ?>'"><?php echo $tag[ 'tag' ] . $tag[ 'count' ]; ?></a> </li> <?php endforeach; ?> </ul><file_sep><div id="tla"> <h3>Sweet Links</h3> <ul> <?php foreach($content->links as $link): ?> <li><?php echo $link->before; ?><a href="<?php echo $link->url; ?>"><?php echo $link->text; ?></a><?php echo $link->after; ?></li> <?php endforeach; ?> </ul> </div><file_sep><?php /** * SpamHoneyPot Class * * This plugin entraps the spammer by supplying a hidden, second textarea that * if filled, auto-qualifies the comment as spam. */ class SpamHoneyPot extends Plugin { /** * Plugin information * * @return array Plugin info array */ function info() { return array ( 'name' => 'Spam HoneyPot', 'url' => 'http://seancoates.com/habari', 'author' => '<NAME>', 'authorurl' => 'http://seancoates.com/', 'version' => '1.0.1', 'description' => 'Entraps spammers with a honeypot comment field', 'license' => 'Apache License 2.0', ); } public function filter_final_output ( $out ) { // this sucks, fwiw, but there's no way to properly capture a comment form, currently $tokenizer = new HTMLTokenizer( $out, false ); $tokens = $tokenizer->parse(); $slices = $tokens->slice( 'textarea', array( 'id' => 'content' ) ); // no comment form... if (!$slices) { return $out; } // should only be one: $slice = $slices[0]; $sliceValue = trim( (string)$slice ); $sliceValue .= '<div style="display: none;" id="honeypot">Hello fine ' .'sir, please enter your ' .'good content here (unless you are evil.. in which ' .'case, do not):<textarea name="morecontent" ' .'id="morecontent"></textarea></div>'; $slice->tokenize_replace( $sliceValue ); $tokens->replace_slice( $slice ); return (string) $tokens; } /** * Check submitted form for honeypot and qualify as spam accordingly * * @param Comment The comment that will be processed before storing it in the database. * @return Comment The comment result to store. **/ function action_comment_insert_before ( Comment $comment ) { // This plugin ignores non-comments if($comment->type != Comment::COMMENT) { return $comment; } if (isset($_POST['morecontent']) && $_POST['morecontent'] != '') { $comment->status = Comment::STATUS_SPAM; $spamcheck[] = _t('Caught by the honeypot'); } } } ?> <file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta name="description" content="<?php Options::out( 'title' );?> - <?php Options::out( 'tagline' ); ?>" /> <meta name="keywords" content="" /> <meta http-equiv="Content-Type" content="text/html"> <meta name="generator" content="Habari"> <link rel="alternate" type="application/atom+xml" title="Atom 1.0" href="<?php $theme->feed_alternate(); ?>"> <link rel="edit" type="application/atom+xml" title="Atom Publishing Protocol" href="<?php URL::out( 'atompub_servicedocument' ); ?>"> <link rel="EditURI" type="application/rsd+xml" title="RSD" href="<?php URL::out( 'rsd' ); ?>"> <link rel="stylesheet" type="text/css" media="screen" href="<?php Site::out_url( 'theme' ); ?>/style.css"> <title><?php Options::out( 'title' ) ?><?php if($request->display_entry && isset($post)) { echo " :: {$post->title}"; } ?></title> <!--[if gt IE 5]> <style> #header #text_in {position: absolute; top: 50%;} </style> <![endif]--> <?php /* global $options; foreach ($options as $value) { if (get_settings( $value['id'] ) === FALSE) { $$value['id'] = $value['std']; } else { $$value['id'] = get_settings( $value['id'] ); } } */ ?> <?php //wp_head(); ?> </head> <body> <div id="wrap"> <div id="top"> <div id="menu"> <ul> <li class="page_item<?php if($request->display_home) { ?> current_page_item<?php } ?>"><a href="<?php Site::out_url( 'habari' ); ?>"><span>Home</span></a></li> <?php foreach ( $pages as $tab ) { ?> <li class="page_item<?php if(isset($post) && $post->slug == $tab->slug) { ?> current_page_item<?php } ?>"><a href="<?php echo $tab->permalink; ?>" title="<?php echo $tab->title; ?>"><span><?php echo $tab->title; ?></span></a></li> <?php } ?> <?php //$pages = wp_list_pages('sort_column=menu_order&depth=1&title_li=&echo=0'); //$pages = preg_replace('%<a ([^>]+)>%U','<a $1><span>', $pages); //$pages = str_replace('</a>','</span></a>', $pages); //echo $pages; ?> </ul> </div> <div id="title"> <h1><a href="<?php Site::out_url( 'habari' ); ?>"><?php Options::out( 'title' ); ?></a></h1> <p><?php Options::out( 'tagline' ); ?></p> </div> </div> <div id="header"> <div id="text"> <div id="text_in"> <div id="inside"> <p><?php echo $header_text; ?></p> </div> </div> </div> </div><file_sep><?php class PageSubtitle extends Plugin { /** * Required plugin information **/ function info() { return array( 'name' => 'Page Subtitle', 'version' => '0.3', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Allows a user to add a subtitle to pages.' ); } /** * Add the subtitle control to the publish page * * @param FormUI $form The publish page form * @param Post $post The post being edited **/ public function action_form_publish ( $form, $post ) { if ( $form->content_type->value == Post::type( 'page' ) ) { $subtitle = $form->settings->append( 'text', 'subtitle', 'null:null', _t( 'Subtitle: '), 'tabcontrol_text' ); $subtitle->value = $post->info->subtitle; $subtitle->move_before( $form->settings->status ); } } /** * Handle update of subtitle * @param Post $post The post being updated * @param FormUI $form. The form from the publish page **/ public function action_publish_post( $post, $form ) { if ( $post->content_type == Post::type( 'page' ) ) { $post->info->subtitle = $form->subtitle->value; } } /** * Enable update notices to be sent using the Habari beacon **/ public function action_update_check() { Update::add( 'PageSubtitle', 'f5afa528-3b71-422f-bfd7-f361e3d54bda', $this->info->version ); } } ?> <file_sep><?php /** * Prestige is a custom Theme class for the Prestige theme. * */ // We must tell Habari to use MyTheme as the custom theme class: define( 'THEME_CLASS', 'PrestigeTheme' ); /** * A custom theme for Prestige output */ class PrestigeTheme extends Theme { function action_init_theme() { // Apply Format::autop() to post content... Format::apply( 'autop', 'post_content_out' ); // Apply Format::autop() to comment content... Format::apply( 'autop', 'comment_content_out' ); // Apply Format::tag_and_list() to post tags... Format::apply( 'tag_and_list', 'post_tags_out' ); // Only uses the <!--more--> tag, with the 'more' as the link to full post Format::apply_with_hook_params( 'more', 'post_content_out', 'more' ); // Creates an excerpt option. echo $post->content_excerpt; Format::apply( 'autop', 'post_content_excerpt'); Format::apply_with_hook_params( 'more', 'post_content_excerpt', '<span class="more">Read more</span>', 150, 1 ); // Excerpt for lead article Format::apply( 'autop', 'post_content_lead'); Format::apply_with_hook_params( 'more', 'post_content_lead', '<span class="more">Read more</span>', 400, 1 ); // Apply Format::nice_date() to post date... Format::apply( 'nice_date', 'post_pubdate_out', 'F j, Y' ); // Apply Format::nice_time() to post date... //Format::apply( 'nice_time', 'post_pubdate_out', 'g:ia' ); // Apply Format::nice_date() to comment date Format::apply( 'nice_date', 'comment_date_out', 'F j, Y g:ia'); } /** * Add additional template variables to the template output. * * This function gets executed *after* regular data is assigned to the * template. So the values here, unless checked, will overwrite any existing * values. */ public function add_template_vars() { if( !$this->template_engine->assigned( 'pages' ) ) { $this->assign('pages', Posts::get( array( 'content_type' => 'page', 'status' => Post::status('published'), 'nolimit' => true ) ) ); } if( !$this->template_engine->assigned( 'asides' ) ) { //For Asides loop in sidebar.php $this->assign( 'asides', Posts::get( array( 'tag'=>'aside', 'limit'=>5) ) ); } if( !$this->template_engine->assigned( 'recent_comments' ) ) { //for recent comments loop in sidebar.php $this->assign('recent_comments', Comments::get( array('limit'=>5, 'status'=>Comment::STATUS_APPROVED, 'orderby'=>'date DESC' ) ) ); } if( !$this->template_engine->assigned( 'more_posts' ) ) { //Recent posts in sidebar.php //visiting page/2 will offset to the next page of posts in the footer /3 etc $page=Controller::get_var( 'page' ); $pagination=Options::get('pagination'); if ( $page == '' ) { $page= 1; } $this->assign( 'more_posts', Posts::get(array ( 'content_type' => 'entry', 'status' => Post::status('published'), 'not:tag' => 'asides','offset' => ($pagination)*($page), 'limit' => 5 ) ) ); } if( !$this->template_engine->assigned( 'all_tags' ) ) { // List of all the tags $this->assign('all_tags', Tags::get() ); } if( !$this->template_engine->assigned( 'all_entries' ) ) { $this->assign( 'all_entries', Posts::get( array( 'content_type' => 'entry', 'status' => Post::status('published'), 'nolimit' => 1 ) ) ); } parent::add_template_vars(); Stack::add('template_header_javascript', Site::get_url('scripts') . "/jquery.js", 'jquery' ); Stack::add('template_header_javascript', Site::get_url('theme') . "/js/jquery.bigframe.js", 'jquery.bigframe', 'jquery' ); Stack::add('template_header_javascript', Site::get_url('theme') . "/js/jquery.dimensions.js", 'jquery.dimensions', 'jquery' ); Stack::add('template_header_javascript', Site::get_url('theme') . "/js/jquery.tooltip.js", 'jquery.tooltip', 'jquery' ); } public function act_display_home( $user_filters= array() ) { //To exclude aside tag from main content loop parent::act_display_home( array( 'not:tag' => 'aside' ) ); } public function action_theme_header( $theme ) { } public function theme_next_post_link( $theme ) { $next_link = ''; if( isset( $theme->post ) ) { $next_post= $theme->post->ascend(); if( ( $next_post instanceOf Post ) ) { $next_link= 'Older <a href="' . $next_post->permalink. '" title="' . $next_post->title .'" >' . '&laquo; ' .$next_post->title . '</a>'; } } return $next_link; } public function theme_prev_post_link( $theme ) { $prev_link = ''; if( isset( $theme->post ) ) { $prev_post= $theme->post->descend(); if( ( $prev_post instanceOf Post) ) { $prev_link= 'Newer <a href="' . $prev_post->permalink. '" title="' . $prev_post->title .'" >' . $prev_post->title . ' &raquo;' . '</a>'; } } return $prev_link; } public function theme_commenter_link($comment) { $link = ''; if( strlen( $comment->url ) && $comment->url != 'http://' ) { $link = '<a href="' . $comment->url . '" >' . $comment->name . '</a>'; } return $link; } public function theme_feed_site( $theme ) { return URL::get( 'atom_feed', array( 'index' => '1' ) ); } public function theme_comment_form( $theme ) { $ui = new FormUI( 'comments_form' ); $ui->set_option( 'form_action', URL::get( 'submit_feedback', array( 'id' => $theme->post->id ) ) ); $comment_fieldset = $ui->append( 'fieldset', 'content_box', _t( 'Add To The Discussion' ) ); $commentContent = $comment_fieldset->append( 'textarea', 'commentContent', 'null:null', _t( 'Comment' )); $commentContent->value = $theme->commenter_content; $commentContent->id = 'content'; $commentContent->control_title = 'Add to the discussion. Required.'; $commentContent->cols = 70; $comment_info_fieldset = $ui->append('fieldset', 'commenter_info', _t( 'A Little Info About You' ) ); $name = $comment_info_fieldset->append( 'text', 'ename', 'null:null', _t( 'Name' ) ); $name->value = $theme->commenter_name; $name->id = 'name'; $name->control_title = 'Your name. Required'; $email = $comment_info_fieldset->append( 'text', 'email', 'null:null', _t('Email' )); $email->value = $theme->commenter_email; $email->id = $email->name; $email->control_title = "Your email address. Required, but not published"; $url = $comment_info_fieldset->append( 'text', 'url', 'null:null', _t( 'Web Address' ) ); $url->value = $theme->commenter_url; $url->id = $url->name; $url->control_title = 'Enter your homepage.'; $submit = $ui->append( 'submit', 'submit', _t( 'Say It' ) ); $submit->id = $submit->name; $ui->out(); } } ?> <file_sep><?php class Commentated extends Plugin { public function action_init_theme() { Stack::add( 'template_header_javascript', Site::get_url('scripts') . '/jquery.js', 'jquery' ); Stack::add( 'template_header_javascript', URL::get_from_filesystem(__FILE__) . '/commentated.js', 'commentated' ); } } ?><file_sep><?php class TracDashModule extends Plugin { private $theme; /** * action_plugin_activation * Registers the core modules with the Modules class. * @param string $file plugin file */ function action_plugin_activation( $file ) { if ( Plugins::id_from_file( $file ) == Plugins::id_from_file( __FILE__ ) ) { Modules::add( 'My Tickets' ); if ( Options::get( 'tracdashmodule__trac_query' ) == null ) { Options::set( 'tracdashmodule__trac_query', 'enter query' ); } } } /** * Add the Configure option for the plugin * * @access public * @param array $actions * @return array */ public function filter_plugin_config( $actions ) { $actions[] = _t( 'Configure' ); return $actions; } /** * action_plugin_deactivation * Unregisters the module. * @param string $file plugin file */ function action_plugin_deactivation( $file ) { Modules::remove_by_name( 'My Tickets' ); } /** * filter_dash_modules * Registers the core modules with the Modules class. */ function filter_dash_modules( $modules ) { $modules[] = 'My Tickets'; //currently not using this //$this->add_template( 'dash_latesttickets', dirname( __FILE__ ) . '/dash_latesttickets.php' ); return $modules; } /** * Plugin UI - Displays the various config options depending on the "option" * chosen. * * @access public * @param string $plugin_id * @param string $action * @return void */ public function action_plugin_ui( $plugin_id, $action ) { $ui = new FormUI( strtolower( __CLASS__ ) ); switch ( $action ){ case _t( 'Configure' ) : $ui = new FormUI( strtolower( __CLASS__ ) ); $post_fieldset = $ui->append( 'fieldset', 'post_settings', _t( 'Fetch trac tickets using custom query', 'tracdashmodule' ) ); $trac_query = $post_fieldset->append( 'textmulti', 'trac_query', 'tracdashmodule__trac_query', _t( 'Enter custom query:', 'tracdashmodule' ) ); $ui->on_success( array( $this, 'updated_config' ) ); $ui->append( 'submit', 'save', _t( 'Save', 'tracdashmodule' ) ); $ui->out(); break; } } /** * Give the user a session message to confirm options were saved. **/ public function updated_config( FormUI $ui ) { Session::notice( _t( 'Trac options saved.', 'tracdashmodule' ) ); $ui->save(); } /** * filter_dash_module_trac_tickets * Gets the latest entries module * @param string $module * @return string The contents of the module */ public function filter_dash_module_my_tickets( $module ) { //add assets when module is on page Stack::add( 'admin_footer_javascript', 'http://yui.yahooapis.com/3.2.0/build/yui/yui.js'); Stack::add( 'admin_footer_javascript', Site::get_url('user') . '/plugins/tracdashmodule/tracdashmodule.js'); $items = false; $cache = false; //get rss feeds from admin configuration $trac_query = Options::get( 'tracdashmodule__trac_query' ); //if multiple then join $trac_query = ( count($trac_query) > 1 ) ? implode('","',$trac_query) : $trac_query[0]; //yql query to extract what we want from feeds & return json $query = "http://query.yahooapis.com/v1/public/yql?q=select%20link%2Ctitle%20from%20rss%20where%20url%20in(%22".urlencode($trac_query)."%22)&format=json&diagnostics=false"; try { $r = new RemoteRequest( $query ); $r->set_timeout( 10 ); $r->execute(); $response = $r->get_response_body(); $json = json_decode($response,1); $items = $json['query']['results']['item']; } catch ( Exception $e ) { //if request failed, then check cache to show last group of tickets if ( Cache::has( 'my_tickets' ) ) { $items = Cache::get( 'my_tickets' ); } //log error EventLog::log( _t( 'TracDashModule error: %1$s', array( $e->getMessage() ), 'tracdashmodule' ), 'err', 'plugin', 'tracdashmodule' ); $item = (object) array ( 'text' => 'Unable to fetch Trac Tickets.', 'time' => '', 'image_url' => '' ); if ( ! $items ) { $items[] = $item; } } //end catch // Cache (even errors) to avoid hitting rate limit. We only use the cache as fallback when api fails Cache::set( 'my_tickets', $items, ( $cache !== false ? $cache : 9000 ) ); // , true ); $html = '<ul class="trac">'; foreach( $items as $k => $v ) { $html .= '<li class="item"><a class="minor" href="'.$v['link'].'">'.$v['title'].'</a></li>'; } $html .= '</ul>'; $module[ 'title' ] == 'Trac Module'; $module[ 'content' ] = $html; return $module; } } ?><file_sep>$(document).ready(function() { var loupe = $('#timeline'); loupe.hover( function() { $('#timeline').animate({ top: "0" }, 500 ); }, function() { $('#timeline').animate({ top: "-35" }, 500 ); } ); });<file_sep><?php /** * Twitter Avatar * Twitter avatar plugin * to use this plugin, please add "<?php echo $comment->twitter_avatar; ?>" * * @package twitter_avatar * @version $Id$ * @author ayunyan <<EMAIL>> * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link http://twitter.com/ * @link http://gravatar.com/ */ class TwitterAvatar extends Plugin { /** * action: plugin_activation * * @access public * @param string $file * @return void */ public function action_plugin_activation($file) { if (Plugins::id_from_file($file) != Plugins::id_from_file(__FILE__)) return; Options::set('twitter_avatar__cache_expire', 24); Options::set('twitter_avatar__default_icon', ''); Options::set('twitter_avatar__fallback_gravatar', true); } /** * action: init * * @access public * @return void */ public function action_init() { $this->load_text_domain('twitter_avatar'); } /** * action: update_check * * @access public * @return void */ public function action_update_check() { Update::add( 'Twitter Avatar', '3d327504-f01b-11dd-bd4c-001b210f913f', $this->info->version); } /** * action: plugin_ui * * @access public * @param string $plugin_id * @param string $action * @return void */ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id != $this->plugin_id()) return; if ($action == _t('Configure')) { $form = new FormUI(strtolower(get_class($this))); $form->append('text', 'cache_expire', 'twitter_avatar__cache_expire', _t('Cache Expire (hour):', 'twitter_avatar')); $form->append('text', 'default_icon', 'twitter_avatar__default_icon', _t('Default Icon URL:', 'twitter_avatar')); $form->append('checkbox', 'fallback_gravater', 'twitter_avatar__fallback_gravatar', _t('Fallback to Gravater: ', 'twitter_avatar')); $form->append('submit', 'save', _t('Save')); $form->out(); } } /** * filter: plugin_config * * @access public * @return array */ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()) { $actions[] = _t('Configure'); } return $actions; } /** * filter: commenct_twitter_avatar * * @param * @return string */ public function filter_comment_twitter_avatar($out, $comment) { if (empty($comment->email)) { $twitter_user = false; } elseif (Cache::has('twitter_avatar_' . $comment->email)) { $twitter_user = Cache::get('twitter_avatar_' . $comment->email); } else { $request = new RemoteRequest('http://twitter.com/users/show.json?email=' . $comment->email, 'GET', 5); $result = $request->execute(); if ($result !== true) { $twitter_user = false; } else { $twitter_user = json_decode($request->get_response_body()); } // Invalid response if ($twitter_user !== false && !isset($twitter_user->screen_name)) { $twitter_user = false; } else { Cache::set('twitter_avatar_' . $comment->email, $twitter_user, Options::get('twitter_avatar__cache_expire') * 3600); } } if ($twitter_user !== false) { return '<a href="http://twitter.com/' . $twitter_user->screen_name . '"><img src="' . $twitter_user->profile_image_url . '" class="twitter_avatar" alt="' . $twitter_user->screen_name . '" /></a>'; } elseif (Options::get('twitter_avatar__fallback_gravatar')) { $query = array(); $query['gravatar_id'] = md5(strtolower($comment->email)); $default_icon = Options::get('twitter_avatar__default_icon'); if (!empty($default_icon)) $query['default'] = urlencode($default_icon); return '<img src="http://www.gravatar.com/avatar.php?' . http_build_query($query, '', '&amp;') . '" class="twitter_avatar" alt="' . $comment->name . '" />'; } else { $default_icon = Options::get('twitter_avatar__default_icon'); if (!empty($default_icon)) { return '<img src="' . $default_icon . '" class="twitter_avatar" alt="' . $comment->name . '" />'; } else { return ''; } } } } ?> <file_sep><?php if ($posts) { echo '<ul class="breezy-monthly-archive">'; foreach ($posts as $post) { if ($show_comment_count) { printf('<li class="post"><a href="%1$s" rel="bookmark">%2$s</a> <span class="comment-count" title="%3$s">%4$d</span></li>', $post->permalink, $post->title_out, sprintf(_n('%1$d Comment', '%1$d Comments', $post->comments->approved->count, $this->class_name), $post->comments->approved->count), $post->comments->approved->count); } else { printf('<li class="post"><a href="%1$s" rel="bookmark">%2$s</a></li>', $post->permalink, $post->title_out); } } if ($current_page > 1 || $page_total > 1) { echo '<li class="pagination">'; if ($current_page > 1) { printf('<a href="%1$s" class="pager-prev">%2$s</a>', $prev_page_link, $prev_page_text); } if ($page_total > $current_page) { printf('<a href="%1$s" class="pager-next">%2$s</a>', $next_page_link, $next_page_text); } echo '</li>'; } echo '</ul>'; } ?><file_sep><?php /** * Highlighter Plugin * * Using this plugin is simple. To highlight inline source using GeSHi, * just surround your code in <div class="highlight php"> ... </div> * * Where "php" could be any language supported by GeSHi. * * I also recommend you use CDATA blocks (which the plugin will automatically * strip), just in case the plugin is ever disabled: * * <div class="highlight php"> * <![CDATA[ * <?php * $foo = 'bar'; * ?> * ]]> * </div> * * Note, you'll also need to grab GeSHi from http://qbnz.com/highlighter/ and * unpack the archive to: [habari directory]/3rdparty/geshi * * THIS PLUGIN REQUIRES HABARI 0.7-dev! IT WILL NOT WORK ON 0.6 (needs at least r3475) */ class HighlightPlugin extends Plugin { public function action_init() { spl_autoload_register( array( __CLASS__, '_autoload') ); Format::apply( 'do_highlight', 'post_content_out' ); Format::apply( 'do_highlight', 'comment_content_out' ); } public static function _autoload( $class_name ) { if ( strtolower( $class_name ) == 'geshi' ) { require HABARI_PATH . "/3rdparty/geshi/geshi.php"; } } } class GeshiHighlighterFormatPlugin extends Format { public static function do_highlight( $in ) { // Look, ma! No Regex! $tokenizer = new HTMLTokenizer( $in, false ); $tokens = $tokenizer->parse(); $slices = $tokens->slice( array('div','pre','code') , array( 'class' => 'highlight' ) ); foreach ($slices as $slice) { $classes = array_filter( explode( ' ', trim( str_replace( 'highlight', '', $slice[0]['attrs']['class'] ) ) ) ); // ugly, refactor $slice->trim_container(); // trims off the div $sliceValue = trim( (string)$slice ); $sliceCacheName = 'plugin.highlight.' . md5($sliceValue); if ( Cache::has( $sliceCacheName ) ) { $geshiOutput = Cache::get( $sliceCacheName ); } else { // capture the first class (not "highlight") if ( substr( $sliceValue, 0, 9 ) == '<![CDATA[' && substr( $sliceValue, -3 ) == ']]>' ) { // trim off CDATA wrapper: $sliceValue = substr( $sliceValue, 9, -3 ); } $geshi = new Geshi( trim( $sliceValue ), isset( $classes[0] ) ? $classes[0] : 'php', HABARI_PATH . '/3rdparty/geshi/geshi/' ); $geshi->set_header_type( GESHI_HEADER_PRE ); $geshi->set_overall_class( 'geshicode' ); $geshiOutput = @$geshi->parse_code(); // @ is slow, but geshi is full of E_NOTICE Cache::set( $sliceCacheName, $geshiOutput ); } $slice->tokenize_replace( $geshiOutput ); $tokens->replace_slice( $slice ); } return (string) $tokens; } } ?><file_sep><?php /** * Keep Login plugin * **/ class KeepLogin extends Plugin { /** * function info * Returns information about this plugin * @return array Plugin info array **/ function info() { return array ( 'name' => 'Keep Login', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'version' => '1.1', 'description' => 'Uses ajax to keep a session logged in in the admin.', 'license' => 'Apache License 2.0', ); } /** * Add output in the admin header * Adds the necessary javascript to make periodic ajax calls to the admin. */ public function action_admin_header() { $ajaxurl = URL::get('auth_ajax', array('context'=>'keep_session')); $script = <<< HEADER_JS $(document).ready(function(){ window.setInterval( function(){ $.post('$ajaxurl'); }, 1000 * 60 * 5 // 5 minutes ); }); HEADER_JS; Stack::add( 'admin_header_javascript', $script, 'keep_login', array('jquery') ); } public function action_auth_ajax_keep_session() { echo time(); } } ?><file_sep><?php class Reportr extends Plugin { const SILO_NAME = 'Scribd'; static $secret_report_cache = array(); public function action_update_check() { Update::add( $this->info->name, '14f9f07a-e40d-4275-83b3-403024a00460', $this->info->version ); } public function action_init() { // self::install(); $this->add_template('scribdr', dirname(__FILE__) . '/formcontrol.scribdr.php'); $this->add_rule('"reports"', 'display_reports'); $this->add_rule('"reports"/"tag"/tag', 'display_reports_by_tag'); // exit; } /** * Handle register_page action **/ public function action_plugin_act_display_reports($handler) { $reports = self::get_reports(); $handler->theme->view_tag = false; $handler->theme->reports = $reports; $handler->theme->display('report.multiple'); } /** * Handle register_page action **/ public function action_plugin_act_display_reports_by_tag($handler) { $tag = $handler->handler_vars['tag']; $reports = self::get_reports( array( "tag" => $tag ) ); $handler->theme->view_tag = $tag; $handler->theme->reports = $reports; $handler->theme->display('report.multiple'); } public function action_plugin_activation( $plugin_file ) { self::install(); } public function action_plugin_deactivation( $plugin_file ) { Post::deactivate_post_type( 'report' ); } public static function get_reports( $params = array() ) { $params['content_type'] = Post::type('report'); $params['nolimit'] = true; if( $params['tag'] != NULL ) { $params['vocabulary'] = array( 'tags:term' => $params['tag'] ); unset( $params['tags'] ); } return Posts::get( $params ); } /** * install various stuff we need */ public static function install() { /** * Register content type **/ Post::add_new_type( 'report' ); // Give anonymous users access $group = UserGroup::get_by_name('anonymous'); $group->grant('post_report', 'read'); } /** * Create name string **/ public function filter_post_type_display($type, $foruse) { $names = array( 'report' => array( 'singular' => _t('Report'), 'plural' => _t('Reports'), ) ); return isset($names[$type][$foruse]) ? $names[$type][$foruse] : $type; } /** * Modify publish form */ public function action_form_publish($form, $post) { if ($post->content_type == Post::type('report')) { $form->content->caption = _t( 'Summary' ); $file= $form->append('file', 'file', 'null:null', _t('URL'), 'scribdr'); $form->move_after($file, $form->title); $id= $form->append('text', 'report_id', 'null:null', _t('ID'), 'admincontrol_text'); $form->move_after($id, $form->file); if( $post->report != NULL ) { // Scribd revisions seem to be buggy $file->remove(); $id->remove(); // Utils::debug( $post->report ); // $form->append('static', 'overwrite_warning', '<div class="container transparent">' . sprintf( _t( 'If you upload a new file, it will overwrite the <a href="%s">existing</a> one.' ), $post->report->url ) . '</div>'); // $form->move_before($form->overwrite_warning, $form->file); } $form->remove($form->silos); } } /** * Save our report */ public function action_publish_post( $post, $form ) { if ($post->content_type == Post::type('report')) { $this->action_form_publish($form, $post); $api = new ScribdAPI; // $pathinfo = pathinfo( $_FILES[$form->file->field]['name'] ); if( $form->file->tmp_file != '' ) { $pathinfo = pathinfo( $_FILES[$form->file->field]['name'] ); // We have an upload if( $post->report == NULL) { // New report $results = $api->upload( $form->file->tmp_file, $pathinfo ); if( $results == FALSE ) { // Error logic } else { $post->info->report_id = $results['id']; $post->info->report_key = $results['key']; } } else { // Update existing report; $results = $post->report->replace( $form->file->tmp_file, $pathinfo ); if( $results == FALSE ) { // Error logic } else { // Utils::debug( $results, $post->report ); // exit; } } } // Utils::debug( $form->report_id != '' ); if( $form->report_id->value != '' ) { $results = $api->get_info ( $form->report_id->value ); $post->info->report_id = $form->report_id->value; $post->info->report_key = $results['access_key']; // Utils::debug( $results ); } // exit; $post->save(); $post->report->title = $form->title->value; $post->report->description = $form->content->value; $post->report->tags = $form->tags->value; $post->report->save(); } } /** * Create the magic report property **/ public function filter_post_report($val, $post) { if($post->content_type == Post::type('report')) { if( isset( Reportr::$secret_report_cache[$post->id] ) ) { return Reportr::$secret_report_cache[$post->id]; } if( !isset( $post->info->report_id) ) { // No associated report return null; } else { Reportr::$secret_report_cache[$post->id] = new Report( $post->info->report_id, $post->info->report_key); return Reportr::$secret_report_cache[$post->id]; } } else { return $val; } } // /** // * Add rewrite rules to map post urls // * // * @param array $rules An array of RewriteRules // * @return array The array of new and old rules // */ // public function filter_rewrite_rules( $rules ) // { // // Utils::debug( $rules ); // // // return $rules; // // $rules[] = new RewriteRule( array( // 'name' => 'display_reports', // 'parse_regex' => '#^reports(?:/page/(?P<page>\d+))?/?$#i', // 'build_str' => 'reports/{$tag}(/page/{$page})', // 'handler' => 'UserThemeHandler', // 'action' => 'display_reports', // 'priority' => 1, // 'description' => 'Return posts matching specified tag.', // 'parameters' => serialize( array( 'content_type' => Post::type('report') ) ) // ) ); // // // array( 'name' => 'display_entries', 'parse_regex' => '#^(?:page/(?P<page>[2-9]|[1-9][0-9]+))/?$#', 'build_str' => '(page/{$page})', 'handler' => 'UserThemeHandler', 'action' => 'display_entries', 'priority' => 999, 'description' => 'Display multiple entries' ), // // return $rules; // return array(); // } } class ScribdAPI { function __construct() { $this->key = '<KEY>'; $this->secret = '<KEY>'; $this->pubid = 'pub-5725093775857216776'; $this->endpoint = 'http://api.scribd.com/api'; $this->conntimeout = 20; } private function get_endpoint( $method ) { $url = $this->endpoint; $url.= '?method=' . $method; $url.= '&api_key=' . $this->key; return $url; } function fetch($method, $params = array(), $tokenize = false, $debug = false) { $url = $this->get_endpoint( $method ); foreach($params as $key => $val) { $url.= '&' . $key . '=' . $val; } if($debug) { print_r($url); } $contents = RemoteRequest::get_contents($url); $data = new SimpleXMLElement($contents); if($data['stat'] == 'ok') { return $data; } else { return FALSE; } } function put($method, $params = array(), $tokenize = false, $debug = false) { $url = $this->get_endpoint( $method ); if($debug) { print_r($url); } $req = curl_init(); $params['api_key'] = $this->key; curl_setopt($req, CURLOPT_URL, $url); curl_setopt($req, CURLOPT_TIMEOUT, 0); // curl_setopt($req, CURLOPT_INFILESIZE, filesize($photo)); // Sign and build request parameters curl_setopt($req, CURLOPT_POSTFIELDS, $params); curl_setopt($req, CURLOPT_CONNECTTIMEOUT, $this->conntimeout); curl_setopt($req, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($req, CURLOPT_HEADER, 0); curl_setopt($req, CURLOPT_RETURNTRANSFER, 1); $this->_http_body = curl_exec($req); if (curl_errno($req)){ throw new Exception(curl_error($req)); } curl_close($req); $xml = simplexml_load_string($this->_http_body); if( $xml['stat'] == 'ok') { return $xml; } else { Utils::debug( $xml, $params, $url ); $result = false; } return $result; } /** * Gets a list of documents for an (optionally) specified user **/ public function getDocs( $user = NULL ) { $xml = $this->fetch('docs.getList'); // Utils::debug( $xml ); $docs = array(); foreach($xml->resultset->result as $doc) { // $report = new Report; $report->id = (string) $doc->doc_id; $report->thumbnail = (string) $doc->thumbnail_url; $report->title = (string) $doc->title; // $props['url'] = "http://farm{$photo['farm']}.static.flickr.com/{$photo['server']}/{$photo['id']}_{$photo['secret']}$size.jpg"; // $props['thumbnail_url'] = "http://farm{$photo['farm']}.static.flickr.com/{$photo['server']}/{$photo['id']}_{$photo['secret']}_m.jpg"; // $props['flickr_url'] = "http://www.flickr.com/photos/{$_SESSION['nsid']}/{$photo['id']}"; // $props['filetype'] = 'flickr'; // Utils::debug( $doc, $report); $docs[] = $report; } return $docs; } /** * Gets the download url of a docuemnt **/ public function getURL( $doc_id, $format = "original" ) { $params = array( "doc_id" => $doc_id, "doc_type" => $format ); $xml = $this->fetch('docs.getDownloadUrl', $params); // Utils::debug( $xml ); if( $xml ) { return (string) $xml->download_link; } else { return false; } } function changeSettings( $doc_id, $settings ) { $args = $settings; $args['doc_ids'] = $doc_id; $result = $this->put( 'docs.changeSettings', $args ); if( $result != false ) { return true; } else { return false; } } function getSettings( $doc_id ) { $args = array(); $args['doc_id'] = $doc_id; $result = $this->fetch( 'docs.getSettings', $args ); if( $result != false ) { $settings = array( "title" => (string) $result->title, "description" => (string) $result->description, ); $settings["tags"] = explode(",", (string) $result->tags); $settings["download_formats"] = explode(",", (string) $result->download_formats); $settings["access_key"] = (string) $result->access_key; return $settings; } else { return false; } } function get_info( $doc_id ) { return $this->getSettings( $doc_id ); } function upload( $file, $pathinfo = array(), $replace = FALSE ) { $args['file'] = '@' . $file; if( $replace ) { $args['rev_id'] = $replace; } if( isset( $pathinfo['extension'] ) ) { $args['doc_type'] = $pathinfo['extension']; } $xml = $this->put( 'docs.upload', $args ); if( $xml ) { $result = array( 'id' => (string) $xml->doc_id, 'key' => (string) $xml->access_key ); } else { $result = false; } return $result; } } class Report { public $api; private $settings = array(); private $changed; private $download_url; function __construct( $id, $key ) { $this->id = $id; $this->key = $key; $this->api = new ScribdAPI; } public function __set( $name, $value ) { switch( $name ) { case 'description': case 'title': case 'tags': $this->settings[$name] = $value; $this->changed = TRUE; break; default; $this->{$name} = $value; break; } } public function __get( $name ) { switch( $name ) { case 'pdf': case 'text': case 'original': if( !isset( $this->{$name . "_url"} ) ) { $this->{$name . "_url"} = $this->api->getURL( $this->id, $name ); } return $this->{$name . "_url"}; case 'url': return 'http://www.scribd.com/doc/' . $this->id; break; case 'formats': $formats = array(); foreach( $this->download_formats as $format ) { if( $format == 'text' ) { // buggy continue; } switch( $format ) { case 'text': case 'original': $string = ucfirst( $format ); break; default: $string = strtoupper( $format ); break; } $formats[$format] = $string; } return $formats; break; case "download_formats": case 'description': case 'title': case 'tags': if( !isset( $this->settings[$name] ) ) { $settings = $this->api->getSettings( $this->id ); $this->settings = $settings; } return $this->settings[$name]; break; default; return $this->{$name}; break; } } public function save() { if( !$this->changed ) { return; } if( $this->api->changeSettings( $this->id, $this->settings) ) { $this->changed = false; return true; } else { return false; } } public function replace( $file, $pathinfo = array() ) { if( $results = $this->api->upload( $file, $pathinfo, $this->id ) ) { return true; } else { return false; } } } ?> <file_sep><!-- This file can be copied and modified in a theme directory --> <h2><?php echo $theme->colophon_title; ?></h2> <p><?php echo $theme->colophon_text; ?></p><file_sep><?php include_once(dirname(__FILE__) . '/simple_html_dom.php'); class PluginLoader extends Plugin { const CORE_SVN_REPO = 'http://svn.habariproject.org/habari-extras/plugins/'; public function action_init() { $this->add_template('plugins.loader', dirname(__FILE__) . '/plugins.loader.php'); } public function filter_plugin_loader($existing_loader, Theme $theme) { $infos = array(); foreach($this->get_repos() as $repo) { $infos = array_merge($infos, $this->scrape_repo($repo)); } //Utils::debug($theme->inactive_plugins); $plugins = array(); $id = 0; foreach($infos as $key => $info) { $xinfo = reset($info); $id = sprintf( '%x', crc32( $key ) ); $plugins[$id] = array( 'plugind_id' => $id, 'file' => '', 'debug' => false, 'info' => new SimpleXMLElement($xinfo), 'active' => false, 'verb' => 'Download', ); foreach($info as $version => $xinfo) { $plugins[$id]['actions'][$version] = array( 'url' => URL::get( 'admin', 'page=plugin_download&plugin_id=' . $id . '&version=' . $version ), 'caption' => _t('Get %s', array($version)), 'action' => 'download-', ); } } $theme->loadable = $plugins; $loader = $theme->fetch('plugins.loader'); return $existing_loader . $loader; } public function scrape_repo($repo) { if(Cache::has('plugin.loader.repo.infos.' . $repo)) { $hrefs = Cache::get('plugin.loader.repo.infos.' . $repo); } else { $hrefs = array(); } if(Cache::has('plugin.loader.repo.dirs.' . $repo)) { $donedirs = Cache::get('plugin.loader.repo.dirs.' . $repo); } else { $donedirs = array(); } // Get the list of plugins foreach($this->get_links($repo) as $href) { $plugindirs[] = $href; } $ct = 0; foreach($plugindirs as $plugindir) { if(in_array($plugindir, $donedirs)) continue; if(++$ct > 5) break; // Only do 5 at a time foreach($this->get_links($repo . '/' . $plugindir . '/trunk') as $href) { if(preg_match('#\.plugin\.xml$#i', $href)) { // This is a plugin's info and the current directory is the plugin directory $info = RemoteRequest::get_contents($repo . '/' . $plugindir . '/trunk/' . $href); $hrefs[$repo . $plugindir] = is_array($hrefs[$repo. $plugindir]) ? $hrefs[$repo . $plugindir] : array(); $hrefs[$repo . $plugindir]['trunk'] = $info; } } foreach($this->get_links($repo . '/' . $plugindir . '/tags') as $tag) { foreach($this->get_links($repo . '/' . $plugindir . '/tags/' . $tag) as $href) { if(preg_match('#\.plugin\.xml$', $href)) { // This is a plugin's info in a tag and the current directory is the plugin directory $info = RemoteRequest::get_contents($repo . '/' . $plugindir . '/trunk/' . $href); $hrefs[$repo . $plugindir] = is_array($hrefs[$repo . $plugindir]) ? $hrefs[$repo . $plugindir] : array(); $hrefs[$repo . $plugindir][$tag] = $info; } } } $donedirs[] = $plugindir; } if($ct > 0) { Cache::set('plugin.loader.repo.infos.' . $repo, $hrefs); Cache::set('plugin.loader.repo.dirs.' . $repo, $donedirs); } return $hrefs; } function get_links($url) { $html = RemoteRequest::get_contents($url); $dom = str_get_html($html); $as = $dom->find('a'); $hrefs = array(); foreach($as as $a) { $href = rtrim($a->getAttribute('href'), '/'); if(strpos($href, '..') !== false || strpos($href, '/') !== false) { } else { $hrefs[] = $href; } } $dom->clear(); return $hrefs; } public function get_repos() { return array('http://svn.habariproject.org/habari-extras/plugins/'); } public function filter_admin_access_tokens( array $require_any, $page ) { switch ( $page ) { case 'plugin_download': $require_any = array( 'manage_plugins' => true ); break; } return $require_any; } public function action_admin_theme_get_plugin_download( AdminHandler $handler, Theme $theme ) { $theme->page_content = ''; $plugin_id = $handler->handler_vars['plugin_id']; $version = $handler->handler_vars['version']; foreach($this->get_repos() as $repo) { $infos = $this->scrape_repo($repo); foreach($infos as $infokey => $info) { if(sprintf( '%x', crc32( $infokey ) ) == $plugin_id) { $downloadurl = $infokey; if($version == 'trunk') { $downloadurl .= '/trunk/'; } else { $downloadurl .= '/tags/' . $version . '/'; } if($this->download($downloadurl, HABARI_PATH . '/user/plugins/', basename($infokey))) { Session::notice(_t('Downloaded the "%s" plugin. It must now be activated before use.', array(basename($infokey)))); } else { Session::notice(_t('There was an error downloading the "%s" plugin', array(basename($infokey)))); } //Utils::debug($downloadurl);die(); Utils::redirect(URL::get('admin', 'page=plugins')); } } } } public function download($source, $destination, $as = null) { echo '<pre>'; var_dump($source, $destination); $rr = new RemoteRequest($source); if($rr->execute()) { $response = $rr->get_response_body(); $headers = $rr->get_response_headers(); if(isset($headers['Location']) && $headers['Location'] != $source) { // This should probably count redirects and bail after some max value return $this->download($headers['Location'], $destination); } $basename = basename($source); if(isset($as)) { $basename = $as; } if(strpos($headers['Content-Type'], 'text/html') !== false) { if(file_exists($destination . $basename) || mkdir($destination . $basename)) { //Session::notice(_t('Created the "%s" directory', array($basename))); $dom = str_get_html($response); $as = $dom->find('a'); $hrefs = array(); foreach($as as $a) { $href = rtrim($a->getAttribute('href'), '/'); if(strpos($href, '..') !== false || strpos($href, '/') !== false) { } else { $this->download($source . $href, $destination . $basename . '/'); } } $dom->clear(); } else { Session::error(_t('Could not create the directory for the plugin')); return false; } } else { //Session::notice(_t('Downloaded "%s" to the plugin directory', array($basename))); file_put_contents($destination . $basename, $response); //file_put_contents($destination . $basename . '.header', print_r($headers,1)); } } return true; } } ?> <file_sep><?php class FileMan extends Plugin { public function filter_admin_access_tokens(array $require_any, $page){ /* Set access tokens */ switch ($page) { case 'fileman': $require_any = array('fileman' => true); break; } return $require_any; } public function action_init() { /* Give FileMan its own page */ $this->add_template('fileman', dirname($this->get_file()) . '/fileman.php'); } public function filter_adminhandler_post_loadplugins_main_menu(array $menu){ /* Add FileMan to the main menu */ /* Set menu variables */ $item_menu = array('pagename' => array( 'url' => URL::get('admin','page=fileman'), 'title' => _t('File Manager'), 'text' => _t('FileMan'), 'hotkey' => 'F', 'selected' => false ) ); /* Do stuff */ $slice_point = array_search('options', array_keys($menu)); array_splice($menu, $slice_point, 0, $item_menu); return $menu; } } ?> <file_sep> <li id="widget-twitter" class="widget"> <h3><?php _e('Soliloquy', 'demorgan'); ?></h3> <p> <?php printf('%1$s <br /><a href="http://twitter.com/%2$s">' . _t('Read more…', 'demorgan') . '</a>', $tweet_text, urlencode(Options::get('twitter__username')), $tweet_time); ?> </p> </li> <file_sep><!-- commentsform --> <h3 id="respond">Leave a Reply</h3> <?php if ( Session::has_errors() ) { Session::messages_out(); } $post->comment_form()->out(); ?> <!-- commentsform --> <file_sep><?php $theme->display( 'header' ); ?> <div class="container"> <?php echo $theme->page_content; ?> </div> <?php $theme->display( 'footer' ); ?> <file_sep><?php /********************************** * * Word Count for Posts * * usage: <?php echo $post->word_count; ?> * *********************************/ class PostWordCount extends Plugin { public function action_post_update_after( $post ) { $allcharacters = 'ÁÀÂÄǍĂĀÃÅǺĄƁĆĊĈČÇĎḌƊÉÈĖÊËĚĔĒĘẸƎƏƐĠĜǦĞĢƔĤḤĦIÍÌİÎÏǏĬĪĨĮỊĴĶƘĹĻŁĽĿŃŇÑŅÓÒÔÖǑŎŌÕŐỌØǾƠŔŘŖŚŜŠŞȘṢŤŢṬÚÙÛÜǓŬŪŨŰŮŲỤƯẂẀŴẄǷÝỲŶŸȲỸƳŹŻŽẒáàâäǎăāãåǻąɓćċĉčçďḍɗéèėêëěĕēęẹǝəɛġĝǧğģɣĥḥħıíìiîïǐĭīĩįịĵķƙĸĺļłľŀʼnńňñņóòôöǒŏōõőọøǿơŕřŗśŝšşșṣſťţṭúùûüǔŭūũűůųụưẃẁŵẅƿýỳŷÿȳỹƴźżžẓΑΆΒΓΔΕΈΖΗΉΘΙΊΪΚΛΜΝΞΟΌΠΡΣΤΥΎΫΦΧΨΩΏαάβγδεέζηήθιίϊΐκλμνξοόπρσςτυύϋΰφχψωώÆǼǢÐĐIJŊŒÞŦæǽǣðđijŋœßþŧ'; $post->info->wordcount = str_word_count( strip_tags( ( $this->config[ 'add_title' ] ? $post->content . " {$post->title}" : $post->content ) ), 0, $allcharacters ); $post->info->commit(); } public function configure() { $class_name= strtolower( get_class( $this ) ); $ui= new FormUI( $class_name ); $add_title= $ui->append( 'checkbox', 'add_title', $class_name . '__add_title', _t( 'Include title words in count?' ) ); $ui->append( 'submit', 'save', 'save' ); return $ui; } public function action_init() { $class_name= strtolower( get_class( $this ) ); $this->config[ 'add_title' ]= Options::get( $class_name . '__add_title' ); } public function filter_post_word_count( $word_count, $post ) { $allcharacters = 'ÁÀÂÄǍĂĀÃÅǺĄƁĆĊĈČÇĎḌƊÉÈĖÊËĚĔĒĘẸƎƏƐĠĜǦĞĢƔĤḤĦIÍÌİÎÏǏĬĪĨĮỊĴĶƘĹĻŁĽĿŃŇÑŅÓÒÔÖǑŎŌÕŐỌØǾƠŔŘŖŚŜŠŞȘṢŤŢṬÚÙÛÜǓŬŪŨŰŮŲỤƯẂẀŴẄǷÝỲŶŸȲỸƳŹŻŽẒáàâäǎăāãåǻąɓćċĉčçďḍɗéèėêëěĕēęẹǝəɛġĝǧğģɣĥḥħıíìiîïǐĭīĩįịĵķƙĸĺļłľŀʼnńňñņóòôöǒŏōõőọøǿơŕřŗśŝšşșṣſťţṭúùûüǔŭūũűůųụưẃẁŵẅƿýỳŷÿȳỹƴźżžẓΑΆΒΓΔΕΈΖΗΉΘΙΊΪΚΛΜΝΞΟΌΠΡΣΤΥΎΫΦΧΨΩΏαάβγδεέζηήθιίϊΐκλμνξοόπρσςτυύϋΰφχψωώÆǼǢÐĐIJŊŒÞŦæǽǣðđijŋœßþŧ'; return str_word_count( strip_tags( ( $this->config[ 'add_title' ] ? $post->content . " {$post->title}" : $post->content ) ), 0, $allcharacters ); } } ?> <file_sep><?php /** * Pageless Plugin */ require_once 'pagelesshandler.php'; class Pageless extends Plugin { private $config = array(); private $class_name = ''; private static $handler_vars = array(); private static function default_options() { return array ( 'num_item' => '3', 'post_class' => 'hentry', 'pager_id' => 'page-selector' ); } /** * Required plugin information * @return array The array of information **/ public function info() { return array( 'name' => 'Pageless', 'version' => '0.2', 'url' => 'http://code.google.com/p/bcse/wiki/Pageless', 'author' => '<NAME>', 'authorurl' => 'http://blog.bcse.info/', 'license' => 'Apache License 2.0', 'description' => _t('Give your blog the ability of infinite scrolling, instead of breaking content into ‘pages.’', $this->class_name) ); } /** * Add update beacon support **/ public function action_update_check() { Update::add('Pageless', '9b146781-0ee5-406a-aed5-90d661f76ade', $this->info->version); } /** * Add actions to the plugin page for this plugin * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id **/ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id === $this->plugin_id()) { $actions[] = _t('Configure', $this->class_name); } return $actions; } /** * Respond to the user selecting an action on the plugin page * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook **/ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id === $this->plugin_id()) { switch ($action) { case _t('Configure', $this->class_name): $ui = new FormUI($this->class_name); $num_item = $ui->append('text', 'num_item', 'option:' . $this->class_name . '__num_item', _t('How many posts to load each time?', $this->class_name)); $num_item->add_validator('validate_uint'); $num_item->add_validator('validate_required'); $post_class = $ui->append('text', 'post_class', 'option:' . $this->class_name . '__post_class', _t('CSS Class Name of Posts', $this->class_name)); $post_class->add_validator('validate_required'); $pager_id = $ui->append('text', 'pager_id', 'option:' . $this->class_name . '__pager_id', _t('ID of Page Selector', $this->class_name)); $pager_id->add_validator('validate_required'); // When the form is successfully completed, call $this->updated_config() $ui->append('submit', 'save', _t('Save', $this->class_name)); $ui->set_option('success_message', _t('Options saved', $this->class_name)); $ui->out(); break; } } } public function validate_uint($value) { if (!ctype_digit($value) || strstr($value, '.') || $value < 0) { return array(_t('This field must be positive integer.', $this->class_name)); } return array(); } /** * Returns true if plugin config form values defined in action_plugin_ui should be stored in options by Habari * @return bool True if options should be stored **/ public function updated_config($ui) { return true; } /** * On plugin activation, set the default options */ public function action_plugin_activation($file) { if (realpath($file) === __FILE__) { $this->class_name = strtolower(get_class($this)); foreach (self::default_options() as $name => $value) { $current_value = Options::get($this->class_name . '__' . $name); if (is_null($current_value)) { Options::set($this->class_name . '__' . $name, $value); } } } } /** * On plugin init, add the template included with this plugin to the available templates in the theme */ public function action_init() { $this->class_name = strtolower(get_class($this)); foreach (self::default_options() as $name => $value) { $this->config[$name] = Options::get($this->class_name . '__' . $name); } $this->load_text_domain($this->class_name); $this->add_template('pageless', dirname(__FILE__) . '/pageless.php'); } public function filter_rewrite_rules($rules) { $rules[] = new RewriteRule(array( 'name' => 'display_pageless', 'parse_regex' => '%^pageless/(?P<slug>[a-zA-Z0-9-]+)(?:/(?P<type>tag|date|search)/(?P<param>.+))?/?$%i', 'build_str' => 'pageless/{$slug}(/{$type}/{$param})', 'handler' => 'PagelessHandler', 'action' => 'display_pageless', 'rule_class' => RewriteRule::RULE_PLUGIN, 'is_active' => 1, 'description' => 'display_pageless' )); $rules[] = new RewriteRule(array( 'name' => 'display_pageless_js', 'parse_regex' => '%^scripts/jquery.pageless_(?P<config>[0-9a-f]{32}).js$%i', 'build_str' => 'scripts/jquery.pageless_{$config}.js', 'handler' => 'UserThemeHandler', 'action' => 'display_pageless_js', 'rule_class' => RewriteRule::RULE_PLUGIN, 'is_active' => 1, 'description' => 'display_pageless_js' )); return $rules; } public function action_handler_display_pageless_js($handler_vars) { // If 'slug' exists, then it must be single, don't do anything if (!isset($handler_vars['slug'])) { // Determine act_display $filter_type = ''; $filter_param = ''; if (isset($handler_vars['tag'])) { $filter_type = 'tag'; $filter_param = $handler_vars['tag']; } else if (isset($handler_vars['year'])) { $filter_type = 'date'; $filter_param = $handler_vars['year']; if (isset($handler_vars['month'])) { $filter_param .= '/' . $handler_vars['month']; } if (isset($handler_vars['day'])) { $filter_param .= '/' . $handler_vars['day']; } } else if (isset($handler_vars['criteria'])) { $filter_type = 'search'; $filter_param = $handler_vars['criteria']; } $out = '(function($){ $(function() { $("#' . $this->config['pager_id'] . '").hide(); $("#' . $this->config['pager_id'] . '").before("<div id=\"pageless-indicator\"></div>"); var spinner = { start: function() { $("#pageless-indicator").spinner({height:32,width:32,speed:50,image:"' . $this->get_url(TRUE) . 'spinnersmalldark.png"}); $("#pageless-indicator").show(); }, stop: function() { $("#pageless-indicator").spinner("stop"); $("#pageless-indicator").hide(); } } var the_end = false; function appendEntries() { if ($(window).scrollTop() >= $(document).height() - ($(window).height() * 2)) { var slug = $(".' . $this->config['post_class'] . ':last").attr("id").replace(/^(?:entry|page)-/, ""); $.ajax({ url: "' . URL::get('display_pageless', array('type' => $filter_type, 'param' => $filter_param)) . '".replace("{$slug}", slug), beforeSend: function() { spinner.start(); $(window).unbind("scroll", appendEntries); }, success: function(response) { if (response.length > 100) { $(".' . $this->config['post_class'] . ':last").after(response); } else { the_end = true; } }, complete: function() { spinner.stop(); if (!the_end && activated) { $(window).bind("scroll", appendEntries); } } }); } } $(window).bind("scroll", appendEntries); var activated = true; function toggleScroll() { activated = !activated; if (!the_end && activated) { $(window).bind("scroll", appendEntries); $("#' . $this->config['pager_id'] . '").hide(); appendEntries(); } else { $(window).unbind("scroll", appendEntries); $("#' . $this->config['pager_id'] . '").show(); } } $(document).bind("dblclick", toggleScroll); }); })(jQuery);'; ob_clean(); header('Content-type: text/javascript'); header('ETag: ' . md5($out)); header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 315360000) . ' GMT'); header('Cache-Control: max-age=315360000'); echo $out; } exit; } public function theme_footer() { if (count(self::$handler_vars) === 0) self::$handler_vars = Controller::get_handler_vars(); // If 'slug' exists, then it must be single, don't do anything if (!isset(self::$handler_vars['slug'])) { // If jQuery is loaded in header, then do not load it again if (!Stack::has('template_header_javascript', 'jquery')) Stack::add('template_footer_javascript', 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', 'jquery'); Stack::add('template_footer_javascript', Site::get_url('scripts') . '/jquery.spinner.js', 'jquery.spinner', 'jquery'); $params = new SuperGlobal($this->config); $params = $params->merge(self::$handler_vars); Stack::add('template_footer_javascript', URL::get('display_pageless_js', array('config' => md5(serialize($params)))), 'jquery.pageless', 'jquery'); } } } ?> <file_sep><div id="post-<?php echo $post->id; ?>" class="<?php echo $post->statusname; ?>"> <div class="post"> <div class="post-info"> <h2 class="posttitle"> <a href="<?php echo $post->permalink; ?>" title="<?php echo $post->title; ?>"> <?php echo $post->title_out; ?> </a> </h2> <p class="postmeta"> Posted by <?php echo $post->author->username; ?> on <?php echo $post->pubdate_out; ?><br /> <?php if ( is_array( $post->tags ) ) : ?> <?php echo ' tagged ' . $post->tags_out; ?> <?php endif; ?> <?php if ( $loggedin ) : ?> <a href="<?php echo $post->editlink; ?>" title="Edit post"> (edit)</a> <?php endif; ?> <br /><span class="commentslink"> <a href="<?php echo $post->permalink; ?>" title="Comments on this post"><?php echo $post->comments->approved->count; ?> <?php echo _n( 'Comment', 'Comments', $post->comments->approved->count ); ?> </a> </span> </p> </div> <!-- post-info --> <div class="postentry"> <?php if ( isset($first) && $first == false ) { echo $post->content_out; } else { echo $post->content_out; } ?> </div> <!-- .post-content --> </div> <!-- .post --> </div> <!-- #post-id .status --> <file_sep><?php class FreeStyleAdmin extends Plugin { function info() { return array( 'url' => 'http://iamgraham.net/plugins', 'name' => 'FreeStyleAdmin', 'description' => 'Allows you to load arbitrary CSS files into the admin pages.', 'license' => 'Apache License 2.0', 'author' => '<NAME>', 'authorurl' => 'http://iamgraham.net/', 'version' => '0.1' ); } public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()) { $actions[] = _t('Configure'); } return $actions; } public function action_plugin_ui($plugin_id, $action) { if ($plugin_id == $this->plugin_id()) { switch ($action) { case _t('Configure'): $ui = new FormUI(strtolower(get_class($this))); $css_location = $ui->append('text', 'css_location', 'option:freestyleadmin__css_location', _t('FreeStyle CSS Location', 'FreeStyleAdmin')); $css_location->add_validator( 'validate_required' ); $ui->append( 'submit', 'save', _t( 'Save', 'FreeStyleAdmin' ) ); $ui->set_option( 'success_message', _t( 'Configuration saved', 'FreeStyleAdmin' ) ); $ui->out(); break; } } } private static function getvar($var) { return Options::get('freestyleadmin__'.$var); } function action_admin_header() { if (self::getvar('css_location') != '') { Stack::add('admin_stylesheet', array(self::getvar('css_location'), 'screen')); } } } ?> <file_sep><?php class Autopinger extends Plugin { /** * Respond to plugin info request * * @return array Info about plugin */ function info() { return array( 'name'=>'Autopinger', 'version'=>'0.3', 'url' => 'http://habariproject.org/', 'author' => 'The Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Adds XML-RPC ping support.', 'copyright' => '2009' ); } /** * Configure beacon information for the plugin */ function action_update_check() { Update::add( 'Autopinger', 'c515ef39-b387-33e4-f14f-40628f11415b', $this->info->version ); } /** * When a post is published, add a cron entry to do pinging * * @param Post $post A post object whose status has been set to published */ public function action_post_status_published( $post) { if ( $post->status == Post::status( 'published' ) && $post->pubdate->int <= time() ) { CronTab::add_single_cron( 'ping update sites', array( 'Autopinger', 'ping_sites' ), time(), 'Ping update sites.' ); EventLog::log( 'Crontab added', 'info', 'default', null, null ); } } /** * Do the ping on the cron filter "ping_sites" * * @param boolean $result The result of the cron job, false if failed * @return boolean The result of the cron job, false if failed to get rescheduled */ public static function ping_sites($result) { $services = Options::get( 'autopinger__pingservices' ); if(!is_array($services)) { EventLog::log('No pings sent - no services configured.'); return false; } else { $count = 0; foreach($services as $service) { $rpc = new XMLRPCClient($service, 'weblogUpdates'); $ping = $rpc->ping(Options::get('title'), Site::get_url('habari')); $count++; } EventLog::log("Ping sent via XMLRPC - pinged {$count} sites.", 'info', 'default', null, $result ); return true; } } /** * Add actions to the plugin page for this plugin * * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id */ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()){ $actions[] = _t( 'Configure' ); } return $actions; } /** * Respond to the user selecting an action on the plugin page * * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook */ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id == $this->plugin_id()){ switch ($action){ case _t( 'Configure' ): $ui = new FormUI(strtolower(get_class($this))); $ping_services = $ui->append( 'textmulti', 'ping_services', 'option:autopinger__pingservices', _t( 'Ping Service URLs:' ) ); $ui->append( 'submit', 'save', 'Save' ); $ui->out(); break; } } } /** * Log ping requests to this site as a server * * @param array $params An array of incoming parameters * @param XMLRPCServer $rpcserver The server object that received the request * @return mixed The result of the request */ public function xmlrpc_weblogUpdates__ping($params, $rpcserver) { EventLog::log("Recieved ping via XMLRPC: {$params[0]} {$params[1]}", 'info', 'default' ); return true; } } ?><file_sep><?php /** * oldpriceTheme is a custom Theme class for the Habari. * * @package Habari */ /** * A custom theme for oldprice output */ class oldpriceTheme extends Theme { private $class_name = ''; private $default_options = array( 'show_author' => false, 'home_tab' => 'Blog' ); /** * Execute on theme init to apply these filters to output */ public function action_init_theme() { if ( ! Plugins::is_loaded('HabariMarkdown') ) { // Apply Format::autop() to post content... Format::apply( 'autop', 'post_content_out' ); } // Apply Format::autop() to comment content... Format::apply( 'autop', 'comment_content_out' ); // Apply Format::tag_and_list() to post tags... Format::apply( 'tag_and_list', 'post_tags_out' ); // Apply Format::nice_date() to post date... Format::apply( 'nice_date', 'post_pubdate_out', 'F j, Y' ); // Apply Format::nice_date() to post date... Format::apply( 'nice_date', 'post_pubdate_time', 'g:i a' ); // Format post date to ISO-8601... Format::apply( 'nice_date', 'post_pubdate_iso', 'c' ); // Apply Format::nice_date() to comment date... Format::apply( 'nice_date', 'comment_date_out', 'F j, Y ‒ g:i a' ); // Format comment date to ISO-8601... Format::apply( 'nice_date', 'comment_date_iso', 'c' ); // Truncate content excerpt at "more" or 100 characters... Format::apply_with_hook_params( 'more', 'post_content_excerpt', '', 100, 1 ); //Format::apply_with_hook_params( 'more', 'post_content_out', 'more', 100, 1 ); } /** * On theme activation, set the default options */ public function action_theme_activation($file) { if ( realpath($file) == __FILE__ ) { $this->class_name = strtolower(get_class($this)); foreach ( $this->default_options as $name => $value ) { $current_value = Options::get($this->class_name . '__' . $name); if ( is_null($current_value) ) { Options::set($this->class_name . '__' . $name, $value); } } } } public function filter_theme_config($configurable) { $configurable = true; return $configurable; } /** * Respond to the user selecting an action on the theme page */ public function action_theme_ui($theme) { $ui = new FormUI(strtolower(get_class($this))); $ui->append('text', 'home_tab', 'option:' . $this->class_name . '__home_tab', _t('Link Text to Home')); $ui->home_tab->add_validator('validate_required'); $ui->append('checkbox', 'show_author', 'option:' . $this->class_name . '__show_author', _t('Display author in posts')); // Save $ui->append('submit', 'save', _t('Save')); $ui->set_option('success_message', _t('Options saved')); $ui->out(); } public function add_template_vars() { //Theme Options if ( Options::get($this->class_name . '__home_tab')==""){ $this->assign( 'home_tab', $this->default_options['home_tab']); } else { $this->assign( 'home_tab', Options::get($this->class_name . '__home_tab')); } //Set to whatever you want your first tab text to be. if ( Options::get($this->class_name . '__show_author') == "" ){ $this->assign( 'show_author', $this->default_options['show_author']); } else { $this->assign( 'show_author' , Options::get($this->class_name . '__show_author') ); } //Display author in posts if ( ! $this->assigned( 'pages' ) ) { $this->assign( 'pages', Posts::get( array( 'content_type' => 'page', 'status' => Post::status('published'), 'nolimit' => 1 ) ) ); } if ( ! $this->assigned( 'recent_comments' ) ) { $this->assign( 'recent_comments', Comments::get( array('limit'=>10, 'status'=>Comment::STATUS_APPROVED, 'type'=>Comment::COMMENT, 'orderby'=>'date DESC' ) ) ); } if ( ! $this->assigned( 'recent_entries' ) ) { $this->assign( 'recent_entries', Posts::get( array('limit'=>10, 'content_type'=>1, 'status'=>2, 'orderby'=>'pubdate DESC' ) ) ); } $this->assign( 'post_id', ( isset($this->post) && $this->post->content_type == Post::type('page') ) ? $this->post->id : 0 ); parent::add_template_vars(); } /** * Returns an unordered list of all used Tags */ public function theme_show_tags( $theme ) { // List of all the tags $tags = DB::get_results(' SELECT t.id AS id, t.term_display AS tag, t.term AS slug FROM {terms} t LEFT JOIN {object_terms} tp ON t.id=tp.term_id INNER JOIN {posts} p ON p.id=tp.object_id AND p.status = ? WHERE t.vocabulary_id = ? GROUP BY slug ORDER BY tag ASC', array( Post::status('published'), Tags::vocabulary()->id ) ); $this->taglist = $tags; return $theme->fetch( 'taglist' ); } public function filter_post_tags_class( $tags ) { $class = ''; foreach ( $tags as $tag ) { $class .= " tag-{$tag->term}"; } if ( $class == '' ) { $class = 'no-tags'; } return $class; } public function theme_title($theme) { $title = ''; if ( $this->request->display_entries_by_date && count($this->matched_rule->named_arg_values) > 0 ) { $date_string = ''; $date_string .= array_key_exists('year', $this->matched_rule->named_arg_values) ? $this->matched_rule->named_arg_values['year'] : '' ; $date_string .= array_key_exists('month', $this->matched_rule->named_arg_values) ? '‒' . $this->matched_rule->named_arg_values['month'] : '' ; $date_string .= array_key_exists('day', $this->matched_rule->named_arg_values) ? '‒' . $this->matched_rule->named_arg_values['day'] : '' ; $title = _t('%1$s &raquo; Chronological Archives of %2$s', array($date_string, Options::get('title'))); } else if ( $this->request->display_entries_by_tag && array_key_exists('tag', $this->matched_rule->named_arg_values) ) { //$tag = (count($this->posts) > 0) ? $this->posts[0]->tags[$this->matched_rule->named_arg_values['tag']] : $this->matched_rule->named_arg_values['tag'] ; $tag = $this->matched_rule->named_arg_values['tag']; $title = _t('%1$s &raquo; Taxonomic Archives of %2$s', array(htmlspecialchars($tag), Options::get('title'))); } else if ( ($this->request->display_entry || $this->request->display_page) && isset($this->posts) ) { $title = _t('%1$s &raquo; %2$s', array(strip_tags($this->posts->title), Options::get('title'))); } /* else if ($this->request->display_search && array_key_exists('criteria', $this->matched_rule->named_arg_values)) { $title = _t('%1$s &raquo; Search Results of %2$s', array(htmlspecialchars($this->matched_rule->named_arg_values['criteria']), Options::get('title'))); } */ else { $title = Options::get('title'); } if ( $this->page > 1 ) { $title = _t('%1$s &rsaquo; Page %2$s', array($title, $this->page)); } return $title; } public function theme_mutiple_h1($theme,$criteria) { $h1 = ''; if ( $this->request->display_entries_by_date && count($this->matched_rule->named_arg_values) > 0 ) { $date_string = ''; $date_string .= array_key_exists('year', $this->matched_rule->named_arg_values) ? $this->matched_rule->named_arg_values['year'] : '' ; $date_string .= array_key_exists('month', $this->matched_rule->named_arg_values) ? '‒' . $this->matched_rule->named_arg_values['month'] : '' ; $date_string .= array_key_exists('day', $this->matched_rule->named_arg_values) ? '‒' . $this->matched_rule->named_arg_values['day'] : '' ; $h1 = '<h2 class="page-title">' . _t('Posts written in %s', array($date_string)) . '</h2>'; } if ( $this->request->display_entries_by_tag && array_key_exists('tag', $this->matched_rule->named_arg_values) ) { //$tag = (count($this->posts) > 0) ? $this->posts[0]->tags[$this->matched_rule->named_arg_values['tag']] : $this->matched_rule->named_arg_values['tag'] ; $tag = $this->matched_rule->named_arg_values['tag'] ; $h1 = '<h2 class="page-title">' . _t('Posts tagged with %s', array(htmlspecialchars($tag))) . '</h2>'; } if ( $this->request->display_search && isset($criteria) ) { $h1 = '<h2 class="page-title">' . _t('Search results for “%s”', array($criteria)) . '</h2>'; } return $h1; } public function action_form_comment( $form ) { $form->append('static', 'cf_mailnote', '<p id="comment-notes">' . _t('Mail will not be published') . '</p>'); $form->move_before( $form->cf_mailnote, $form->cf_commenter ); $required_flag = " *"; $required = Options::get('comments_require_id'); $form->cf_commenter->caption = 'Name' . ($required ? $required_flag : ''); $form->cf_email->caption = 'Mail' . ($required ? $required_flag : ''); } } ?> <file_sep> <h2>Feedburner Stats</h2><div class="handle">&nbsp;</div> <ul class="items"> <?php foreach ( $feedburner_stats as $key => $count ) : ?> <li class="item clear"> <span class="pct90"><?php echo $key; ?></span> <span class="comments pct10"><?php echo $count; ?></span> </li> <?php endforeach ?> </ul> <file_sep><div id="div_<?php echo $slug; ?>"></div> <script type="text/javascript"> var opts = { <?php echo $js_opts; ?> }; <?php echo $js_data; ?> <?php echo $js_draw; ?> </script> <div class="pct10">&nbsp;</div> <div class="pct90"><strong>Total Visitors: <?php echo $data_total; ?></strong></div> <file_sep><?php /** * Live Help Plugin * **/ class LiveHelp extends Plugin { /** * function info * Returns information about this plugin * @return array Plugin info array **/ function info() { return array ( 'name' => 'Live Help', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'version' => '0.12', 'description' => 'Allows users to connect to #habari on IRC from within the admin.', 'license' => 'Apache License 2.0', ); } /** * add ACL tokens when this plugin is activated **/ public function action_plugin_activation( $file ) { if(Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__)) { ACL::create_token( 'LiveHelp', 'Access the #habari IRC channel via the LiveHelp plugin', 'livehelp' ); } } /** * remove ACL tokens when this plugin is deactivated **/ function action_plugin_deactivation( $plugin_file ) { if( Plugins::id_from_file( __FILE__ ) == Plugins::id_from_file( $plugin_file ) ) { ACL::destroy_token( 'LiveHelp' ); } } /** * Add the Live Help page to the admin menu * * @param array $menus The main admin menu * @return array The altered admin menu */ function filter_adminhandler_post_loadplugins_main_menu( $menus ) { if ( User::identify()->can('LiveHelp') ) { $menus['livehelp'] = array( 'url' => URL::get( 'admin', 'page=livehelp'), 'title' => _t('Live Help'), 'text' => _t('Live Help'), 'selected' => false ); } return $menus; } /** * On plugin init, add the admin_livehelp template to the admin theme */ function action_init() { $this->add_template('livehelp', dirname(__FILE__) . '/livehelp.php'); } public function action_add_template_vars( $theme ) { if ($theme->admin_page == 'livehelp') { $user = User::identify(); $nick = $user->username; $nick = $nick == 'admin' ? substr($user->email, 0, strpos($user->email, '@')) : $nick; $theme->assign('nick', $nick); } } public function action_admin_header( $theme ) { if ($theme->admin_page == 'livehelp') { Stack::add('admin_stylesheet', array($this->get_url() . '/livehelp.css', 'screen')); } } /** * Implement the update notification feature */ public function action_update_check() { Update::add( 'Live Help', 'c2413ab2-7c79-4f92-b008-18e3d8e05b64', $this->info->version ); } /** * filter the permissions so that admin users can use this plugin **/ public function filter_admin_access_tokens( $require_any, $page, $type ) { // we only need to filter if the Page request is for our page if ( 'livehelp' == $page ) { // we can safely clobber any existing $require_any // passed because our page didn't match anything in // the adminhandler case statement $require_any= array( 'super_user' => true, 'livehelp' => true ); } return $require_any; } } ?> <file_sep><?php if ( ! $post->info->comments_disabled ) { ?> <h3><?php echo $post->comments->approved->count; ?> <?php echo _n( 'Response', 'Responses', $post->comments->approved->count ); ?></h3> <ol id="comments-list"> <?php if ( $post->comments->approved->count ) { foreach ( $post->comments->approved as $comment ) { if ( $comment->url == '' ) { $comment_url = $comment->name_out; } else { $comment_url = '<a href="' . $comment->url . '" rel="external">' . $comment->name_out . '</a>'; } ?> <li id="comment-<?php echo $comment->id; ?>" class="comment"> <p class="commenter"><cite><?php echo $comment_url; ?></cite>, on <a href="#comment-<?php echo $comment->id; ?>" title="<?php _e('Permanent link to'); ?>"><?php echo $comment->date->out('d-m-Y / H:i'); ?></a>, said:</p> <div class="response"> <?php echo $comment->content_out; ?> </div> <p> <?php if ( $user ) { ?> <a href="<?php URL::out( 'admin', 'page=comment&id=' . $comment->id); ?>" title="<?php _e('Edit this comment'); ?>"><?php _e('Edit this comment'); ?></a> <?php } ?> </p> </li> <?php } } else { ?> <li><?php _e('There are currently no comments.'); ?></li> <?php } ?> </ol> <?php $post->comment_form()->out(); } ?><file_sep><?php /** * A plugin to hide spoilers until a conscious action on the part of the user. * **/ class Spoilers extends Plugin { private $has_spoilers; private $current_id; private $post; public function info() { return array( 'name' => 'Spoilers', 'version' => '1.0', 'url' => 'http://habariproject.org/', 'author' => '<NAME>', 'authorurl' => 'http://twofishcreative.com/', 'license' => 'Apache License 2.0', 'description' => 'A plugin to hide spoilers until a conscious action on the part of the user.' ); } /** * Set up some default options * **/ public function action_plugin_activation($file) { if ( Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__) ) { Options::set('spoiler__message', 'Reveal spoiler'); } } /** * Create plugin configuration **/ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t('Configure'); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure') : $form = new FormUI( strtolower( get_class( $this ) ) ); $form->append( 'label', 'message_label', _t( 'Default message used as a link in posts and feeds.', 'spoilers') ); $form->append( 'text', 'message', 'spoiler__message', _t('Spoiler message:', 'spoilers') ); $form->append( 'submit', 'save', _t('Save') ); $form->set_option('success_message', _t('Options saved')); $form->out(); break; } } } /** * Add help text to plugin configuration page **/ public function help() { $help = _t( "Inserting &lt;spoiler message=\"Click this to reveal spoiler\"&gt;The butler did it!&lt;/spoiler&gt; would show a link saying 'Click to reveal spoiler' and hide 'The butler did it!' in a post. A default message can be set in the plugin's configuration. In feeds, the spoiler is removed completely, requiring the user to click the link and visit the site to reveal spoilers.", 'spoilers' ); return $help; } /** * Add a template for the spoilers **/ public function action_init() { $this->add_template('spoiler', dirname(__FILE__) . '/spoiler.php'); } /** * Filter the content of a post, turning <spoiler>foobar</spoiler> into a div that can be hidden * **/ public function filter_post_content( $content, $post ) { // If we're on the publish page, replacement will be destructive. // We don't want that, so return here. $handler = Controller::get_handler(); if ( isset( $handler->action ) && $handler->action == 'admin' && isset($handler->handler_vars['page']) && $handler->handler_vars['page'] == 'publish' ) { return $content; } // If there are no spoilers, save the trouble and just return it as is. if ( strpos( $content, '<spoiler' ) === false ) { return $content; } $this->current_id = $post->id; $this->post = $post; $return = preg_replace_callback( '/(<spoiler(\s+message=[\'"](.*)[\'"])?>)(.*)(<\/spoiler>)/Us', array($this, 'add_spoiler'), $content ); if ( !$this->has_spoilers ) { return $content; } return $return; } private function add_spoiler( $matches ) { $this->has_spoilers = true; list(,,, $message, $spoiler) = $matches; if ( '' == $message ) { $message = Options::get('spoiler__message'); } $theme = Controller::get_handler()->theme; // If it's a feed, drop the spoiler and link back. // This is horribly hacky. Is there a nicer way to check if it's a feed (Atom or RSS)? if ( null == $theme ) { $link = $this->post->permalink; return "<a href='$link'>$message</a>"; } $theme->spoiler = $spoiler; $theme->message = $message; return $theme->fetch( 'spoiler' ); } public function action_update_check () { Update::add( 'Spoilers', 'cb1e23b3-821d-46e5-838d-a8f8cc5e5e26', $this->info->version ); } public function theme_header() { Stack::add('template_stylesheet', array(URL::get_from_filesystem(__FILE__) . '/spoilers.css', 'screen'), 'spoilers', array() ); } public function theme_footer() { if ( $this->has_spoilers ) { // Load jQuery, if it's not already loaded if ( !Stack::has( 'template_header_javascript', 'jquery' ) ) { Stack::add( 'template_footer_javascript', Site::get_url('scripts') . '/jquery.js', 'jquery', array('jquery') ); } Stack::add( 'template_footer_javascript', URL::get_from_filesystem(__FILE__) . '/spoilers.js', 'spoilers', array('jquery') ); Stack::add('template_stylesheet', array(URL::get_from_filesystem(__FILE__) . '/spoilers.css', 'screen'), 'spoilers', array() ); } } } ?> <file_sep> <?php //Getting result of of theme function if ($pollid == null) { $poll = Post::get(array('content_type' => Post::type('Poll'))); } elseif (is_int($pollid) === true) { $poll = Post::get(array('content_type'=>Post::type('Poll'), 'id'=>$pollid)); } $form = new FormUi(strtolower( get_class( $this ) ) ); $array = array(); $form->append('radio', 'entry', 'null:null', 'poll this'); $poll->info->entry; $array = $poll->info->entry; $form->entry->options = $array; ?> <div id="main_poll"> <span id="polltitle"> <a href="<?php echo $poll->permalink ?>"> <b> <?php echo $poll->title; ?> </b> </a></span> <?php if (!Session::get_set('votes', false)) { ?> <div id="vote"> <?php $form->out(); ?> </div> <a id="votesubmitt"> Vote </a> <?php } ?> <div id="contentLoading" style=" display: none;"alt="Loading, please wait"> Loading... </div> <div id="results" > </div> <?php if (!Session::get_set('votes', false)) { ?> <a submitt="<?php if (Session::get_set('votes', false)) { echo 'off'; } ?>"> <span id="veiw_results"> Veiw resutls </span> </a> <?php } ?> <script type="text/javascript"> $('#veiw_results').click(function() { if($('#veiw_results').text() == "go back to poll") { $('#votesubmitt').show(); $('#veiw_results').text("Veiw resutls"); $('#vote').css({display: "block"}); $('#results').css({display: "none"}); } else { //results $('#votesubmitt').hide(); $('#veiw_results').text("go back to poll") $('#vote').css({display: "none"}); $('#results').css({display: "block"}); $.get('<?php echo URL::get('ajax', array('context' => 'ajaxpoll')); ?>', {result: null, pollid: <?php echo $poll->id?>}, function(data) { $('#results').html(data); }) } }) $('#votesubmitt').click(function() { value = "entry" value = $("input[type = 'radio']:checked").val(); value = value.replace('entry','') value = parseFloat(value); $.get('<?php echo URL::get('ajax', array('context' => 'ajaxpoll')); ?>', {result: value, pollid: <?php echo $poll->id ?> }, function(data) { $('#results').html(data); $('#results').show() $('#vote').css({display: "none"}); lockdown() }) }) function lockdown() { $('#veiw_results').hide(); $('#votesubmitt').hide(); $('#vote').hide(); } function getresults() { $.get('<?php echo URL::get('ajax', array('context' => 'ajaxpoll')); ?>', {result: null, pollid: <?php echo $poll->id ?>}, function(data) { $('#results').html(data); }) } $().ajaxSend(function(r,s){ $("#contentLoading").show(); }); $().ajaxStop(function(r,s){ $("#contentLoading").fadeOut("fast"); }); </script> <?php if (Session::get_set('votes', false)) { ?> <script type="text/javascript"> lockdown() getresults() </script> <?php } ?> </div><file_sep><?php class BreezyArchivesHandler extends ActionHandler { public $theme = null; /** * Constructor for the default theme handler. Here, we * automatically load the active theme for the installation, * and create a new Theme instance. */ public function __construct() { $this->theme = Themes::create(); } /** * Helper function which automatically assigns all handler_vars * into the theme and displays a theme template * * @param template_name Name of template to display (note: not the filename) */ protected function display($template_name) { /* * Assign internal variables into the theme (and therefore into the theme's template * engine. See Theme::assign(). */ foreach ($this->handler_vars as $key => $value) { $this->theme->assign($key, $value); } try { $this->theme->display($template_name); } catch(Error $e) { EventLog::log($e->humane_error(), 'error', 'plugin', $this->handler_vars['class_name'], print_r($e, 1)); } } private function get_params($user_filters = array()) { $default_filters = array( 'content_type' => Post::type('entry'), 'status' => Post::status('published'), 'limit' => Options::get($this->handler_vars['class_name'] . '__posts_per_page'), 'page' => 1, 'orderby' => Options::get($this->handler_vars['class_name'] . '__show_newest_first') ? 'pubdate DESC' : 'pubdate ASC' ); $paramarray = new SuperGlobal($default_filters); $paramarray = $paramarray->merge($user_filters, $this->handler_vars); unset($paramarray['entire_match']); unset($paramarray['class_name']); return $paramarray; } /** * Helper function: Display the posts for a specific date * @param array $user_filters Additional arguments used to get the page content */ public function act_display_breezyarchives_by_month($user_filters = array()) { $paramarray = $this->get_params($user_filters); $cache_name = array($this->handler_vars['class_name'], 'month_' . $paramarray['year'] . $paramarray['month'] . '_page_' . $paramarray['page']); if (Cache::has($cache_name)) { echo Cache::get($cache_name); } else { $posts = Posts::get($paramarray); $this->theme->assign('posts', $posts); $this->theme->assign('page_total', Utils::archive_pages($posts->count_all(), $paramarray['limit'])); $this->theme->assign('current_page', $paramarray['page']); $this->theme->assign('prev_page_text', Options::get($this->handler_vars['class_name'] . '__prev_page_text')); $this->theme->assign('prev_page_link', URL::get('display_breezyarchives_by_month', array('class_name' => $this->handler_vars['class_name'], 'year' => $paramarray['year'], 'month' => $paramarray['month'], 'page' => $paramarray['page'] - 1))); $this->theme->assign('next_page_text', Options::get($this->handler_vars['class_name'] . '__next_page_text')); $this->theme->assign('next_page_link', URL::get('display_breezyarchives_by_month', array('class_name' => $this->handler_vars['class_name'], 'year' => $paramarray['year'], 'month' => $paramarray['month'], 'page' => $paramarray['page'] + 1))); $this->theme->assign('show_comment_count', Options::get($this->handler_vars['class_name'] . '__posts_per_page')); $this->theme->assign('year', $paramarray['year']); $this->theme->assign('month', $paramarray['month']); $ret = $this->theme->fetch('breezyarchives_month'); Cache::set($cache_name, $ret); echo $ret; } } /** * Helper function: Display the posts for a specific tag * @param array $user_filters Additional arguments used to get the page content */ public function act_display_breezyarchives_by_tag($user_filters = array()) { $paramarray = $this->get_params($user_filters); $cache_name = array($this->handler_vars['class_name'], 'tag_' . $this->handler_vars['tag_slug'] . '_page_' . $paramarray['page']); if (Cache::has($cache_name)) { echo Cache::get($cache_name); } else { $posts = Posts::get($paramarray); $this->theme->assign('posts', $posts); $this->theme->assign('page_total', Utils::archive_pages($posts->count_all(), $paramarray['limit'])); $this->theme->assign('current_page', $paramarray['page']); $this->theme->assign('prev_page_text', Options::get($this->handler_vars['class_name'] . '__prev_page_text')); $this->theme->assign('prev_page_link', URL::get('display_breezyarchives_by_tag', array('class_name' => $this->handler_vars['class_name'], 'tag_slug' => $this->handler_vars['tag_slug'], 'page' => $paramarray['page'] - 1))); $this->theme->assign('next_page_text', Options::get($this->handler_vars['class_name'] . '__next_page_text')); $this->theme->assign('next_page_link', URL::get('display_breezyarchives_by_tag', array('class_name' => $this->handler_vars['class_name'], 'tag_slug' => $this->handler_vars['tag_slug'], 'page' => $paramarray['page'] + 1))); $this->theme->assign('show_comment_count', Options::get($this->handler_vars['class_name'] . '__posts_per_page')); $ret = $this->theme->fetch('breezyarchives_tag'); Cache::set($cache_name, $ret); echo $ret; } } /** * Helper function: Display the JavaScript for Breezy Archives */ public function act_display_breezyarchives_js() { ob_clean(); header('Content-type: text/javascript'); // header('ETag: ' . md5($out)); // header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 315360000) . ' GMT'); // header('Cache-Control: max-age=315360000'); $this->theme->assign('habari_url', Site::get_url('habari', TRUE)); $this->theme->assign('class_name', $this->handler_vars['class_name']); $this->theme->assign('spinner_img', URL::get_from_filesystem(__FILE__, TRUE) . 'breezyarchives_spinner.png'); $this->display('breezyarchives_js'); } } ?><file_sep>var InstantSearch = { running: false, request: null, url: '', init: function () { // hook our ajax event when a key is released $('input#q').keyup( function ( ) { InstantSearch.search( $(this).val() ); // prevent the browser from doing anything return false; } ); // also hook our ajax event when the instant search form is submitted (via button or 'enter') $('form#instant_search').submit( function ( ) { InstantSearch.search( $('input#q').val() ); // prevent the browser from doing anything return false; } ); }, search: function ( search_term ) { // cancel any previous requests if ( InstantSearch.running ) { InstantSearch.request.abort(); InstantSearch.running = false; } // if the search is blank, there is no point in making a request, display the blank results if ( search_term == '' ) { InstantSearch.show_results('', search_term); } this.request = $.ajax({ method: 'GET', url: this.url, dataType: 'json', data: { q: search_term }, success: function ( data ) { InstantSearch.show_results(data, search_term); } }); }, show_results: function ( data, search_term ) { // the request has finished InstantSearch.running = false; var html = ''; $.each( data, function( i, item ) { var snip = ''; // build the html for this post snip += '<div class="result">'; snip += ' <h2><a href="' + item.url + '">' + item.title + '</a></h2>'; snip += ' <p>' + item.content.replace( search_term, '<span class="highlight">' + search_term + '</span>' ) + '</p>'; snip += ' <a href="' + item.url + '" class="read_more">Read more...</a>'; snip += '</div>'; // append it to the main html block we're building html += snip; } ); // and stick the html we built into the results div $('div#results').html( html ); } }; $(document).ready( InstantSearch.init );<file_sep><?php $theme->display ('header'); ?> <div class="entry span-24"> <div class="left column span-6 first"> <h2></h2> </div> <div class="center column span-13"> <h2><?php echo $post->title_out; ?></h2> <?php echo $post->content_out; ?> <span class="tags"><p><strong>Tagged:</strong> <?php echo $post->tags_out; ?></p></span> </div> <div class="right column span-5 last"> <h2><a href="<?php echo $post->permalink; ?>" rel="bookmark" title='<?php echo $post->title; ?>'><?php echo $post->pubdate_out; ?></a></h2> <span class="comments"> </span> </div> </div> <?php $theme->display ('footer'); ?> <file_sep><?php class Projectr extends Plugin { static $secret_report_cache = array(); public function action_update_check() { Update::add( $this->info->name, '8d5a4403-33a5-430e-8674-ae4a1b1a09d3', $this->info->version ); } public function action_init() { // gotta be an easier way of doing this $theme_dir = Plugins::filter( 'admin_theme_dir', Site::get_dir( 'admin_theme', TRUE ) ); $theme = Themes::create( 'admin', 'RawPHPEngine', $theme_dir ); if( !$theme->template_exists( 'admincontrol_select') ) { $this->add_template('admincontrol_select', dirname(__FILE__) . '/admincontrol_select.php'); } } public function action_plugin_activation( $plugin_file ) { self::install(); } public function action_plugin_deactivation( $plugin_file ) { Post::deactivate_post_type( 'project' ); } public static function get_projects( $params = array() ) { $params['content_type'] = Post::type('project'); $params['nolimit'] = true; return Posts::get( $params ); } /** * Gets a simple list of all projects **/ public static function get_projects_simple() { $posts = self::get_projects(); $projects = array(); foreach( $posts as $project ) { $projects[ $project->slug ] = $project->title; } return $projects; } /** * install various stuff we need */ public static function install() { /** * Register content type **/ Post::add_new_type( 'project' ); // Give anonymous users access $group = UserGroup::get_by_name('anonymous'); $group->grant('post_project', 'read'); } /** * Create name string **/ public function filter_post_type_display($type, $foruse) { $names = array( 'project' => array( 'singular' => _t('Project'), 'plural' => _t('Projects'), ) ); return isset($names[$type][$foruse]) ? $names[$type][$foruse] : $type; } /** * Modify publish form */ public function action_form_publish($form, $post) { if ($post->content_type == Post::type('project')) { $form->title->caption = 'Project Name'; } else { $projects = self::get_projects_simple(); $projects['other'] = "Other"; $projects = array_reverse( $projects ); $project_selector= $form->append('select', 'project', 'null:null', _t('Project'), $projects, 'admincontrol_select'); foreach( $projects as $key => $name ) { if( array_key_exists( $key, $post->tags ) ) { $project_selector->value = $key; } } $form->move_after($project_selector, $form->tags); } } /** * Save our report */ public function action_publish_post( $post, $form ) { // Delete all project tags $projects = self::get_projects_simple(); $tags = array(); foreach( $post->tags as $tag ) { if( !array_key_exists( $tag, $projects ) ) { $tags[] = $tag; } } // Add the project tag if( $form->project->value != 'other' ) { $tags[] = $form->project->value; } $post->tags = $tags; // exit; } } ?><file_sep><?php class notify_all extends Plugin { /** * Add update beacon support */ public function action_update_check() { Update::add( 'Notify All', '7445fa2e-badc-4b6a-8098-4f3b85563ffb', $this->info->version ); } /** * Sets default values for notify_all options and userinfo * Users will receive email notifications of new posts and comments by default */ public function action_plugin_activation( $file ) { if ( Plugins::id_from_file( $file ) == Plugins::id_from_file( __FILE__ ) ) { Options::set('notify_all__notify_posts', 1); Options::set('notify_all__notify_comments', 1); Options::set('notify_all__user_can_override', 1); } } /** * Remove notify_all options on deactivation */ public function action_plugin_deactivation( $file ) { if ( Plugins::id_from_file( $file ) == Plugins::id_from_file( __FILE__ ) ) { Options::delete('notify_all__notify_posts'); Options::delete('notify_all__notify_comments'); Options::delete('notify_all__user_can_override'); } } /** * Add plugin config */ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t( 'Configure' ); } return $actions; } /** * Populate the plugin config form */ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { if ( $action == _t( 'Configure' ) ) { $ui = new FormUI( strtolower( get_class( $this ) ) ); $notify_posts = $ui->append( 'checkbox', 'notify_posts', 'notify_all__notify_posts', _t( 'Send email notifications for posts', 'notify_all' ) ); $notify_comments = $ui->append( 'checkbox', 'notify_comments', 'notify_all__notify_comments', _t( 'Send email notifications for comments', 'notify_all' ) ); $notify_user_can_override = $ui->append( 'checkbox', 'user_can_override', 'notify_all__user_can_override', _t( 'User can set whether notifications are sent', 'notify_all' ) ); $ui->append( 'submit', 'save', 'Save' ); $ui->out(); } } } /** * Add 'notify_posts' and 'notify_comments' options to the user profile page */ public function action_form_user( $form, $edit_user ) { if ( Options::get( 'notify_all__user_can_override' ) ) { $notify_all = $form->insert('page_controls', 'wrapper', 'notify_all', _t( 'Notify All', 'notify_all' ) ); $notify_all->class = 'container settings'; $notify_all->append( 'static', 'post notifier', '<h2>' . htmlentities( _t( 'Notify All', 'notify_all' ), ENT_COMPAT, 'UTF-8' ) . '</h2>' ); $notify_posts = $notify_all->append( 'checkbox', 'notify_all__notify_posts', 'null:null', _t( 'Notify Posts', 'notify_all' ), 'optionscontrol_checkbox' ); $notify_posts->class[] = 'item clear'; $notify_posts->helptext = _t( 'Whether the user should receive email notifications of new posts', 'notify_all' ); $notify_posts->value = $edit_user->info->notify_all__notify_posts; $notify_comments = $notify_all->append( 'checkbox', 'notify_all__notify_comments', 'null:null', _t( 'Notify Comments', 'notify_all' ), 'optionscontrol_checkbox' ); $notify_comments->class[] = 'item clear'; $notify_comments->helptext = _t( 'Whether the user should receive email notifications of new comments', 'notify_all' ); $notify_comments->value = $edit_user->info->notify_all__notify_comments; $form->move_after( $notify_all, $form->change_password ); } } /** * Add the 'notify_posts' and 'notify_comments' options to the list of valid field names. * This causes adminhandler to recognize the 'notify_posts' and 'notify_comments' fields and to set the userinfo record accordingly */ public function filter_adminhandler_post_user_fields( $fields ) { if ( Options::get( 'notify_all__user_can_override' ) ) { $fields['notify_all__notify_posts'] = 'notify_all__notify_posts'; $fields['notify_all__notify_comments'] = 'notify_all__notify_comments'; } return $fields; } /** * Add help text to plugin configuration page */ public function help() { $help = _t( "<p>When there is a new post or comment this plugin sends an email notification to all registered users. On activation all users are set to receive these notifications. Users can turn off the notifications through the user profile page.</p>", 'notify_all' ); return $help; } /** * Send email notifications when a post is published */ public function action_publish_post( $post, $form ) { if ( $post->status == Post::status( 'published' ) ) { $this->send_post_notifications( $post ); } } /** * Send email notifications when an approved comment is made */ public function action_comment_insert_after( $comment ) { if ( $comment->status == Comment::STATUS_APPROVED ) { $this->send_comment_notifications( $comment ); } } /** * Send email notifications when an comment is approved */ public function action_admin_moderate_comments( $action, $comments, $handler ) { $action = strtolower(trim($action)); if ( $action == 'approve' || $action == 'approved' ) { foreach ( $comments as $c) { $this->send_comment_notifications( $c ); } } } /** * Set the 'notify_posts' and 'notify_comments' options to true if they are not already set */ private function set_notify( $user ) { $commit = FALSE; if ( $user->info->notify_all__notify_posts == NULL ) { $user->info->notify_all__notify_posts = '1'; $commit = TRUE; } if ( $user->info->notify_all__notify_comments == NULL ) { $user->info->notify_all__notify_comments = '1'; $commit = TRUE; } if ( $commit ) { $user->info->commit(); } } /** * Send the email notifications for posts */ private function send_post_notifications( $post ) { $author = User::get_by_id( $post->user_id ); $title = sprintf(_t('[%1$s] New post: %2$s', 'notify_all'), Options::get('title'), $post->title ); $message = <<< MESSAGE There is a new post, "%1\$s", on %2\$s: %3\$s Author: %4\$s Post: MESSAGE; $message = _t( $message, 'notify_all' ); $message = sprintf( $message, $post->title, Options::get('title'), $post->permalink, $author->username ); $body = $post->content; $headers = 'From: ' . $author->username . ' <' . $author->email . '>'; $users = Users::get(); foreach ( $users as $user ) { // if user is not allowed to override, and email notification for posts is on, send email // if user is allowed to override, and they have opted to receive emails, send email // also don't send email to the author of the post if ( ( ( !Options::get( 'notify_all__user_can_override' ) && Options::get( 'notify_all__notify_posts' ) ) || ( Options::get( 'notify_all__user_can_override' ) && $user->info->notify_all__notify_posts ) ) && $user->id != $author->id ) { $this->send_mail( $user->email, $title, $message, $body, $headers, 'post' ); } } } /** * Send the email notifications for comments */ private function send_comment_notifications( $comment ) { // we should only execute on comments, not pingbacks // and don't bother if the comment is know to be spam if ( ( $comment->type != Comment::COMMENT ) || ( $comment->status == Comment::STATUS_SPAM ) ) { return; } $post = Post::get( array('id' => $comment->post_id ) ); $author = User::get_by_id( $post->user_id ); $title = sprintf(_t('[%1$s] New comment on: %2$s', 'notify_all'), Options::get('title'), $post->title); $message = <<< MESSAGE There is a new comment on the post "%1\$s", on %2\$s: %3\$s Author: %4\$s <%5\$s> URL: %6\$s Comment: MESSAGE; $message = _t( $message, 'notify_all' ); $message = sprintf( $message, $post->title, Options::get('title'), $post->permalink . '#comment-' . $comment->id, $comment->name, $comment->email, $comment->url ); $body = $comment->content; $headers = 'From: ' . $comment->name . ' <' . $comment->email . '>'; $users = Users::get(); foreach ( $users as $user ) { // if user is not allowed to override, and email notification for comments is on, send email // if user is allowed to override, and they have opted to receive emails, send email // also don't send email to the email address of the person who wrote the comment if ( ( ( !Options::get( 'notify_all__user_can_override' ) && Options::get( 'notify_all__notify_comments' ) ) || ( Options::get( 'notify_all__user_can_override' ) && $user->info->notify_all__notify_comments ) ) && $user->email != $comment->email ) { $this->send_mail( $user->email, $title, $message, $body, $headers, 'comment' ); } } } /** * Sends the email and writes to the log */ private function send_mail( $email, $subject, $message, $body, $headers, $type ) { // use PHP_EOL instead of \r\n to separate headers as you must use native // line endings for the system running PHP $mailHeaders = 'MIME-Version: 1.0' . PHP_EOL; $mailHeaders .= 'Content-type: text/plain; charset=utf-8' . PHP_EOL; $mailHeaders .= 'Content-Transfer-Encoding: 8bit' . PHP_EOL; $mailHeaders .= $headers . PHP_EOL; // strip all HTML tags as this email is sent in plain text $body = strip_tags( $body ); // limit post/comment content to 50 words or 3 paragraphs // (which doesn't make any different for plain text) $body = Format::summarize( $body, 50, 3 ); $message .= $body; // for the reason above, use consistent line separators $message = str_replace( array( "\r\n", "\n", "\r" ), PHP_EOL, $message ); if ( ( mail( $email, $subject, $message, $mailHeaders ) ) === TRUE ) { EventLog::log( $type . ' email sent to ' . $email, 'info', 'default', 'notify_all' ); } else { EventLog::log( $type . ' email could not be sent to ' . $email, 'err', 'default', 'notify_all' ); } } } ?> <file_sep><?php class Code_Escape extends Plugin { public function filter_post_content_out ( $content, $post ) { $content = preg_replace_callback('/<code>(.*?)<\/code>/s', array( 'self', 'escape_code' ), $content); return $content; } public static function escape_code ( $matches ) { $string = $matches[1]; $string = htmlspecialchars( $string ); $string = '<code>' . $string . '</code>'; return $string; } public function action_update_check ( ) { Update::add( 'Code Escape', '3ede3d2c-cb4f-4a37-9ac5-c5918fef7257', $this->info->version ); } } ?><file_sep><?php // tell Habari which class to use define( 'THEME_CLASS', 'FunWithPhotoblogs' ); /** * A custom class for the Fun With Photoblogs theme */ class FunWithPhotoblogs extends Theme { public $post_content_more = ''; /** * Execute on theme init to apply these filters to output */ public function action_init_theme() { Format::apply( 'nice_date', 'post_pubdate_out', 'l jS F Y' ); } /** * * @return */ public function add_template_vars() { //the title to display on the manu bar $this->assign('menu_title',$this->calculate_menu_title()); parent::add_template_vars(); } /** * * @return */ public function act_display_home( $user_filters = array() ){ //limit the home page to on post parent::act_display_entries( array('limit'=>1 ) ); } public function action_template_header( ) { Stack::add( 'template_header_javascript', Site::get_url('scripts') . '/jquery.js', 'jquery' ); Stack::add( 'template_header_javascript', Site::get_url('user') . '/themes/fun-with-photoblogs/js/script.js', 'fwpb-script' ); } /** * Return the title for the page * @return String the title. */ public function the_title( $head = false ){ $title = ''; //check against the matched rule switch( $this->matched_rule->name ){ case 'display_404': $title = 'Error 404'; break; case 'display_entry': $title .= $this->post->title; break; case 'display_page': $title .= $this->post->title; break; case 'display_search': $title .= 'Search for ' . ucfirst( $this->criteria ); break; case 'display_entries_by_tag': $title .= ucfirst( $this->tag ) . ' Tag'; break; case 'display_entries_by_date': $title .= 'Archive for '; $archive_date = new HabariDateTime(); if ( empty($date_array['day']) ){ if ( empty($date_array['month']) ){ //Year only $archive_date->set_date( $this->year , 1 , 1 ); $title .= $archive_date->format( 'Y' ); break; } //year and month only $archive_date->set_date( $this->year , $this->month , 1 ); $title .= $archive_date->format( 'F Y' ); break; } $archive_date->set_date( $this->year , $this->month , $this->day ); $title .= $archive_date->format( 'F jS, Y' ); break; case 'display_home': return Options::get( 'title' ); break; } return $title; } /** * Post content filter to find the photo information and formatit on the comments page. */ public function filter_post_content_out( $content , $post ){ //if the plugin is being used if ( isset($post->info->photo) && !empty($post->info->photo) ){ $this->post_content_more = $content; $content = sprintf('<img src="%s" alt="%s" />' , $post->info->photo , $post->title ); return $content; } //see if there is anything to extract if ( preg_match('/<!--details-->(.*)$/s' , $content , $matches) ) { //keep the content for later $this->post_content_more = $matches[1]; //remove the extras from the post here $content = str_replace($matches[0] , '' , $content); } return $content; } /** * * @return */ public function calculate_menu_title(){ if (isset($this->post)){ //if home page use the most recent post title and the date if ( $this->request->display_home ){ if ( $this->posts instanceof Posts ){ return $this->posts[0]->title_out . ' <span>' . $this->posts[0]->pubdate_out . '</span>'; } else { //if there is a static home page then no title is needed. return ''; } } if ( $this->request->display_page ){ return 'page'; } if ( $this->request->display_entry ){ return $this->post->title_out . ' <span>' . $this->posts->pubdate_out . '</span>'; } } } /** * Returns a link to the next post based on the post object passed to it. * I am sure there should be a built in method of doing this but I can't find it, so... * @return * @param $post Object A post obkect */ public function next_post_link( $post ){ //get the next post if ( $next_post = $post->ascend() ) { return '<a href="'.$next_post->permalink.'" title="'.$next_post->title_out.'" class=next-post>'.$next_post->title_out.'</a>'; } else { return ''; } } /** * Returns a link to the previous post based on the post object passed to it. * I am sure there should be a built in method of doing this but I can't find it, so... * @return * @param $post Object A post obkect */ public function prev_post_link( $post ){ //get the next post if ( $prev_post = $post->descend() ) { return '<a href="'.$prev_post->permalink.'" title="'.$prev_post->title_out.'" class=prev-post>'.$prev_post->title_out.'</a>'; } else { return ''; } } /** * Generate an HTML menu containing the site's pages. * @return */ public function pages_menu(){ //get a list of pages $pages = Posts::get( array( 'content_type' => 'page', 'status' => Post::status('published'), 'nolimit' => 1 ) ); //start the html $pages_menu_html = '<ul id="pages_menu">' . PHP_EOL; //add the home page $pages_menu_html .= $this->make_link( 'Home' , Site::get_url( 'habari' ) ) . PHP_EOL; //get the titles and links for other pages foreach( $pages as $page ){ $pages_menu_html .= $this->make_link( $page->title , $page->permalink ) . PHP_EOL; } //add the feedurl //???? $theme->feed_alternate(); //$pages_menu_html .= $this->make_link( 'Home' , Site::get_url( 'habari' ) ); //end the html $pages_menu_html .= '</ul>' . PHP_EOL; //send it back return $pages_menu_html; } /** * Generate and return the given title and url as an html link. * @return String html link * @param $title The title and display text * @param $url The url to link to */ private function make_link( $title , $url){ return '<a href="'.$url.'" title="'.$title.'">'.$title.'</a>'; } public function fwpb_comment_class( $comment, $post ) { $class= 'class="comment'; if ( $comment->status == Comment::STATUS_UNAPPROVED ) { $class.= '-unapproved'; } // check to see if the comment is by a registered user if ( $u= User::get( $comment->email ) ) { $class.= ' byuser comment-author-' . Utils::slugify( $u->displayname ); } if( $comment->email == $post->author->email ) { $class.= ' bypostauthor'; } $class.= '"'; return $class; } } ?><file_sep><?php /** * Hadminstrip Plugin * * A plugin for Habari that displays and admin strip * at the bottom of every page of your theme, for easy access to * the admin section. * Adapted from habminbar - http://habariproject.org * Inspired by wp-adminstrip - http://www.somefoolwitha.com/search/adminstrip * * @package hadminstrip */ class HadminStrip extends Plugin { const VERSION= '1.0.2'; /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Hadmin Strip', 'A39FB26A-B024-11DD-8832-E9A256D89593', $this->info->version ); } /** * Adds the admin bar stylesheet to the template_stylesheet Stack if the user is logged in. */ public function action_template_header() { if ( User::identify()->loggedin ) { echo '<link rel="stylesheet" type="text/css" href="' . $this->get_url() . '/hadminstrip.css">'; } } /** * Filters the hadminstrip via Plugin API to add the edit menu item. * * @param array $menu The hadminstrip array * @return array The modified hadminstrip array */ public function filter_hadminstrip( $menu ) { if ( Controller::get_var('slug') ) { $menu['write']= array( 'Edit', URL::get( 'admin', 'page=publish&slug=' . Controller::get_var('slug') ) ); } return $menu; } /** * Ouputs the default menu in the template footer, and runs the 'hadminstrip' plugin filter. * You can add menu items via the filter. See the 'filter_hadminstrip' method for * an example. */ public function action_template_footer() { if ( User::identify()->loggedin ) { ?> <div id="adminstrip"> <?php $unapprovedcomments=Comments::count_total( Comment::STATUS_UNAPPROVED, FALSE ); $postnumber=Posts::get( array( 'count' => 1, 'content_type' => Post::type('entry'), 'status' => Post::status('published') ) ); $commentnumber=Comments::count_total( Comment::STATUS_APPROVED, FALSE ); $spamnumber=Comments::count_total( Comment::STATUS_SPAM ); $tagscount = Tags::vocabulary()->count_total(); $pagecount=Posts::get( array( 'count' => 1, 'content_type' => Post::type('page'), 'status' => Post::status('published') ) );?> <a id="striplink" href="<?php echo ( URL::get( 'admin', 'page=dashboard' )); ?>" title="Visit the Dashboard.."><span id="admin">DASHBOARD</span></a> &middot; <a id="striplink" href="<?php echo (URL::get( 'user', 'page=logout')); ?>" title="Log out..">Logout</a> &middot; <a id="striplink" href="<?php echo (URL::get( 'admin', 'page=publish')); ?>" title="Write an entry..">Write</a> &middot; <a id="striplink" href="<?php echo (URL::get( 'admin', 'page=plugins'));?>" title="Plugins">Plugins</a> &middot; <a id="striplink" href="<?php echo (URL::get( 'admin', 'page=options' )); ?>" title="Update settings..">Options</a> <?php if ( $unapprovedcomments!=0) { ?> &middot; <a id="modcomments" href="<?php echo (URL::get( 'admin', 'page=comments' )); ?>" title="Unapproved Comments"><?php echo ($unapprovedcomments) ?> moderate</a><?php } ?> <?php if ( $spamnumber!=0) { ?> &middot; <a id="admincomments" href="<?php echo (URL::get( 'admin', 'page=comments' )); ?>?status=2" title="Spam Comments"><?php echo ($spamnumber) ?> spam</a><?php } ?> &middot; There are <a id="striplink" href="<?php echo (URL::get( 'admin', 'page=posts&type=' . Post::type('entry')));?>" title="<?php echo($postnumber) ?> posts"><?php echo($postnumber) ?> posts</a>, <a id="striplink" href="<?php echo (URL::get( 'admin', 'page=posts&type=' . Post::type('page')));?>" title="<?php echo($pagecount) ?> pages"><?php echo($pagecount) ?> pages</a> and <a id="striplink" href="<?php echo (URL::get( 'admin', 'page=comments' )); ?>" title="Comments"><?php echo($commentnumber) ?> comments</a> within <a id="striplink" href="<?php echo (URL::get( 'admin', 'page=tags'));?>" Tags="Tags"><?php echo($tagscount) ?> tags</a> </div> <?php } } } ?> <file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr"> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <title><?php $theme->title(); ?></title> <meta name="generator" content="Habari" /> <?php $theme->header(); ?> <link rel="alternate" type="application/atom+xml" title="Atom 1.0" href="<?php $theme->feed_alternate(); ?>" /> <link rel="edit" type="application/atom+xml" title="Atom Publishing Protocol" href="<?php URL::out( 'atompub_servicedocument' ); ?>" /> <link rel="EditURI" type="application/rsd+xml" title="RSD" href="<?php URL::out( 'rsd' ); ?>" /> <link rel="Shortcut Icon" href="/favicon.ico" /> <link rel="stylesheet" type="text/css" href="<?php Site::out_url( 'theme' ); ?>/style.css" /> <!--[if lte IE 7]> <link href="<?php Site::out_url( 'theme' ); ?>/ie6.css" type="text/css" rel="stylesheet" media="screen" /> <![endif]--> <script src="/mint/?js" type="text/javascript"></script> <!-- Special thanks to Diagona Icons by Yusuke,they are really nice. --> </head> <body class="<?php $theme->body_class(); ?>"> <div id="header"> <h1 id="blog-title"><span><a href="<?php Site::out_url( 'habari' ); ?>"><?php Options::out( 'title' ); ?></a></span></h1> <div id="blog-description"><?php Options::out( 'tagline' ); ?></div> <div id="menu"> <ul> <li class="page_item<?php if ($post_id == 0) echo " current_page_item"; ?>"><a href="<?php Site::out_url( 'habari' ); ?>" title="<?php Options::out( 'title' ); ?>"><?php echo $home_tab; ?></a></li><?php foreach ( $pages as $tab ) { ?> <li id="page_item_<?php echo $tab->id; ?>" class="page_item<?php if($tab->id == $post_id) echo " current_page_item"; ?>"><a href="<?php echo $tab->permalink; ?>" title="<?php echo $tab->title; ?>"><?php echo $tab->title; ?></a></li> <?php } ?> </ul> </div> <div id="search"> <?php $theme->display ('searchform' ); ?> </div> </div> <div id="wrapper_top">top</div> <div id="wrapper" class="hfeed"> <file_sep><?php class Commentated extends Plugin { function info() { return array( 'name' => 'Commentated', 'version' => '1.0', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Shows commenters a live preview of their comment', ); } public function action_init_theme() { Stack::add( 'template_header_javascript', Site::get_url('scripts') . '/jquery.js', 'jquery' ); Stack::add( 'template_header_javascript', URL::get_from_filesystem(__FILE__) . '/commentated.js', 'commentated' ); } } ?><file_sep><?php class Silencer extends Plugin { /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Silencer', 'fdb7e18c-f883-4456-a55d-b8e5c8c9ffaa', $this->info->version ); } /** * Add help text to plugin configuration page **/ public function help() { $help = _t( 'Once this is enabled, "Comments Allowed" will be deselected in the settings of all newly published posts and pages.' ); return $help; } /** **/ public function action_plugin_activation( $file ) { if(Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__)) { // for now, do nothing. Someday global postinfo changes may go here. } } /** * Update the setting prior to displaying the form. **/ public function action_form_publish( $form, $post, $context ) { $form->settings->comments_enabled->value = false; } } ?> <file_sep><?php require_once('cpgexif.php'); class CpgDb { const DB_VERSION = 005; public static function registerTables() { DB::register_table( 'cpg_images' ); DB::register_table( 'cpg_exif' ); DB::register_table( 'cpg_sets' ); DB::register_table( 'cpg_setimages' ); } public static function install() { $schema = "CREATE TABLE " . DB::table('cpg_images') . " ( id int unsigned NOT NULL auto_increment, modified int(10) NOT NULL, added int(10) NOT NULL, path varchar(45) NOT NULL default '', name varchar(45) NOT NULL default '', PRIMARY KEY (id) );"; $exifDbMap = CpgExif::getDbMap(); $dbColumns = ""; foreach ($exifDbMap as $exifColumn) { $dbColumns .= "\n $exifColumn text,"; } $schema .= "\nCREATE TABLE " . DB::table('cpg_exif') . " ( image_id int unsigned NOT NULL,$dbColumns PRIMARY KEY (image_id) );"; $schema .= "\nCREATE TABLE " . DB::table('cpg_sets') . " ( id int unsigned NOT NULL auto_increment, set_type varchar(45) NOT NULL, modified int(10) NOT NULL, added int(10) NOT NULL, parent_id int unsigned NOT NULL, name varchar(45) NOT NULL, data text, PRIMARY KEY (id) );"; $schema .= "\nCREATE TABLE " . DB::table('cpg_setimages') . " ( set_id int unsigned NOT NULL default '0', image_id int unsigned NOT NULL default '0', modified int(10) NOT NULL, added int(10) NOT NULL, priority int unsigned NOT NULL default '0', PRIMARY KEY (set_id, image_id) );"; //Utils::debug($schema); //exit; return DB::dbdelta($schema); } } ?><file_sep><!-- commentform --> <?php // Do not delete these lines if (!defined('HABARI_PATH')) { die(_t('Please do not load this page directly. Thanks!', 'binadamu')); } ?> <div id="respond"> <h2><?php _e('Leave a Reply', 'binadamu'); ?></h2> <?php if (Session::has_errors()) { Session::messages_out(); } ?> <form action="<?php URL::out('submit_feedback', array('id' => $post->id)); ?>" method="post" id="commentform"> <fieldset> <div class="commenter-info"> <label for="name" class="name"><?php _e('Name', 'binadamu'); ?></label> <input name="name" id="name" value="<?php echo $commenter_name; ?>" size="22" tabindex="1" /> <label for="email" class="email"><?php _e('E-mail', 'binadamu'); ?></label> <input name="email" id="email" value="<?php echo $commenter_email; ?>" size="22" tabindex="2" /> <label for="url" class="url"><?php _e('Website', 'binadamu'); ?></label> <input name="url" id="url" value="<?php echo $commenter_url; ?>" size="22" tabindex="3" /> <label for="message" class="content"><?php _e('Message', 'binadamu'); ?></label> </div> <div class="response-content"> <textarea name="content" id="message" cols="100" rows="10" tabindex="4"><?php if (isset($details['content'])) { echo $details['content']; } ?></textarea> <button type="submit" id="submit_feedback" tabindex="5" /><?php _e('Submit', 'binadamu'); ?></button> </div> <p class="moderation-notice"><?php _e('Your comment may not display immediately due to spam filtering. Please wait for moderation.', 'binadamu'); ?></p> </fieldset> </form> </div> <!-- /commentform --> <file_sep><?php class GoogleAnalytics extends Plugin { function info() { return array( 'url' => 'http://iamgraham.net/plugins', 'name' => 'GoogleAnalytics', 'description' => 'Automatically adds Google Analytics code to the bottom of your webpage.', 'license' => 'Apache License 2.0', 'author' => '<NAME>', 'authorurl' => 'http://iamgraham.net/', 'version' => '0.5.1' ); } public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()) { $actions[]= _t('Configure'); } return $actions; } public function action_plugin_ui($plugin_id, $action) { if ( $plugin_id == $this->plugin_id() ) { switch ($action) { case _t('Configure'): $form = new FormUI(strtolower(get_class($this))); $form->append('text', 'clientcode', 'googleanalytics__clientcode', _t('Analytics Client Code')); $form->append('checkbox', 'loggedintoo', 'googleanalytics__loggedintoo', _t('Track logged-in users too')); $form->append('submit', 'save', 'Save'); $form->out(); break; } } } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'GoogleAnalytics', '7e57a660-3bd1-11dd-ae16-0800200c9a66', $this->info->version ); } function theme_footer() { if ( URL::get_matched_rule()->entire_match == 'user/login') { // Login page; don't dipslay return; } $clientcode = Options::get('googleanalytics__clientcode'); $script1 = <<<SCRIPT1 <script type='text/javascript'> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> SCRIPT1; $script2 = <<<SCRIPT2 <script type="text/javascript"> try { var pageTracker = _gat._getTracker("{$clientcode}"); } catch(err) {} </script> SCRIPT2; $script3 = <<<SCRIPT3 <script type="text/javascript"> try { var pageTracker = _gat._getTracker("{$clientcode}"); pageTracker._trackPageview(); } catch(err) {} </script> SCRIPT3; // always output the first part, so things like the site overlay work for logged in users echo <<<SCRIPT1 <script type='text/javascript'> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> SCRIPT1; echo <<<SCRIPT2 <script type="text/javascript"> try { var pageTracker = _gat._getTracker("{$clientcode}"); SCRIPT2; // only actually track the page if we're not logged in, or we're told to always track if ( User::identify()->loggedin == false || Options::get('googleanalytics__loggedintoo') ) { echo <<<SCRIPT3 pageTracker._trackPageview(); SCRIPT3; } echo <<<SCRIPT4 } catch(err) {}</script> SCRIPT4; } } ?> <file_sep><?php class OpenID extends Plugin { public function filter_rewrite_rules( $db_rules ) { $db_rules[] = new RewriteRule( array( 'name' => 'openid', 'parse_regex' => '%^openid/?(?P<user>[^/]*)/?$%i', // For Server, if previous matched, don't look. 'build_str' => 'openid/({$user})', 'handler' => 'OpenID', 'action' => 'dispatch', 'priority' => 1, 'is_active' => 1, 'rule_class' => RewriteRule::RULE_CUSTOM, 'description' => 'OpenID Authentification' ) ); return $db_rules; } public function act( $action ) { if ( isset( $_GET['openid_mode'] ) ) { switch ( $_GET['openid_mode'] ) { case 'id_res': self::openid_end(); break; case 'cancel': EventLog::log( 'Authorization failed: User cancelled authorization.', 'info', 'authentication', 'OpenID' ); throw new Exception( 'Authorization failed: User cancelled authorization.' ); break; } } else if ( isset( $_POST['openid_url'] ) ) { self::openid_start(); } else { EventLog::log( 'Authorization failed: unknown error.', 'err', 'authentication', 'OpenID' ); throw new Exception( 'Authorization failed: unknown error.' ); } } public function action_plugin_activation( $file ) { if ( realpath( $file ) == __FILE__ ) { if ( !extension_loaded('curl') && !@dl('curl') ) { EventLog::log( 'Could not load CURL, which is needed for OpenID to work.', 'err', 'authentication', 'OpenID' ); throw new Exception( 'Could not load CURL, which is needed for OpenID to work.' ); } EventLog::register_type( 'authentification', 'OpenID' ); } } public function action_plugin_deactivation( $file ) { if ( realpath( $file ) == __FILE__ ) { EventLog::unregister_type( 'OpenID' ); } } public function action_init() { if ( session_id() == '' ) { session_start(); } ini_set( 'include_path', dirname( __FILE__ ) ); Stack::add( 'template_stylesheet', array( $this->get_url() . '/openid.css', 'screen' ), 'openid_style' ); } public function action_theme_loginform_before() { if ( isset( $_GET['openid_url'] ) ) { echo '<hr><div class="alert"><strong>If you have an existing account</strong>, sign in so we can assign your OpenID identifer to it.</div>'; } } public function action_theme_loginform_after() { // @todo Remove the !isset( $_GET['openid_url'] ) once registration works in Habari. if ( ( Controller::get_action() != 'register' ) && !isset( $_GET['openid_url'] ) ) { if ( Controller::get_action() == 'login' ) { echo ' <form method="post" action="'. URL::get( 'openid' ) .'" id="admin_openidform"> <p> <label for="openid_url" class="incontent abovecontent">' . _t('OpenID Identifier') . '</label><input type="text" name="openid_url" id="openid_url"' . ( isset($openid_url) ? 'value="'. $openid_url . '"' : '' ) . ' placeholder="' . _t('openid identifier') . '" class="styledformelement"> </p> <p> <input id="openid_submit" class="submit" type="submit" value="Sign in using OpenID"> </p> </form> '; } else { echo ' <form method="post" action="'. URL::get( 'openid' ) .'" id="openidform"> <p> <label for="openid_url">OpenID Identifier:</label> <input type="text" size="25" name="openid_url" id="openid_url"> </p> <p> <input type="submit" value="Sign in using OpenID"> </p> </form> '; } } } public function action_theme_loginform_controls() { if ( isset( $_GET['openid_url'] ) ) { echo '<input type="hidden" value="'.$_GET['openid_url'].'" name="habari_openid_url">'; } } /* Uncomment once registration is supported by Habari. public function action_theme_registerform_controls() { if ( isset( $_GET['openid_url'] ) ) { echo '<input type="hidden" value="'.$_GET['openid_url'].'" name="habari_openid_url">'; } } */ public function action_theme_admin_user( $user ) { $openid_url = isset( $user->info->openid_url ) ? $user->info->openid_url : ''; echo ' <div class="container settings user openid" id="openid"> <h2>' . _t('OpenID') . '</h2> <div class="item clear" id="openid_url"> <span class="pct20"> <label for="habari_openid_url">' . _t('OpenID Identifier') . '</label> </span> <span class="pct80"> <input type="text" name="habari_openid_url" id="habari_openid_url" class="border" value="' . $openid_url . '" disabled> </span> </div> </div>'; } public function action_user_identify() { if ( ( Controller::get_action() == 'login' ) && !empty( $_POST['openid_url'] ) ) { self::openid_start(); } } // TODO: Add more security against form hijacking (for instance, check against server sent data) public function action_user_authenticate_successful( $user ) { if ( !empty( $_POST['habari_openid_url'] ) ) { $user->info->openid_url = $_POST['habari_openid_url']; } } function action_admin_header( $theme ) { // Add the css if this is the default login page if ( $theme->admin_page == 'login' ) { Stack::add( 'admin_stylesheet', array( $this->get_url() . '/openid.css', 'screen' ), 'openid_style' ); } } function getOpenIDURL() { if ( empty( $_POST['openid_url'] ) ) { EventLog::log( 'Expected an OpenID URL.', 'err', 'authentication', 'OpenID' ); throw new Exception( 'Expected an OpenID URL.' ); } return $_POST['openid_url']; } function getReturnTo() { return URL::get('openid'); } function getTrustRoot() { return Site::get_url('habari'); } function getStore() { $store_path = "/tmp/_php_consumer_test"; if ( !file_exists( $store_path ) && !mkdir( $store_path ) ) { EventLog::log( 'Could not create the FileStore directory: ' . $store_path, 'err', 'authentication', 'OpenID' ); throw new Exception( 'Could not create the FileStore directory: ' . $store_path . '. Please check the effective permissions.' ); } return new Auth_OpenID_FileStore( $store_path ); } function getConsumer() { require_once "Auth/OpenID/Consumer.php"; require_once "Auth/OpenID/FileStore.php"; require_once "Auth/OpenID/SReg.php"; $store = self::getStore(); return new Auth_OpenID_Consumer( $store ); } function openid_start() { $openid = self::getOpenIDURL(); $consumer = self::getConsumer(); $auth_request = $consumer->begin( $openid ); if ( !$auth_request ) { EventLog::log( 'Authentication error: Not a valid OpenID.', 'err', 'authentication', 'OpenID' ); throw new Exception( 'Authentication error: Not a valid OpenID.' ); } $sreg_request = Auth_OpenID_SRegRequest::build( array( 'nickname' ), array( 'fullname', 'email' ) ); if ( $sreg_request ) { $auth_request->addExtension( $sreg_request ); } if ( $auth_request->shouldSendRedirect() ) { $redirect_url = $auth_request->redirectURL( self::getTrustRoot(), self::getReturnTo() ); if ( Auth_OpenID::isFailure( $redirect_url ) ) { EventLog::log( 'Could not redirect to server: ' . $redirect_url->message, 'err', 'authentication', 'OpenID' ); throw new Exception( 'Could not redirect to server: ' . $redirect_url->message ); } else { header( "Location: ".$redirect_url ); } } else { $form_id = 'openid_message'; $form_html = $auth_request->formMarkup( self::getTrustRoot(), self::getReturnTo(), false, array( 'id' => $form_id ) ); if ( Auth_OpenID::isFailure( $form_html ) ) { EventLog::log( 'Could not prepare redirection form: ' . $form_html->message, 'err', 'authentication', 'OpenID' ); throw new Exception( 'Could not prepare redirection form: ' . $form_html->message ); } else { echo ' <html> <head> <title>OpenID transaction in progress</title> </head> <body onload="document.getElementById(\''.$form_id.'\').submit()"> '.$form_html.' </body> </html> '; } } } function openid_end() { $consumer = self::getConsumer(); $return_to = self::getReturnTo(); $response = $consumer->complete( $return_to, Auth_OpenId::getQuery( $_SERVER->raw( 'QUERY_STRING' ) ) ); switch( $response->status ) { case Auth_OpenID_CANCEL: EventLog::log( 'Verification cancelled.', 'err', 'authentication', 'OpenID' ); throw new Exception( 'Verification cancelled.' ); break; case Auth_OpenID_FAILURE: EventLog::log( 'OpenID authentication failed: ' . $response->message, 'err', 'authentication', 'OpenID' ); throw new Exception( 'OpenID authentication failed: ' . $response->message ); break; case Auth_OpenID_SUCCESS: $openid = $response->getDisplayIdentifier(); $esc_identity = htmlspecialchars( $openid, ENT_QUOTES ); $user = Users::get_by_info( 'openid_url', $openid ); if ( count( $user ) != 0 ) { if ( count( $user ) > 1 ) { EventLog::log( 'Authentication error: More than one user has this OpenID.', 'err', 'authentication', 'OpenID' ); throw new Exception( 'Authentication error: More than one user has this OpenID.' ); } $user[0]->remember(); EventLog::log( 'Successful login for ' . $user[0]->username, 'info', 'authentication', 'OpenID' ); header( "HTTP/1.1 100 Continue" ); header( "Location: " . Site::get_url( 'admin' ) ); header( "Connection: close" ); } else { Utils::redirect( URL::get( 'user', array( 'page'=>'login', 'openid_url' => $openid ), true ) ); } } } } ?> <file_sep><?php /** * Bumping - Bumps a post to first position (order by modified) if it's * modified or a comment is made (and approved) */ class Bumping extends Plugin { function info() { return array( 'name' => 'Bumping', 'license' => 'Apache Software License 2.0', 'url' => 'http://nashape.com/habari/plugins/bumping/', 'author' => '<NAME>', 'authorurl' => 'http://nashape.com/', 'version' => '1.0', 'description' => 'Posts that are updated or receive (approved) comments are bumped to the first post position.', 'copyright' => '2009'); } function filter_template_where_filters( $where_filters ) { $where_filters["orderby"] = "modified DESC, pubdate DESC"; return $where_filters; } function action_comment_insert_after( $comment ) { // check if comment is approved (user is logged in) if ( $comment->status == Comment::STATUS_APPROVED ) { $this->update_post_modified( $comment->post_id ); EventLog::log( 'bumped post ' . $comment->post_id, 'info', 'default', 'bumping' ); } } function action_admin_moderate_comments( $action, $comments, $handler ) { if ( $action == 'approve' || $action == 'approved' ) { foreach ( $comments as $c ) { $this->update_post_modified( $c->post_id ); EventLog::log( 'bumped post ' . $c->post_id . ', by admin approval', 'info', 'default', 'bumping' ); } } } private function update_post_modified( $post_id ) { $post = Post::get( array( 'id' => $post_id ) ); $post->modified = HabariDateTime::date_create(); $post->update(); } } ?> <file_sep><?php class NullTheme extends Theme { /** * Execute on theme init to apply these filters to output */ public function action_init_theme( ) { // Apply Format::autop() to comment content... Format::apply( 'autop', 'comment_content_out' ); // Truncate content excerpt at "more" or 140 characters... Format::apply( 'autop', 'post_content_excerpt' ); Format::apply_with_hook_params( 'more', 'post_content_excerpt', '', 140, 1 ); } public function add_template_vars( ) { // Auto add FormControl templates $user_formcontrols = glob( dirname( __FILE__ ) . '/*.formcontrol.php' ); foreach ( $user_formcontrols as $file ) { $name = substr( $file, strrpos( $file, '/' ) + 1, -1 * strlen( '.formcontrol.php' ) ); $this->add_template( $this->name . '_' . $name, $file ); } parent::add_template_vars( ); } public function filter_body_class( $body_class, $theme ) { if ( isset( $theme->posts ) && count( $theme->posts ) === 1 && $theme->posts instanceof Post ) { $body_class[] = Post::type_name( $theme->posts->content_type ) . '-' . $theme->posts->slug; $body_class[] = 'single'; } return $body_class; } public function filter_post_tags_list( $tags ) { if ( !count( $tags ) ) return 'No tags'; $tag_list = array(); foreach ( $tags as $tag ) { $tag_list[] = sprintf( '<li><a href="%s" rel="tag">%s</a></li>', URL::get('display_entries_by_tag', array( 'tag' => $tag->term ) ), $tag->term_display ); } return '<ul>' . implode( '', $tag_list ) . '</ul>'; } public function action_form_comment( $form ) { $form->append( 'fieldset', 'cf_fieldset', _t( 'Leave your thoughts' ) ); $form->cf_fieldset->append( 'wrapper', 'cf_rules' ); $form->cf_fieldset->cf_rules->append( 'static', 'comment_rules', '<ul><li>' . _t( 'You can use some HTML in your comment.' ) . '</li><li>' . _t( 'Your comment may not display immediately due to spam filtering. Please wait for moderation.' ) . '</li></ul>' ); $form->cf_fieldset->append( 'wrapper', 'cf_inputarea' ); $form->cf_content->move_before( $form->cf_commenter ); $form->cf_content->move_into( $form->cf_fieldset->cf_inputarea ); $form->cf_content->caption = _t( 'Your Comments' ); $form->cf_content->placeholder = _t( 'Your Comments' ); $form->cf_content->required = true; $form->cf_content->template = $this->name . '_textarea'; $form->cf_commenter->move_into( $form->cf_fieldset->cf_inputarea ); $form->cf_commenter->caption = _t( 'Name' ); $form->cf_commenter->placeholder = _t( 'Name' ); $form->cf_commenter->required = true; $form->cf_commenter->template = $this->name . '_text'; $form->cf_email->move_into( $form->cf_fieldset->cf_inputarea ); $form->cf_email->caption = _t( 'E-mail' ); $form->cf_email->placeholder = _t( 'E-mail' ); $form->cf_email->required = true; $form->cf_email->template = $this->name . '_email'; $form->cf_url->move_into( $form->cf_fieldset->cf_inputarea ); $form->cf_url->caption = _t( 'Website' ); $form->cf_url->placeholder = _t( 'Website' ); $form->cf_url->required = false; $form->cf_url->template = $this->name . '_url'; $form->cf_submit->move_into( $form->cf_fieldset->cf_inputarea ); $form->cf_submit->caption = _t( 'Send' ); $form->cf_submit->placeholder = _t( 'Send' ); $form->cf_submit->template = $this->name . '_submit'; } public function theme_header( $theme ) { Stack::add( 'template_stylesheet', array( Site::get_url('theme') . '/css/screen.css', 'screen' ), 'main' ); Stack::out( 'template_stylesheet', array( 'Stack', 'styles' ) ); } } ?><file_sep><?php /** * Calendar * * @package calendar * @version $Id$ * @author ayunyan <<EMAIL>> * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link http://ayu.commun.jp/habari-calendar */ class Calendar extends Plugin { private $week_starts = array(6 => 'Saturday', 0 => 'Sunday', 1 => 'Monday'); /** * action: plugin_activation * * @access public * @param string $file * @return void */ public function action_plugin_activation($file) { if (Plugins::id_from_file($file) != Plugins::id_from_file(__FILE__)) return; Options::set('calendar__week_start', 0); } /** * action: init * * @access public * @return void */ public function action_init() { $this->load_text_domain('calendar'); $this->add_template('calendar', dirname(__FILE__) . '/templates/calendar.php'); } /** * action: plugin_ui * * @access public * @param string $plugin_id * @param string $action * @return void */ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id != $this->plugin_id()) return; if ($action == _t('Configure')) { $form = new FormUI(strtolower(get_class($this))); $form->append('select', 'week_start', 'calendar__week_start', _t('Week starts on: ', 'calendar'), $this->week_starts); $form->append('submit', 'save', _t('Save')); $form->out(); } } /** * filter: plugin_config * * @access public * @return array */ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()) { $actions[] = _t('Configure'); } return $actions; } /** * theme: show_calendar * * @access public * @param object $theme * @return string */ public function theme_show_calendar($theme) { $handler_vars = Controller::get_handler_vars(); if (Controller::get_action() == 'display_date' && isset($handler_vars['month'])) { $year = (int)$handler_vars['year']; $month = (int)$handler_vars['month']; } else { $year = date('Y'); $month = date('m'); } $next_year = $year; $prev_year = $year; $next_month = $month + 1; $prev_month = $month - 1; if ($next_month == 13) { $next_month = 1; $next_year++; } if ($prev_month == 0) { $prev_month = 12; $prev_year--; } $start_time = mktime(0, 0, 0, $month, 1, $year); $end_time = mktime(0, 0, 0, $next_month, 1, $next_year); $t_posts_day = DB::get_column('SELECT pubdate FROM {posts} WHERE pubdate >= ? AND pubdate < ? AND status = ?', array($start_time, $end_time, Post::status('published'))); $posts_day = array(); @reset($t_posts_day); while (list(, $pubdate) = @each($t_posts_day)) { $posts_day[] = (int)date("j", $pubdate); } $month_start_week = date("w", $start_time); $month_days = date("t", $start_time); $week_days = array(_t('Sun', 'calendar'), _t('Mon', 'calendar'), _t('Tue', 'calendar'), _t('Wed', 'calendar'), _t('Thu', 'calendar'), _t('Fri', 'calendar'), _t('Sat', 'calendar')); $week_start = Options::get('calendar__week_start'); $calendar = array(); $day = 0; while (1) { $week = array(); for ($i = 0; $i < 7; $i++) { $wday = ($i + $week_start) % 7; if (count($calendar) == 0) { $week[] = array('label' => $week_days[($i + $week_start) % 7]); continue; } elseif ($day == 0) { if ($wday == $month_start_week) { $day = 1; if (array_search($day, $posts_day) !== false) { $week[] = array('label' => $day, 'url' => URL::get('display_entries_by_date', array('year' => $year, 'month' => sprintf('%02d', $month), 'day' => sprintf('%02d', $day)))); } else { $week[] = array('label' => $day); } } else { $week[] = array('label' => null); continue; } } elseif ($day >= $month_days) { $week[] = array('label' => null); continue; } else { $day++; if (array_search($day, $posts_day) !== false) { $week[] = array('label' => $day, 'url' => URL::get('display_entries_by_date', array('year' => $year, 'month' => sprintf('%02d', $month), 'day' => sprintf('%02d', $day)))); } else { $week[] = array('label' => $day); } } } $calendar[] = $week; if ($day == $month_days) break; } $theme->year = $year; $theme->month = $month; $theme->prev_month_url = URL::get('display_entries_by_date', array('year' => $prev_year, 'month' => sprintf('%02d', $prev_month))); $theme->next_month_url = URL::get('display_entries_by_date', array('year' => $next_year, 'month' => sprintf('%02d', $next_month))); $theme->calendar = $calendar; return $theme->fetch('calendar'); } } ?> <file_sep><?php include HABARI_PATH . '/system/admin/header.php'; ?> <form name="blogroll_quick_link" id="blogroll_quick_link" action="<?php URL::out('admin', 'page=blogroll_publish'); ?>" method="post"> <div class="pagesplitter"> <ul class="tabcontrol tabs"> <li class="quick_link_blogroll first last"><a href="#quick_link_blogroll"><?php _e( 'Add Quick Link', 'blogroll' ); ?></a></li> </ul> <div id="quick_link_blogroll" class="splitter"> <div class="splitterinside publish"> <div class="container"> <p><?php _e( 'Enter the URL or feed URL, other information will be "auto-discovered".', 'blogroll' ); ?></p> <div> <p><label for="quick_link" class="incontent"><?php _e( 'URL', 'blogroll' ); ?></label> <input type="text" id="quick_link" name="quick_link" size="100%" value="" class="styledformelement"></p> </div> <p><input type="submit" id="add_link" name="add_link" value="<?php _e( 'Add', 'blogroll' ); ?>"></p> </div> </div> </div> </div> </form> <form name="blogroll_publish" id="blogroll_publish" action="<?php URL::out('admin', 'page=blogroll_publish'); ?>" method="post"> <div class="publish"> <div class="container"> <p><label for="name" class="incontent"><?php _e( 'Blog Name', 'blogroll' ); ?></label> <input type="text" id="name" name="name" size="100%" value="<?php echo isset($name)?$name:''; ?>" class="styledformelement"></p> <p><label for="url" class="incontent"><?php _e( 'Blog URL', 'blogroll' ); ?></label> <input type="text" id="url" name="url" size="100%" value="<?php echo isset($url)?$url:''; ?>" class="styledformelement"></p> <p><label for="description" class="incontent"><?php _e( 'Description', 'blogroll' ); ?></label> <textarea id="description" name="description" rows="10" cols="114" class="styledformelement resizable"><?php echo isset($description)?$description:''; ?></textarea></p> <p><label for="tags" class="incontent"><?php _e( 'Tags, separated by, commas', 'blogroll' ); ?></label><input type="text" name="tags" id="tags" class="styledformelement" value="<?php if ( !empty( $tags ) ) { echo $tags; } ?>"></p> </div> </div> <div class="pagesplitter"> <ul class="tabcontrol tabs"> <?php $first = 'first'; $ct = 0; $last = ''; foreach($controls as $controlsetname => $controlset) : $ct++; if($ct == count($controls)) { $last = 'last'; } $class = "{$first} {$last}"; $first = ''; $cname = preg_replace('%[^a-z]%', '', strtolower($controlsetname)) . '_settings'; echo <<< EO_CONTROLS <li class="{$cname} {$class}"><a href="#{$cname}">{$controlsetname}</a></li> EO_CONTROLS; endforeach; ?> </ul> <?php foreach($controls as $controlsetname => $controlset): $cname = preg_replace('%[^a-z]%', '', strtolower($controlsetname)) . '_settings'; ?> <div id="<?php echo $cname; ?>" class="splitter"> <div class="splitterinside"> <?php echo $controlset; ?> </div> </div> <?php endforeach; ?> </div> <div class="publish"> <div id="formbuttons" class="container"> <p class="column span-13" id="left_control_set"> <input type="submit" id="save" name="save" class="publish" value="<?php _e( 'Save', 'blogroll' ); ?>"> </p> <p class="column span-3 last" id="right_control_set"></p> </div> </div> <div id="hidden"> <?php if ( !empty($id) ) : ?><input type="hidden" id="id" name="id" value="<?php echo $id; ?>"><?php endif; ?> </div> </form> <script type="text/javascript"> $(document).ready(function(){ <?php if( !empty( $id ) ) : ?> $('#left_control_set #save').attr('value', '<?php _e( 'Update', 'blogroll' ); ?>'); $('#left_control_set').append($('<input type="submit" name="auto_update" id="auto_update" value="<?php _e( 'Auto Update', 'blogroll' ); ?>">')); $('#auto_update').click(function(){ $('#blogroll_publish') .append($('<input type="hidden" name="quick_link" value="<?php echo $url; ?>">')) }); $('#right_control_set').append($('<input type="submit" name="delete" id="delete" class="delete" value="<?php _e( 'Delete', 'blogroll' ); ?>">')); $('#delete').click(function(){ $('#blogroll_publish') .append($('<input type="hidden" name="change" value="delete"><input type="hidden" name="blog_ids[]" value="<?php echo $id; ?>">')) .attr('action', '<?php URL::out( 'admin', 'page=blogroll_manage' ); ?>'); }); <?php endif; ?> }); </script> <?php include HABARI_PATH . '/system/admin/footer.php'; ?> <file_sep><?php /** * @todo generate nice report page in admin * @todo add email reports * @todo add cron to run DB optimization * @todo implement/include session manager code to keep session table clean * @todo check links in comments * @todo check for chosen type (html,xhtml,etc.) validation for post content_out * @todo lot's more */ class SiteMaintenance extends Plugin { const CHECK_LINKS_CRON = 'sitemaintenance_checklinks'; const TEXT_DOMAIN = 'sitemaintenance'; public function action_init() { spl_autoload_register( array( __CLASS__, '_autoload') ); // @todo move this to activation hook if ( ! CronTab::get_cronjob(self::CHECK_LINKS_CRON) ) { CronTab::add_weekly_cron( self::CHECK_LINKS_CRON, 'check_links_cron', _t('Check links in posts for errors', self::TEXT_DOMAIN) ); } } public function filter_check_links_cron ( $result ) { SiteMaintenanceLog::report_log('checking links', 'info', 'check_links', null); $this->check_links( Posts::get( 'content_type=' . Post::type('entry') ) ); } public static function _autoload($class_name) { if ( strtolower( $class_name ) == 'sitemaintenancelog' ) { include( dirname(__FILE__) . '/sitemaintenancelog.php' ); } elseif ( strtolower( $class_name ) == 'remoterequestsucks' ) { include( dirname(__FILE__) . '/remoterequestsucks.php' ); } } /** * Check if links are 404 or 302 */ protected function check_links( Posts $posts ) { foreach ( $posts as $post ) { $tokenizer = new HTMLTokenizer($post->content_out, false); $nodes = $tokenizer->parse(); $urls = array(); foreach ( $nodes as $node ) { if ( $node['type'] == HTMLTokenizer::NODE_TYPE_ELEMENT_OPEN && strtolower($node['name']) == 'a' ) { $urls[] = $node['attrs']['href']; } } $urls = array_unique($urls); if ( count($urls) > 0 ) { foreach ( $urls as $url ) { $request = new RemoteRequest($url, 'HEAD'); $headers = RemoteRequestSucks::head($url); if ( $headers ) { $status = $headers['status']; // is it 404 not found? if ( $status == 404 ) { $message = _t("404 at %s in post %s, got: %s", array($url, $post->slug, $status), 'sitemaintenance'); SiteMaintenanceLog::report_log($message, 'err', '404', serialize($headers)); } // is it 301 moved permanently? elseif ( $status == 301 ) { if ( isset($headers['location']) ) { $location = $headers['location']; } else { $location = _t('unknown', self::TEXT_DOMAIN); } $message = _t("301 at %s in post %s, moved to: %s", array($url, $post->slug, $location), 'sitemaintenance'); SiteMaintenanceLog::report_log($message, 'err', '301', serialize($headers)); } } } } } } } ?> <file_sep>CREATE SEQUENCE {rateit_log}_pkey_seq; CREATE TABLE {rateit_log} ( id INTEGER NOT NULL DEFAULT nextval('{rateit_log}_pkey_seq'), post_id INTEGER NOT NULL, rating SMALLINT NOT NULL, timestamp TIMESTAMP NOT NULL, ip BIGINT NOT NULL, PRIMARY KEY ( id ), UNIQUE ( post_id, ip ) ); CREATE INDEX rateit_log_ip_key ON {rateit_log}( ip ); CREATE INDEX rateit_log_post_id_key ON {rateit_log}( post_id ); <file_sep><?php /** * FeedList Plugin - Makes feeds available for output in a <ul> from a theme. * * To display the feed list in the template output, add this code where the * list should be displayed: * <code> * <?php echo $feedlist; ? > * </code> */ class FeedList extends Plugin { // Version info const VERSION = '0.2'; /** * Required plugin info() implementation provides info to Habari about this plugin. */ public function info() { return array ( 'name' => 'Feed List', 'url' => 'http://asymptomatic.net/', 'author' => '<NAME>', 'authorurl' => 'http://asymptomatic.net/', 'version' => self::VERSION, 'description' => 'Outputs an RSS feed as an unordered list.', 'license' => 'ASL', ); } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Feed List', '9a75f180-3da2-11dd-ae16-0800200c9a66', $this->info->version ); } /** * Plugin init action, executed when plugins are initialized. */ public function action_init() { // Register the name of a new database table. DB::register_table('feedlist'); } /** * Plugin plugin_activation action, executed when any plugin is activated * @param string $file The filename of the plugin that was activated. */ public function action_plugin_activation( $file ='' ) { // Was this plugin activated? if ( Plugins::id_from_file( $file ) == Plugins::id_from_file( __FILE__ ) ) { // Register a default event log type for this plugin EventLog::register_type( "default", "FeedList" ); // Register the name of a new database table DB::register_table('feedlist');// 'plugin_activation' hook is called without first calling 'init' // Create the database table, or upgrade it switch ( DB::get_driver_name() ) { case 'mysql': $schema = 'CREATE TABLE {feedlist} ( id INT UNSIGNED AUTO_INCREMENT, feed_id INT NOT NULL DEFAULT 0, guid VARCHAR(255) NOT NULL, title VARCHAR(255) NOT NULL, link VARCHAR(255) NOT NULL, updated DATETIME NOT NULL, description TEXT, PRIMARY KEY (id), UNIQUE KEY guid (guid) );'; break; case 'sqlite': $schema = 'CREATE TABLE {feedlist} ( id INTEGER PRIMARY KEY AUTOINCREMENT, feed_id INTEGER NOT NULL DEFAULT 0, guid VARCHAR(255) UNIQUE NOT NULL, title VARCHAR(255) NOT NULL, link VARCHAR(255) NOT NULL, updated DATETIME NOT NULL, description TEXT );'; break; } DB::dbdelta( $schema ); // Log a table creation event EventLog::log('Installed feedlist cache table.'); // Add a periodical execution event to be triggered hourly CronTab::add_hourly_cron( 'feedlist', 'load_feeds', 'Load feeds for feedlist plugin.' ); // Log the cron creation event EventLog::log('Added hourly cron for feed updates.'); } } /** * Plugin plugin_deactivation action, executes when any plugin is deactivated. * @param string $plugin_id The filename of the plguin that was deactivated. */ public function action_plugin_deactivation( $file ) { // Was this plugin deactivated? if ( Plugins::id_from_file( $file ) == Plugins::id_from_file( __FILE__ ) ) { // Drop the database table DB::query( 'DROP TABLE IF EXISTS {feedlist};'); // Log a dropped table event EventLog::log('Removed feedlist cache table.'); // Remove the periodical execution event CronTab::delete_cronjob( 'feedlist' ); // Log the cron deletion event. EventLog::log('Deleted cron for feed updates.'); } } /** * Executes when the admin plugins page wants to know if plugins have configuration links to display. * * @param array $actions An array of existing actions for the specified plugin id. * @param string $plugin_id A unique id identifying a plugin. * @return array An array of supported actions for the named plugin */ public function filter_plugin_config( $actions, $plugin_id ) { // Is this plugin the one specified? if($plugin_id == $this->plugin_id()) { // Add a 'configure' action in the admin's list of plugins $actions[]= 'Configure'; } return $actions; } /** * Executes when the admin plugins page wants to display the UI for a particular plugin action. * Displays the plugin's UI. * * @param string $plugin_id The unique id of a plugin * @param string $action The action to display */ public function action_plugin_ui( $plugin_id, $action ) { // Display the UI for this plugin? if($plugin_id == $this->plugin_id()) { // Depending on the action specified, do different things switch($action) { // For the action 'configure': case 'Configure': // Create a new Form called 'feedlist' $ui = new FormUI( 'feedlist' ); // Add a text control for the feed URL $feedurl = $ui->append('textmulti', 'feedurl', 'feedlist__feedurl', 'Feed URL'); // Mark the field as required $feedurl->add_validator( 'validate_required' ); // Mark the field as requiring a valid URL // $feedurl->add_validator( 'validate_url' ); // When the form is successfully completed, call $this->updated_config() $ui->on_success( array( $this, 'updated_config') ); $ui->set_option( 'success_message', _t( 'Configuration updated' ) ); // Display the form $ui->append( 'submit', 'save', _t( 'Save' ) ); $ui->out(); break; } } } /** * Perform actions when the admin plugin form is successfully submitted. * * @param FormUI $ui The form that successfully completed * @return boolean True if the normal processing should occur to save plugin options from the form to the database */ public function updated_config( $ui ) { $ui->save(); // Delete the cached feed data DB::query( 'TRUNCATE {feedlist}' ); // Reset the cronjob so that it runs immediately with the change CronTab::delete_cronjob( 'feedlist' ); CronTab::add_hourly_cron( 'feedlist', 'load_feeds', 'Load feeds for feedlist plugin.' ); return false; } /** * Plugin add_template_vars action, executes just before a template is to be rendered. * Note that $theme and $handler_vars are passed by reference, and so you can add things to them. * @param Theme $theme The theme object that is displaying the template. * @param array $handler_vars Variables passed in the URL to the action handler. */ public function action_add_template_vars( $theme, $handler_vars ) { // Get the most recent ten items from each feed $feedurls = Options::get( 'feedlist__feedurl' ); if ( $feedurls ) { $feeds = array(); $feeditems = array(); foreach( $feedurls as $index=>$feedurl ) { $items = DB::get_results( 'SELECT * FROM {feedlist} WHERE feed_id = ? ORDER BY updated DESC LIMIT 10', array($index) ); // If there are items to display, produce output if(count($items)) { $feed = "<ul>\n"; foreach ( $items as $item ) { $feed.= sprintf( "\t" . '<li><a href="%1$s">%2$s</a></li>' . "\n", $item->link, $item->title ); } $feed.= "</ul>\n"; } else { $feed = '<p>Sorry, no items to display.</p>'; } $feeds[] = $feed; $feeditems = array_merge($feeditems, $items); } // Assign the output to the template variable $feedlist //<? echo $feedlist[0];? >// This will output the first feed list in the template $theme->assign( 'feedlist', $feeds ); $theme->assign( 'feeditems', $feeditems ); } else { $theme->assign( 'feedlist', "Feedlist needs to be configured." ); } } /** * Plugin load_feeds filter, executes for the cron job defined in action_plugin_activation() * @param boolean $result The incoming result passed by other sinks for this plugin hook * @return boolean True if the cron executed successfully, false if not. */ public function filter_load_feeds( $result ) { $feedurls = Options::get( 'feedlist__feedurl' ); foreach( $feedurls as $feed_id=>$feedurl ) { // Fetch the feed from remote into an XML object if($feedurl == '') { echo "Could not update feed"; } else { $xml = simplexml_load_string( RemoteRequest::get_contents( $feedurl ) ); $channel = $xml->channel; // If there are feed items, cache them to the feedlist table if ( ( $channel->item ) ) { foreach( $channel->item as $item ) { if( isset( $item->guid ) ) { // doesn't work when guid is an array. $guid = $item->guid; } else { $guid = md5( $item->asXML() ); } DB::query(' REPLACE INTO {feedlist} (feed_id, guid, title, link, updated, description) VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP, ?);', array( $feed_id, $guid, $item->title, $item->link, $item->description ) ); } } else if ( ( $xml->item ) ) { foreach( $xml->item as $item ) { if( isset( $item->guid ) ) { $guid = $item->guid; } else { $guid = md5( $item->asXML() ); } DB::query(' REPLACE INTO {feedlist} (feed_id, guid, title, link, updated, description) VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP, ?);', array( $feed_id, $guid, $item->title, $item->link, $item->description ) ); } } else { // feed isn't currently readable. } // Log an event that the feed was updated EventLog::log("Updated feed {$feedurl}"); } } $olddate = DB::get_value('SELECT updated FROM ' . DB::table('feedlist') . ' ORDER BY updated DESC LIMIT 10, 1'); DB::query('DELETE FROM ' . DB::table('feedlist') . ' WHERE updated < ?', array($olddate)); return $result;// Only change a cron result to false when it fails. } public function xmlrpc_system__testme($input) { return $input[0]; } } ?> <file_sep><?php /** * MyTheme is a custom Theme class for the Hemingway theme. * * @package Habari */ /** * @todo This stuff needs to move into the custom theme class: */ // Apply Format::autop() to post content... Format::apply( 'autop', 'post_content_out' ); // Apply Format::autop() to comment content... Format::apply( 'autop', 'comment_content_out' ); // Apply Format::tag_and_list() to post tags... Format::apply( 'tag_and_list', 'post_tags_out' ); // Apply Format::nice_date() to post date... // Format::apply( 'nice_date', 'post_pubdate_out', 'm.j' ); // Format::apply( 'nice_date', 'post_pubdate_home', 'm/d/y' ); // Format::apply( 'nice_time', 'post_pubdate_time', 'ga' ); // Apply Format::nice_date() to comment date... // Format::apply( 'nice_date', 'comment_date', 'F jS, Y' ); // Limit post length to 1 paragraph or 100 characters. As currently implemented // in home.php and entry.multiple.php, the first post will be displayed in full // and subsequent posts will be excerpts. search.php uses excerpts for all posts. // Comment out this line to have full posts. //Format::apply_with_hook_params( 'more', 'post_content_excerpt', '', 100, 1 ); Format::apply_with_hook_params( 'more', 'post_content_out', '', 100, 4 ); // We must tell Habari to use MyTheme as the custom theme class: define( 'THEME_CLASS', 'MyTheme' ); /** * A custom theme for Hemingway output */ class MyTheme extends Theme { //Set to 'white' or 'black' depending on your color scheme. const CSS_COLOR = 'black'; //Set to 'header' or 'sidebar' depending on where you want to position your twitter plugin. const TWITTER_IN = 'sidebar'; /** * Add additional template variables to the template output. * * You can assign additional output values in the template here, instead of * having the PHP execute directly in the template. The advantage is that * you would easily be able to switch between template types (RawPHP/Smarty) * without having to port code from one to the other. * * You could use this area to provide "recent comments" data to the template, * for instance. * * Note that the variables added here should possibly *always* be added, * especially 'user'. * * Also, this function gets executed *after* regular data is assigned to the * template. So the values here, unless checked, will overwrite any existing * values. */ public function add_template_vars() { $this->assign('css_color', self::CSS_COLOR); $this->assign('twitter_in', self::TWITTER_IN); if( !$this->template_engine->assigned( 'pages' ) ) { $this->assign('pages', Posts::get( array( 'content_type' => 'page', 'status' => Post::status('published'), 'nolimit' => 1 ) ) ); } if( !$this->template_engine->assigned( 'user' ) ) { $this->assign('user', User::identify() ); } if( !$this->template_engine->assigned( 'page' ) ) { $this->assign('page', isset( $page ) ? $page : 1 ); } $this->assign( 'nav_pages', Posts::get( array( 'limit' => 5, 'content_type' => 'page', 'status' => 'published', 'orderby' => 'slug ASC' ))); $this->assign( 'home_recent_posts', Posts::get(array ( 'limit' => 2, 'content_type' => 'entry', 'status' => 'published', 'orderby' => 'pubdate DESC' ))); $this->assign( 'recent_posts', Posts::get(array ( 'limit' => 3, 'content_type' => 'entry', 'status' => 'published', 'orderby' => 'pubdate DESC' ))); // FormUI comment form $this->add_template( 'formcontrol_text', dirname(__FILE__).'/forms/formcontrol_text.php', true); $this->add_template( 'formcontrol_textarea', dirname(__FILE__).'/forms/formcontrol_textarea.php', true); $this->add_template( 'formcontrol_submit', dirname(__FILE__).'/forms/formcontrol_submit.php', true); parent::add_template_vars(); } } ?> <file_sep><?php class Suggestr extends Plugin { var $rules; public function info() { return array( 'name' => 'Suggestr', 'author' => 'Habari Community', 'description' => 'Provides tag suggestions for posts', 'url' => 'http://habariproject.org', 'version' => '0.1', 'license' => 'Apache License 2.0' ); } public function action_admin_header() { Stack::add( 'admin_header_javascript', URL::get_from_filesystem(__FILE__) . '/suggestr.js', 'suggestr' ); Stack::add( 'admin_stylesheet', array(URL::get_from_filesystem(__FILE__) . '/suggestr.css', 'screen'), 'suggestr' ); } public function action_ajax_tag_suggest( $handler ) { if(!isset($handler->handler_vars['text'])) { $text= ''; } else { $text= $handler->handler_vars['text']; } $tags = array(); $tags = $this->fetch_yahoo_tags($text); $tags = serialize($tags); $tags = Plugins::filter('tag_suggestions', $tags, $text); $tags = unserialize($tags); $count = count($tags); if($count == 0) { $message = _t('No tag suggestions could be found'); } else { $message = sprintf( '%d tag ' . _n( _t( 'suggestion'), _t( 'suggestions' ), $count ) . ' could be found.', $count ); } echo json_encode(array('count' => $count, 'tags' => $tags, 'message' => $message)); } public function fetch_yahoo_tags( $text ) { $appID = '<KEY>T68GI-'; $context = $text; $request = new RemoteRequest('http://search.yahooapis.com/ContentAnalysisService/V1/termExtraction', 'POST'); $request->set_params(array( 'appid' => $appID, 'context' => $context )); $tags = array(); // Utils::debug($request->execute()); if(!is_object($request->execute())) { $response = $request->get_response_body(); $xml = new SimpleXMLElement($response); foreach($xml->Result as $tag) { $tags[] = strval($tag); } } return $tags; } } ?> <file_sep><?php class DatabaseOptimizer extends Plugin { const VERSION = '0.4'; public function info ( ) { return array ( 'name' => 'Database Optimizer', 'url' => 'http://habariproject.org', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org', 'version' => self::VERSION, 'description' => 'Automagically optimizes your database tables weekly.', 'license' => 'Apache License 2.0' ); } public function action_update_check ( ) { Update::add( 'DatabaseOptimizer', 'E619A6D0-15F8-11DD-8567-98DE55D89593', self::VERSION ); } public function action_plugin_activation ( $file ='' ) { if ( Plugins::id_from_file( $file ) == Plugins::id_from_file( __FILE__ ) ) { if ( Options::get( 'database_optimizer__frequency' ) == null ) { Options::set( 'database_optimizer__frequency', 'weekly' ); } // add a cronjob to kick off next and optimize our db now CronTab::add_single_cron( 'optimize database tables initial', 'optimize_database', HabariDateTime::date_create( time() ), 'Optimizes database tables.' ); $this->create_cron(); } } public function create_cron ( ) { // delete the existing cronjob CronTab::delete_cronjob( 'optimize database tables' ); $frequency = Options::get( 'database_optimizer__frequency' ); $function_name = 'add_' . $frequency . '_cron'; call_user_func_array( array( 'CronTab', $function_name ), array( 'optimize database tables', 'optimize_database', 'Optimizes database tables automagically ' . $frequency ) ); EventLog::log( 'CronTab added to optimize database tables ' . $frequency . '.' ); } public function action_plugin_deactivation ( $file ='' ) { if ( Plugins::id_from_file( $file ) == Plugins::id_from_file( __FILE__ ) ) { CronTab::delete_cronjob( 'optimize database tables initial' ); CronTab::delete_cronjob( 'optimize database tables' ); Options::delete( 'database_optimizer__frequency' ); } } public function filter_optimize_database ( $result, $paramarray ) { $space_saved = 0; $tables = 0; switch ( DB::get_driver_name() ) { case 'mysql': $q = 'SHOW TABLE STATUS WHERE data_free > 0'; $tables = DB::get_results( $q ); if ( count( $tables ) > 0 ) { foreach ( $tables as $table ) { $q2 = 'OPTIMIZE TABLE ' . $table->Name; if ( DB::query( $q2 ) ) { $space_saved += $table->Data_free; $tables++; } } EventLog::log( 'Database Tables Optimized. ' . Utils::human_size( $space_saved ) . ' reclaimed from ' . Locale::_n( 'table', 'tables', $tables ) . '.' ); } $result = true; break; case 'sqlite': if ( DB::exec( 'VACUUM' ) ) { $result = true; EventLog::log( 'SQLite database VACUUM\'ed successfully.' ); } else { $result = false; } break; default: $result = false; break; } return $result; } public function filter_plugin_config ( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t( 'Optimize' ); $actions[] = _t( 'Configure' ); } return $actions; } public function action_plugin_ui ( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { if ( $action == _t( 'Configure' ) ) { $class_name = strtolower( get_class( $this ) ); $form = new FormUI( $class_name ); $form->append( 'select', 'frequency', 'database_optimizer__frequency', _t( 'Optimization Frequency' ), array( 'hourly' => 'hourly', 'daily' => 'daily', 'weekly' => 'weekly', 'monthly' => 'monthly' ) ); $form->append( 'submit', 'save', _t( 'Save' ) ); $form->on_success( array( $this, 'updated_config' ) ); $form->out(); } if ( $action == _t( 'Optimize' ) ) { $result = $this->filter_optimize_database( true, array() ); if ( $result ) { echo 'Database Optimized successfully!'; } else { echo 'There was an error, or your database platform is not supported!'; } } } } public function updated_config ( $form ) { $form->save(); // create our cronjob $this->create_cron(); } } ?> <file_sep><?php $theme->display( 'header'); ?> <!-- page --> <div class="page" id="<?php echo $post->slug; ?>"> <div id="left-col"> <h2><?php echo $post->title_out; ?></h2> <?php echo $post->content_out; ?> </div> <div id="right-col"> <?php $theme->display ( 'sidebar' ); ?> </div> </div> <!-- /page --> <?php $theme->display ('footer'); ?> <file_sep><?php $theme->display('header');?> <div id="crontab" class="container settings"> <h2><?php _e('%s Cron Job', array($cron->name), 'crontabmanager'); ?></h2> <?php echo $form; ?> </div> <?php $theme->display('footer');?> <file_sep> <li id="widget-tagcloud" class="widget"> <h3><?php _e('Tag Cloud', 'binadamu'); ?></h3> <?php $theme->tag_cloud(); ?> </li> <file_sep><?php class Thickbox extends Plugin { /** * Adds needed files to the theme stacks (javascript and stylesheet) */ public function action_init() { Stack::add( 'template_header_javascript', Site::get_url('scripts') . '/jquery.js', 'jquery' ); Stack::add( 'template_header_javascript', Site::get_url('user') . '/plugins/thickbox/thickbox-compressed.js', 'thickbox-js' ); Stack::add( 'template_stylesheet', array( Site::get_url('user') . '/plugins/thickbox/thickbox.css', 'screen,projector'), 'thickbox-css' ); } /** * Add help text to plugin configuration page **/ public function help() { $help = _t( 'There is no configuration for this plugin. Once this plugin is activated, add <code>class="thickbox"</code> to the link of an image file to open it in a hybrid modal box. More information and advanced instructions are available at the <a href="http://jquery.com/demo/thickbox/" title="ThickBox 3.1 Documentation and Examples">jQuery Demo page</a>.' ); return $help; } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Thickbox', '5e276e9e-c7ce-4010-a979-42580feefdd9', $this->info->version ); } } ?> <file_sep><?php class extracontent extends Plugin { public function info() { return array( 'name' => 'Extra Content', 'version' => '1.0', 'url' => 'http://habariproject.org/', 'author' => 'The Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Display one additional textarea on the entry publish page.', 'copyright' => '2010', ); } public function help() { $help = _t( '<p>Activate, then create a new entry or edit an existing one to see the new textarea. Display it with <code>&lt;?php echo $post->info->extra; ?&gt;</code> wherever you have a Post object.</p><p>This can be formatted, also, as <code>&lt;?php echo Format::autop( $post->info->extra ); ?&gt;</code></p>', "extra_content" ); return $help; } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Extra Content', '1b39ce6e-3576-49ca-aa45-326688720711', $this->info->version ); } /** * Add additional controls to the publish page tab * * @param FormUI $form The form that is used on the publish page * @param Post $post The post being edited **/ public function action_form_publish( $form, $post ) { switch( $post->content_type ) { case Post::type( 'entry' ): $extra = $form->append( 'textarea', 'extra_textarea', 'null:null', _t( 'Extra', 'extra_content' ) ); $extra->value = $post->info->extra; $extra->class[] = 'resizable'; $extra->rows = 3; $extra->template = 'admincontrol_textarea'; $form->move_after($form->extra_textarea, $form->content); break; default: return; } } /** * Modify a post before it is updated * * @param Post $post The post being saved, by reference * @param FormUI $form The form that was submitted on the publish page */ public function action_publish_post( $post, $form ) { switch( $post->content_type ) { case Post::type( 'entry' ): $post->info->extra = $form->extra_textarea->value; break; default: return; } } } ?> <file_sep><?php /** * RenderType Plugin Class * * This plugin adds a formatter called 'render_type' which templates can use * to render text, such as titles, as images in a chosen font. It requires * ImageMagick and the PHP Imagick library.(It will not work with GD.) * * Here is a minimal example of how you might use Render Type in * action_init_theme in your theme.php(see the documentation for * filter_render_type below for more details): * * Format::apply( 'render_type', 'post_title_out', '/path/to/font.ttf' ); * * The image data for a unique combination of input string, font, size, color, * background color, and output format(e.g. PNG, JPEG, etc.) is cached * after the first time it is requested, so performance should be reasonable, * though I've performed no load testing. This cache is currently never * expired -- not even if you deactivate the plugin. This may be * addressed in the future. * * Nota bene: This plugin is not suitable for hiding email addresses from * harvesters -- the original text appears in the formatter's output in the * alt and title attributes of the img element. * * @package render_type **/ require_once 'render-type-formatter.php'; class RenderTypePlugin extends Plugin { const VERSION = '0.5'; /** * function info * Returns information about this plugin * @return array Plugin info array **/ public function info() { return array( 'name' => 'Render Type', 'url' => 'http://svn.habariproject.org/habari-extras/plugins/render-type/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org', 'version' => self::VERSION, 'description' => 'A plugin for rendering text as images.', 'license' => 'Public Domain', ); } /** * function action_update_check * Check for more recent versions of this plugin. **/ public function action_update_check() { Update::add( 'RenderType', 'FEFD6638-838E-11DD-8AFF-17DB55D89593', self::VERSION ); } /** * function filter_render_type * Returns HTML markup containing an image with a data: URI * @param string $content The text to be rendered * @param string $font_file The path to a font file in a format ImageMagick can handle * @param integer $font_size The font size, in pixels (defaults to 28) * @param string $font_color The font color (defaults to 'black') * @param string $background_color The background color (defaults to 'transparent') * @param string $output_format The image format to use (defaults to 'png') * @return string HTML markup containing the rendered image **/ public function filter_render_type( $content, $font_file, $font_size, $font_color, $background_color, $output_format, $width) { // Preprocessing $content // 1. Strip HTML tags. It would be better to support them, but we just strip them for now. // 2. Decode HTML entities to UTF-8 charaaters. $content = html_entity_decode( strip_tags( $content ), ENT_QUOTES, 'UTF-8' ); // 3. Do word wrap when $width is specified. Not work for double-width characters. if ( is_int( $width ) ) { $content = wordwrap( $content, floor( $width / ( 0.3 * $font_size ) ) ); } $cache_group = strtolower( get_class( $this ) ); $cache_key = $font_file . $font_size . $font_color . $background_color . $output_format . $content . $width; if ( ! Cache::has( array( $cache_group, md5( $cache_key ) ) ) ) { $font_color = new ImagickPixel( $font_color ); $background_color = new ImagickPixel( $background_color ); $draw = new ImagickDraw(); $draw->setFont( $font_file ); $draw->setFontSize( $font_size ); $draw->setFillColor( $font_color ); $draw->setTextEncoding( 'UTF-8' ); $draw->annotation(0, $font_size * 2, $content); $canvas = new Imagick(); $canvas->newImage( 1000, $font_size * 5, $background_color ); $canvas->setImageFormat( $output_format ); $canvas->drawImage( $draw ); // The following line ensures that the background color is set in the PNG // metadata, when using that format. This allows you, by specifying an RGBa // background color (e.g. #ffffff00) to create PNGs with a transparent background // for browsers that support it but with a "fallback" background color (the RGB // part of the RGBa color) for IE6, which does not support alpha in PNGs. $canvas->setImageBackgroundColor( $background_color ); $canvas->trimImage( 0 ); Cache::set( array( $cache_group, md5( $cache_key ) ), $canvas->getImageBlob() ); } return '<img class="rendered-type" src="' . URL::get( 'display_rendertype', array( 'hash' => md5( $cache_key ), 'format' => $output_format ) ) . '" title="' . $content . '" alt="' . $content . '">'; } public function filter_rewrite_rules( $rules ) { $rules[] = new RewriteRule(array( 'name' => 'display_rendertype', 'parse_regex' => '%^rendertype/(?P<hash>[0-9a-f]{32}).(?P<format>png)$%i', 'build_str' => 'rendertype/{$hash}.{$format}', 'handler' => 'UserThemeHandler', 'action' => 'display_rendertype', 'rule_class' => RewriteRule::RULE_PLUGIN, 'is_active' => 1, 'description' => 'display_rendertype' )); return $rules; } public function action_handler_display_rendertype( $handler_vars ) { $cache_group = strtolower( get_class( $this ) ); if( Cache::has( array( $cache_group, $handler_vars['hash'] ) ) ) { header( 'Content-type: image/' . $handler_vars['format'] ); header( 'Pragma: '); header( 'Cache-Control: public' ); header( 'Expires: ' . gmdate("D, d M Y H:i:s", strtotime("+10 years")) . ' GMT' ); echo Cache::get( array( $cache_group, $handler_vars['hash'] ) ); } else { echo 'Cache not found'; } } } ?><file_sep><?php $theme->display('header'); ?> <!-- multiple --> <div id="content" class="hfeed"> <?php $theme->mutiple_h1(); ?> <?php foreach ($posts as $post) { ?> <div id="entry-<?php echo $post->slug; ?>" class="hentry entry <?php echo $post->statusname , ' ' , $post->tags_class; ?>"> <div class="entry-head"> <h2 class="entry-title"><a href="<?php echo $post->permalink; ?>" title="<?php echo strip_tags($post->title); ?>" rel="bookmark"><?php echo $post->title_out; ?></a></h2> <ul class="entry-meta"> <li class="entry-date"><abbr class="published" title="<?php echo $post->pubdate->out(HabariDateTime::ISO8601); ?>"><?php echo $post->pubdate->out('F j, Y'); ?></abbr></li> <li class="entry-time"><abbr class="published" title="<?php echo $post->pubdate->out(HabariDateTime::ISO8601); ?>"><?php echo $post->pubdate->out('g:i a'); ?></abbr></li> <li class="comments-link"><a href="<?php echo $post->permalink; ?>#comments" title="<?php _e('Comments to this post', 'binadamu') ?>"><?php printf(_n('%1$d Comment', '%1$d Comments', $post->comments->approved->count, 'binadamu'), $post->comments->approved->count); ?></a></li> <?php if (is_array($post->tags)) { ?> <li class="entry-tags"><?php echo $post->tags_out; ?></li> <?php } ?> <?php if ($loggedin) { ?> <li class="entry-edit"><a href="<?php echo $post->editlink; ?>" title="<?php _e('Edit post', 'binadamu') ?>"><?php _e('Edit', 'binadamu') ?></a></li> <?php } ?> </ul> </div> <div class="entry-content"> <?php echo $post->content_out; ?> </div> </div> <?php } ?> <div id="page-selector"> <?php $theme->prev_page_link(); ?> <?php $theme->page_selector(null, array('leftSide' => 2, 'rightSide' => 2)); ?> <?php $theme->next_page_link(); ?> </div> </div> <hr /> <!-- /multiple --> <?php $theme->display('sidebar'); ?> <?php $theme->display('footer'); ?> <file_sep><?php /* * TODO: Make increment configurable * TODO: Make config nicer (server type/name/port/ssl dropdown instead of server string) * TODO: allow user to choose content status */ class pbem extends Plugin { public function info() { return array( 'name' => 'PBEM', 'version' => '0.1.0', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Post by sending e-mail to a special mailbox or IMAP folder.', 'copyright' => '2009' ); } public function action_plugin_activation( $file ) { if ( realpath( $file ) == __FILE__ ) { CronTab::add_cron( array( 'name' => 'pbem_check_accounts', 'callback' => array( __CLASS__, 'check_accounts' ), 'increment' => 600, 'description' => 'Check for new PBEM mail every 600 seconds.', ) ); ACL::create_token( 'PBEM', 'Directly administer posts from the PBEM plugin', 'pbem' ); } } public function action_plugin_deactivation( $file ) { if ( realpath( $file ) == __FILE__ ) { CronTab::delete_cronjob( 'pbem_check_accounts' ); ACL::destroy_token( 'PBEM' ); } } /* Go to http://your-blog/admin/pbem to immediately check the mailbox and post new posts AND SEE ERRORS. */ function action_admin_theme_get_pbem( $handler, $theme ) { self::check_accounts(); exit; } public static function check_accounts() { $users = Users::get(); foreach ($users as $user) { $server_string = $user->info->pbem__server_string; $server_username = $user->info->pbem__server_username; $server_password = $user->info->pbem__server_password; if ($server_string) { $mh = imap_open($server_string, $server_username, $server_password, OP_SILENT | OP_DEBUG); $n = imap_num_msg($mh); for ($i = 1; $i <= $n; $i++) { $body = imap_body($mh, $i); $header = imap_header($mh, $i); $tags = ''; if (stripos($body, 'tags:') === 0) { list($tags, $body) = explode("\n", $body, 2); $tags = trim(substr($tags, 5)); $body = trim($body); } $postdata = array( 'slug' =>$header->subject, 'title' => $header->subject, 'tags' => $tags, 'content' => $body, 'user_id' => $user->id, 'pubdate' => HabariDateTime::date_create( date( 'Y-m-d H:i:s', $header->udate ) ), 'status' => Post::status('published'), 'content_type' => Post::type('entry'), ); // Utils::debug( $postdata ); // This htmlspecialchars makes logs with &lt; &gt; etc. Is there a better way to sanitize? EventLog::log( htmlspecialchars( sprintf( 'Mail from %1$s (%2$s): "%3$s" (%4$d bytes)', $header->fromaddress, $header->date, $header->subject, $header->Size ) ) ); $post = Post::create( $postdata ); if ($post) { // done with the message, now delete it. Comment out if you're testing. imap_delete( $mh, $i ); } else { EventLog::log( 'Failed to create a new post?' ); } } imap_expunge( $mh ); imap_close( $mh ); } } return true; } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t('Configure', 'pbem'); if ( User::identify()->can( 'PBEM' ) ) { // only users with the proper permission // should be able to retrieve the emails $actions[]= _t( 'Execute Now' ); } } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure', 'pbem') : $ui = new FormUI( 'pbem' ); $server_string = $ui->append( 'text', 'server_string', 'user:pbem__server_string', _t('Mailbox (<a href="http://php.net/imap_open">imap_open</a> format): ', 'pbem') ); $server_string->add_validator( 'validate_required' ); $server_username = $ui->append( 'text', 'server_username', 'user:pbem__server_username', _t('Username: ', 'pbem') ); $server_username->add_validator( 'validate_required' ); $server_password = $ui->append( 'password', 'server_password', 'user:pbem__server_password', _t('Password: ', '<PASSWORD>') ); $server_password->add_validator( 'validate_required' ); $ui->append( 'submit', 'save', _t( 'Save', 'pbem' ) ); $ui->set_option( 'success_message', _t( 'Configuration saved', 'pbem' ) ); $ui->out(); break; case _t('Execute Now','pbem') : $this->check_accounts(); Utils::redirect( URL::get( 'admin', 'page=plugins' ) ); break; } } } /** * filter the permissions so that admin users can use this plugin **/ public function filter_admin_access_tokens( $require_any, $page, $type ) { // we only need to filter if the Page request is for our page if ( 'pbem' == $page ) { // we can safely clobber any existing $require_any // passed because our page didn't match anything in // the adminhandler case statement $require_any= array( 'super_user' => true, 'pbem' => true ); } return $require_any; } } ?> <file_sep><?php // get header ?> <?php $theme->display ( 'header'); ?> <body id="single" > <div id="shadow"> <div id="rap"> <?php // get the nav etc ?> <?php include "topbanner.php"; ?> <div id="content"> <div class="post"> <!-- Post title --> <h3 class="storytitle">Error 404: Page not found</h3> <!-- Actual post --> <div class="storycontent"> </div> </div> </div> <?php // get footer ?> <?php $theme->display ( 'footer' ); ?> </div> </div> </body> </html><file_sep><?php class Spamview extends Plugin { /** * Add update beacon support **/ public function action_update_check() { Update::add( $this->info->name, 'd346880b-67a6-43ab-b3aa-61250d86b7fe', $this->info->version ); } /** * Initialization, useful to check for options * * @return void **/ public function action_init() { if( Options::get('spamview__spambutton') === NULL ) { Options::set('spamview__spambutton', true); } if( Options::get('spamview__logbutton') === NULL ) { Options::set('spamview__logbutton', false); } } /** * action_plugin_activation * Registers the core modules with the Modules class. Add these modules to the * dashboard if the dashboard is currently empty. * @param string $file plugin file */ function action_plugin_activation( $file ) { if( Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__) ) { Modules::add( 'Latest Spam' ); } } /** * action_plugin_deactivation * Unregisters the core modules. * @param string $file plugin file */ function action_plugin_deactivation( $file ) { if( Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__) ) { Modules::remove_by_name( 'Latest Spam' ); } } /** * Create plugin configuration **/ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t('Configure'); } return $actions; } /** * Create configuration panel */ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure') : $form = new FormUI( strtolower( get_class( $this ) ) ); $form->append( 'checkbox', 'spambutton', 'spamview__spambutton', _t('Enable delete all spam button') ); $form->append( 'checkbox', 'logbutton', 'spamview__logbutton', _t('Enable delete all logs button') ); $form->append( 'submit', 'save', _t('Save') ); $form->out(); break; } } } /** * filter_dash_modules * Registers the modules with the Modules class. */ function filter_dash_modules( $modules ) { if(!User::identify()->can( 'manage_all_comments' )) { return $modules; } // array_push( $modules, 'Latest Spam' ); $this->add_template( 'dash_spam', dirname( __FILE__ ) . '/spam.module.php' ); return $modules; } /** * filter_dash_module_latest_spam * Function used to set theme variables to the latest spam dashboard widget * @param string $module_id * @return string The contents of the module */ public function filter_dash_module_latest_spam( $module, $module_id, $theme ) { $comments= Comments::get(array('status' => array(Comment::status('spam'), Comment::status('unapproved')), 'limit' => 8 )); $theme->latestspam_comments = $comments; $theme->spambutton = Options::get('spamview__spambutton'); $theme->spamcount = Comments::count_total( Comment::STATUS_SPAM, FALSE ); $module['title'] = '<a href="' . Site::get_url('admin') . '/comments?status=' . Comment::status('spam') . '">' . _t('Latest Spam') . '</a>'; // $module['options'] = _t( 'You should not be here' ); $module['content'] = $theme->fetch( 'dash_spam' ); return $module; } /** * Add CSS & JS to admin stack * * @return void **/ public function action_admin_header() { if( Options::get('spamview__spambutton') ) { Stack::add('admin_stylesheet', array(URL::get_from_filesystem(__FILE__) . '/spamview.css', 'screen'), 'spamview'); Stack::add( 'admin_header_javascript', URL::get_from_filesystem(__FILE__) . '/spamview.js', 'spamview', array('jquery', 'jquery.hotkeys') ); } } /** * Handles spam deletion * * @return void **/ public function action_auth_ajax_deleteall( $handler ) { $result = array(); switch( $handler->handler_vars['target'] ) { case 'spam': if(!User::identify()->can( 'manage_all_comments' )) { Session::error( _t( 'You do not have permission to do that action.' ) ); break; } $total = Comments::count_total( Comment::STATUS_SPAM, FALSE ); Comments::delete_by_status( Comment::status('spam') ); Session::notice( sprintf( _t( 'Deleted all %s spam comments.' ), $total ) ); break; case 'logs': if(!User::identify()->can( 'manage_logs' )) { Session::error( _t( 'You do not have permission to do that action.' ) ); break; } $to_delete = EventLog::get( array( 'date' => 'any', 'nolimit' => 1 ) ); $count = 0; foreach( $to_delete as $log ) { $log->delete(); $count++; } Session::notice( sprintf( _t( 'Deleted all %s log entries.' ), $count ) ); break; } $result['messages'] = Session::messages_get( true, 'array' ); echo json_encode( $result ); } /** * Inject the delete all button * * @return void **/ public function action_admin_info( $theme, $page ) { if( $page == 'comments' && Options::get('spamview__spambutton') == TRUE ) { $spamcount = Comments::count_total( Comment::STATUS_SPAM, FALSE ); echo '<a href="#" id="deleteallspam" class="deleteall">' . sprintf( _t( 'Clear spam' ), $spamcount ) . '</a>'; } if( $page == 'logs' && Options::get('spamview__logbutton') == TRUE ) { echo '<a href="#" id="deletealllogs" class="deleteall">' . _t( 'Clear logs' ) . '</a>'; } return; } } ?><file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <link rel="stylesheet" href="<?php Site::out_url( 'theme' ); ?>/blueprint/screen.css" type="text/css" media="screen, projection" /> <link rel="stylesheet" href="<?php Site::out_url( 'theme' ); ?>/blueprint/print.css" type="text/css" media="print" /> <!--[if IE]><link rel="stylesheet" href="<?php Site::out_url( 'theme' ); ?>/blueprint/ie.css" type="text/css" media="screen, projection" /><![endif]--> <link rel="stylesheet" href="<?php Site::out_url( 'theme' ); ?>/blueprint/style.css" type="text/css" media="screen" /> <title><?php if($request->display_entry && isset($post)) { echo "{$post->title} - "; } ?><?php Options::out( 'title' ) ?></title> <link rel="alternate" type="application/atom+xml" title="Atom 1.0" href="<?php $theme->feed_alternate(); ?>" /> <link rel="edit" type="application/atom+xml" title="Atom Publishing Protocol" href="<?php URL::out( 'atompub_servicedocument' ); ?>" /> <link rel="EditURI" type="application/rsd+xml" title="RSD" href="<?php URL::out( 'rsd' ); ?>" /> <?php $theme->header();?> <script type="text/javascript"> $(function(){ $('#main').corner({ tl: { radius: 3 }, tr: { radius: 3 }, bl: { radius: 3 }, br: { radius: 3 }, antiAlias: true, autoPad: true, validTags: ["div"] }); }) </script> </head> <body> <div class="container"> <div id="header" class="push-4 span-16"> <h1><a href="<?php Site::out_url( 'habari' ); ?>"><?php Options::out( 'title' ); ?></a></h1> </div> <div id="searchbox" class="push-4 span-16"> <?php include 'searchform.php'; ?> </div><file_sep><?php /** * Rino theme footer */ ?> </div> <?php $theme->footer() ?> </body> </html> <file_sep><?php /********************************** * * Word Count for Posts * * usage: <?php echo $post->word_count; ?> * *********************************/ class PostWordCount extends Plugin { const VERSION= '0.3'; public function info() { return array( 'name' => 'Post Word Count', 'url' => 'http://mikelietz.org/code/habari/counters.php', 'author' =>'<NAME>', 'authorurl' => 'http://mikelietz.org', 'version' => self::VERSION, 'description' => 'Counts words in a single post', 'license' => 'Apache License 2.0', ); } public function help() { $help = _t( 'To use, <code>&lt;?php echo $post->word_count; ?&gt;</code>.' ); return $help; } public function action_update_check() { Update::add( 'Post Word Count', 'a0a50d90-6e0b-11dd-ad8b-0800200c9a66', $this->info->version ); } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t( 'Configure' ); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t( 'Configure' ): $class_name= strtolower( get_class( $this ) ); $ui= new FormUI( $class_name ); $add_title= $ui->append( 'checkbox', 'add_title', $class_name . '__add_title', _t( 'Include title words in count?' ) ); $ui->append( 'submit', 'save', 'save' ); $ui->out(); break; } } } public function action_init() { $class_name= strtolower( get_class( $this ) ); $this->config[ 'add_title' ]= Options::get( $class_name . '__add_title' ); } public function filter_post_word_count( $word_count, $post ) { $allcharacters = 'ÁÀÂÄǍĂĀÃÅǺĄƁĆĊĈČÇĎḌƊÉÈĖÊËĚĔĒĘẸƎƏƐĠĜǦĞĢƔĤḤĦIÍÌİÎÏǏĬĪĨĮỊĴĶƘĹĻŁĽĿŃŇÑŅÓÒÔÖǑŎŌÕŐỌØǾƠŔŘŖŚŜŠŞȘṢŤŢṬÚÙÛÜǓŬŪŨŰŮŲỤƯẂẀŴẄǷÝỲŶŸȲỸƳŹŻŽẒáàâäǎăāãåǻąɓćċĉčçďḍɗéèėêëěĕēęẹǝəɛġĝǧğģɣĥḥħıíìiîïǐĭīĩįịĵķƙĸĺļłľŀʼnńňñņóòôöǒŏōõőọøǿơŕřŗśŝšşșṣſťţṭúùûüǔŭūũűůųụưẃẁŵẅƿýỳŷÿȳỹƴźżžẓΑΆΒΓΔΕΈΖΗΉΘΙΊΪΚΛΜΝΞΟΌΠΡΣΤΥΎΫΦΧΨΩΏαάβγδεέζηήθιίϊΐκλμνξοόπρσςτυύϋΰφχψωώÆǼǢÐĐIJŊŒÞŦæǽǣðđijŋœßþŧ'; return str_word_count( strip_tags( ( $this->config[ 'add_title' ] ? $post->content_out . " {$post->title}" : $post->content_out ) ), 0, $allcharacters ); } } ?> <file_sep><?php // Apply Format::tag_and_list() to post tags... Format::apply( 'tag_and_list', 'post_tags_out' ); // Apply Format::nice_date() to post date... Format::apply( 'nice_date', 'post_pubdate_out', 'F j, Y g:ia' ); // Limit post length on the home page to 1 paragraph or 100 characters Format::apply( 'autop', 'post_content_excerpt' ); Format::apply_with_hook_params( 'more', 'post_content_excerpt', '', 100, 1 ); // Apply Format::nice_date() to post date... Format::apply( 'nice_date', 'post_pubdate_out', 'F j, Y g:ia' ); define( 'THEME_CLASS', 'wings' ); class wings extends Theme { public function add_template_vars() { if( !$this->template_engine->assigned( 'pages' ) ) { $this->assign('pages', Posts::get( array( 'content_type' => 'page', 'status' => Post::status('published'), 'nolimit' => 1 ) ) ); } } public function monthname($id) { if($id == 1) { return "January"; } elseif ($id == 2) { return "February"; } elseif ($id == 3) { return "March"; } elseif ($id == 4) { return "April"; } elseif ($id == 5) { return "May"; } elseif ($id == 6) { return "June"; } elseif ($id = 10) { return "October"; } } } ?> <file_sep><?php $theme->display( 'header'); ?> <!-- 404 --> <div class="page" id="four-o-four"> <div id="left-col"> <h2>404 Error</h2> <p>The page you are looking forward could not be found.</p> </div> <div id="right-col"> <?php $theme->display ( 'sidebar' ); ?> </div> </div> <!-- /404 --> <?php $theme->display ('footer'); ?> <file_sep><?php /** * @file backup and restore SQLite storage snapshots for Habari. * * As long as this is a development plugin, I've found enough reasons to make * use of gzip and other facilities for handling the 'backups'. This is not a * backup plugin replacement. * * @author ilo **/ /** * SQLite snapshot plugin class */ class SQLiteSnapshot extends Plugin { /** * Plugin public methods section. */ /** * Plugin activation action. * Create custom requirements: token, * @param string $file plugin being activated. **/ public function action_plugin_activation( $file ) { if ( realpath( $file ) == __FILE__ ) { // Register our own log type. EventLog::register_type( 'default', 'snapshot' ); // Create an ACL token. ACL::create_token( 'manage_sqlite_snapshots', _t('Create and restore site snapshots'), 'Administration' ); // Set a default value for the backup directory. $backup_path = Site::get_path('user', true) . 'files' . DIRECTORY_SEPARATOR; if ( !is_writable( $backup_path ) || !is_dir( $backup_path ) ) { $link = $this->helper_build_admin_link( array( 'configaction' => 'Configure'), _t('configure the plugin')); Session::notice( _t( 'Default backup directory is not writable, please %s first.', array( $link ) ) ); } Options::set('sqlite_snapshot__path', $backup_path ); if ( DB::get_driver_name() != 'sqlite' ) { Session::notice( _t( 'Your current database driver is not SQLite, so all options will be disabled.' ) ); } } } /** * Plugin deactivation action. * Remove any site item, but don't remove site snapshots. * @param string $file plugin being activated. **/ public function action_plugin_deactivation( $file ) { if ( Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__) ) { // Remove Dashboard module, and ACL token. Modules::remove_by_name( 'Site Snapshots' ); ACL::destroy_token( 'manage_sqlite_snapshots' ); // Notify remaining snapshot files are found in the system. if ( $snapshots = $this->sqlite_snapshot_get() ) { Session::notice( _t( 'There are snapshots left in the backup folder.' ) ); } // Remove variables created by this plugin. Options::delete('sqlite_snapshot__path'); } } /** * Plugin user interface action. * Reacts on user seletected option to show the form or take the snapshot. * @param string $plugin_id Id of plugin that fired the action. * @param string $action action fired. * @return FormUI for the required action. **/ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t( 'Configure' ) : // Show the main configuration form. $ui = $this->form_ui_build_configuration(); $ui->out(); break; case _t( 'Snapshot' ) : // Take the snapshot of current db file, and redirect to restore. $this->sqlite_snapshot_take(); Utils::redirect( URL::get('admin', array('page' => 'plugins', 'configure' => $this->plugin_id, 'configaction' =>'Restore') )); break; case _t( 'Restore' ) : $ui = $this->form_ui_build_restore(); $ui->out(); break; } } } /** * Plugin configuration filter. * Declare the plugin configuration entries. * @param array $actions array of actions available. * @param string $plugin_id Id of plugin to put configuration actions. **/ public function filter_plugin_config( $actions, $plugin_id ) { // Taking and restore snapshots are only available to permissionsed users. if ( ( $plugin_id == $this->plugin_id() ) && ( User::identify()->can( 'manage_sqlite_snapshots' ) ) && ( DB::get_driver_name() == 'sqlite' ) ) { $actions = array ( _t( 'Configure'), _t( 'Snapshot' ), _t( 'Restore' ), ); } return $actions; } /** * Declare dashboard widgets of this plugin. * @param array $modules list of modules that have dashboard widgets. * @return array including the module controled widgets. **/ public function filter_dash_modules( $modules ) { if ( User::identify()->can( 'manage_sqlite_snapshots' ) ) { // If user has permissions, let him show the snapshots dashboard widget. array_push( $modules, 'Site Snapshots' ); } return $modules; } /** * Generate snapshot dashboard widget. * @param array $module associative array with information for the widget. * @param integer $module_id widget id. * @param theme $theme Theme object. * @return array associative array with the module information: title, content.. **/ public function filter_dash_module_site_snapshots( $module, $module_id, $theme ) { if ( ! User::identify()->can( 'manage_sqlite_snapshots' ) ) { // this user doesn't have access to snapshots. return $module; } return $this->form_ui_dashboard_snapshots($module, $module_id, $theme); } /** * Forms section */ /** * Builds the configuration form. * @return FormUI */ private function form_ui_build_configuration() { $ui = new FormUI( strtolower( get_class( $this ) ) ); $ui->append( 'text', 'path', 'option:sqlite_snapshot__path', _t('Path to backup directory: ') ); $ui->append( 'submit', 'save', _t('Save' ) ); $ui->path->add_validator( array( $this, 'form_ui_configuration_path_validator' ) ); return $ui; } /** * Verify that $path is a folder and is writable. * @param mixed $path value of the field being validated. * @param FormControl $control control being validated. * @param FormUI $ui submitted configuration form. * @return array validation errors to be shown. **/ public function form_ui_configuration_path_validator( $path, $control, $ui ) { $errors = array(); if ( !is_writable( $path ) || !is_dir( $path ) ) { $errors[] = _t( 'Selected directory is not writable' ); } if ( ! in_array( substr( $path, -1 ), array( "/", "\\") ) ) { $errors[] = _t( 'Backup directory must finish with a slash' ); } return $errors; } /** * Builds the snapshot restore form. * @return FormUI */ private function form_ui_build_restore() { // Build a list of snapshots. $ui = new FormUI( strtolower( get_class( $this ) ) ); // Only keep building the UI if there are snapshots. if ( $snapshots = $this->sqlite_snapshot_get() ) { // Format the date and time according to user preferences. $user = User::identify(); $format = $user->info->locale_date_format . " " . $user->info->locale_time_format; // Build the select options. $options = array(); foreach ( $snapshots as $id => $snapshot) { $options[$id] = date($format, $id); } $ui->append( 'select', 'snapshots', 'null:null', _t('Select snapshot to restore')); $ui->snapshots->options = $options; // Set a default value (passed in the url by dashboard widget). $ui->snapshots->value = isset($_GET['snapshot']) ? intval ( $_GET['snapshot'] ) : 0 ; // Restoring the session table would log out current session, set a way // to keep it working. $ui->append( 'checkbox', 'session_keep', 'null:null', _t( 'Keep current session active' ) ); $ui->append( 'submit', 'restore', _t('Restore' ) ); $ui->on_success( array( $this, 'form_ui_configuration_restore_success' ) ); } else { //No snapshosts found, append a link to encourage a snapshot creation. $link = $this->helper_build_admin_link( array( 'configaction' => 'Snapshot'), _t( 'First snapshot' )); $ui->append( 'label', 'info', _t('Create the %s now!', array( $link ) ) ); } return $ui; } /** * Callback function for the restore configuration form. Try to restore from * the selected snapshot in the form, and keep current session active if * enabled. * @param FormUI $ui * @return FormUI */ public function form_ui_configuration_restore_success( $ui ) { $selected = $ui->snapshots->value; // Get all the snapshots $snapshots = $this->sqlite_snapshot_get(); // and now keep session active by inserting into the database. if ( $ui->session_keep->value == true ) { $data = Session::read(session_id()); } // Call the restore function $this->sqlite_snapshot_restore( $snapshots[$selected] ); // and now keep session active by inserting into the database. if ( $ui->session_keep->value == true ) { Session::write(session_id(), $data); } return $ui->out; } /** * Build the content of the Site Snapshots widget. * @param array $module associative array with information for the widget. * @param integer $module_id widget id. * @param theme $theme Theme object. * @return array associative array with the module information: title, content. */ private function form_ui_dashboard_snapshots($module, $module_id, $theme) { // Build dashboard content $content = '<ul class="items">'; if ( $files = $this->sqlite_snapshot_get() ) { // Format the date and time according to user preferences. $info = new UserInfo(User::identify()->id); $format = $info->locale_date_format . " " . $info->locale_time_format; // Loop up to eight files. $count = 0; foreach ( $files as $id => $snapshot ) { $content .= '<li class="item clear"><span class="date pct25 minor">' . date( $format, $id ) . '</span>'; $content .= '<span class="message pct60 minor">' . $snapshot . '</span>'; $content .= '<span class="comments pct15">'; $content .= $this->helper_build_admin_link( array( 'snapshot' => $id ), _t( 'Restore' ), _t( 'Restore the system using this snapshot.' ) ); $content .= '</span></li>'; if ( $count++ > 6 ) break; } } else { // Build a link to inform that there are no snapshots available for this site. $content .= '<li class="item clear"><span class="message pct85 minor">'; $settings = array ( 'page' => 'plugins', 'configure' => $this->plugin_id(), 'configaction' => 'Snapshot', 'snapshot' => time(), ); $content .= sprintf( _t( "No backups found. Make a snapshot %s " ), $this->helper_build_admin_link( $settings, _t( 'Now' ) ) ); $content .= '</span></li>'; } $content .= '</ul>'; // Set widget information. $module['title'] = _t( 'Latest Snapshots' ); $module['content'] = $content; return $module; } /** * API functions */ /** * Find snapshot(s) file(s) in the configured directory. Only return those * with the same database name that current site. * @param string $id of the snapshot to find, it is a timestamp value to string. * @Return an array in the form of [timestamp] => filename with the available * snapshots, empty array if none found. */ private function sqlite_snapshot_get( $id = null) { $snapshots = array(); // find only snapshots of this site. Multiple database files from other // sites can be in this directory. $db_name = $this->helper_get_sqlite_db_name(); $files = glob( Options::get( 'sqlite_snapshot__path' ) . $db_name . '-*.db' ); if ( count( $files ) ) { // Files are in dbname-timestamp.db form. rsort( $files ); // create the return array foreach ( $files as $snapshot) { $tstamp = substr($snapshot, -13, 10); $snapshots[$tstamp] = $snapshot; } if ( isset( $id ) && isset( $snapshots[$id] ) ){ return array( $id => $snapshots[$id]); } } return $snapshots; } /** * Creates a snapshot of current sqlite database. * @return boolean true or false if snapshot has been created successfuly. **/ private function sqlite_snapshot_take() { // Get current database name. if ( ! $db_name = $this->helper_get_sqlite_db_name() ) { return false; } // Build paths $db_file = Site::get_path( 'user', TRUE ) . $db_name; $outfile = Options::get('sqlite_snapshot__path') . basename( $db_name . '-' . time() . '.db' ); // Verify that final file does not exist, just in case. if ( file_exists( $outfile ) || is_dir($outfile) ) { Session::error( _t( 'Can not create backup file: a file or a directory with that name exist, try again.' ) ); return false; } // let's optimize the DB file before backing it up. It is a devel module // so don't expect locking database or other things. DB::query( 'VACUUM' ); if ( $of = fopen( $outfile, 'wb9' ) ) { if ( $if = fopen( $db_file, 'rb' ) ) { while ( ! feof( $if ) ) { fwrite( $of, fread( $if, 1024*512 ) ); } fclose( $if ); fclose( $of ); Session::notice( _t( 'Snapshot created' )); return true; } else { Session::error( _t( 'Can not open current database for backup.' ) ); } fclose( $of ); } else { Session::error( _t( 'Can not create backup file.' ) ); } return false; } /** * Restores a snapshot of an sqlite database. * @param string $infile file path to be restored. * @return boolean true or false if snapshot has been created successfuly. **/ private function sqlite_snapshot_restore( $infile ) { // Get current database name. if ( ! $db_name = $this->helper_get_sqlite_db_name() ) { return false; } // Build paths $db_file = Site::get_path( 'user', TRUE ) . $db_name; // Verify that final file does not exist, just in case. if ( !file_exists( $infile ) ) { Session::error( _t( 'Can not restore from this snapshot file: the file does not exist.' ) ); return false; } if ( $of = fopen( $db_file, 'wb9' ) ) { if ( $if = fopen( $infile, 'rb' ) ) { while ( ! feof( $if ) ) { fwrite( $of, fread( $if, 1024*512 ) ); } fclose( $if ); fclose( $of ); Session::notice( _t( 'Snapshot restored' )); return true; } else { Session::error( _t( 'Can not open snapshot file.' ) ); } fclose( $of ); } else { Session::error( _t( 'Can not write to current database.' ) ); } return false; } /** * Helper functions. */ /** * Returns current sqlite database file path. * @return string path to current database name. */ private function helper_get_sqlite_db_name() { // Get database name, if we get here there is a connection string. list( $type, $db_name )= explode( ':', Config::get( 'db_connection' )->connection_string ); if( basename( $db_name ) == $db_name && !file_exists( './' . $db_name ) ) { return $db_name; } Session::error( _t( 'Unable to find current database. Interesting.. please report this in the tracker' ) ); return false; } /** * Simple function to build a link. * @param array $settings settings for the link. * @param string $text Link readable text. * @param string $title the Alternative title. * @return string built html code of the link. **/ private function helper_build_admin_link( $settings = array(), $text, $title = '' ) { $settings += array( 'page' => 'plugins', 'configure' => $this->plugin_id(), 'configaction' => 'Restore', 'snapshot' => 0, ); return '<a href="' . URL::get('admin', $settings, true) . '" title="' . $title . '">' . $text . '</a>'; } } ?> <file_sep><?php class Mpango extends Plugin { public function action_update_check() { Update::add( $this->info->name, 'e283ba9d-d16d-4932-b9dd-0117e84a3ba8', $this->info->version ); } /** * Set up needed stuff for the plugin **/ public function install() { Post::add_new_type( 'project' ); // Give anonymous users access $group = UserGroup::get_by_name('anonymous'); $group->grant('post_project', 'read'); } /** * Remove stuff we installed **/ public function uninstall() { Post::deactivate_post_type( 'project' ); } /** * action_plugin_activation * @param string $file plugin file */ function action_plugin_activation( $file ) { if( Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__) ) { self::install(); } } /** * action_plugin_deactivation * @param string $file plugin file */ function action_plugin_deactivation( $file ) { if( Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__) ) { self::uninstall(); } } /** * Create name string **/ public function filter_post_type_display($type, $foruse) { $names = array( 'project' => array( 'singular' => _t('Project'), 'plural' => _t('Projects'), ) ); return isset($names[$type][$foruse]) ? $names[$type][$foruse] : $type; } /** * Modify publish form */ public function action_form_publish($form, $post) { if ( $post->content_type == Post::type('project') ) { $options = $form->publish_controls->append('fieldset', 'options', _t('Project')); $options->append('text', 'repository', 'null:null', _t('Repository URL'), 'tabcontrol_text'); if($post->project->repository != null) { $options->repository->value = $post->project->repository->base; } $options->append('text', 'commands', 'null:null', _t('Commands URL'), 'tabcontrol_text'); $options->commands->value = $post->project->commands_url; } } /** * Save our data to the database */ public function action_publish_post( $post, $form ) { if ($post->content_type == Post::type('project')) { // $this->action_form_publish( $form, $post, 'create'); $post->info->repository = $form->repository->value; $post->info->commands_url = $form->commands->value; } } /** * Creates the Project class for each post **/ public function filter_post_project($project, $post) { if($post->content_type == Post::type('project')) { return new Project( $post ); } else { return $project; } } /** * Add needed elements to header * * **/ public function action_template_header($theme) { if( $theme->request->display_post && $theme->post->project != null ) { if( $theme->post->project->type == 'ubiquity' ) { echo '<link rel="commands" href="' . $theme->post->project->commands_url . '" name="Ubiquity Commands" />'; } } } } /** * Class for projects, is a subclass of post */ class Project { function __construct( $post ) { $this->post = $post; } public function __get( $property ) { switch ( $property ) { case 'type': if( $this->xml != null ) { $this->type = (string) $this->xml['type']; } elseif( $this->commands_url != null ) $this->type = 'ubiquity'; else { $this->type = 'generic'; } return $this->type; case 'xml_url': if( $this->repository == null ) { $this->xml_url = null; } else { $this->xml_url = $this->repository->trunk . $this->post->slug . '.plugin.xml'; } return $this->xml_url; case 'commands_url': if( $this->post->info->commands_url == null ) { $this->commands_url = null; } else { $this->commands_url = $this->post->info->commands_url; } return $this->commands_url; case 'repository': if($this->post->info->repository == (null || false || '')) { $this->repository = null; } else { $repository = new stdClass; $repository->base = $this->post->info->repository; $repository->trunk = $repository->base . 'trunk/'; $this->repository = $repository; } return $this->repository; case 'description': $this->description = (string) $this->xml->description; return $this->description; case 'version': $this->version = (string) $this->xml->version; return $this->version; case 'license': $this->license = array( 'url' => (string) $this->xml->license['url'], 'name' => (string) $this->xml->license ); return $this->license; case 'authors': $authors = array(); foreach( $this->xml->author as $author) { $authors[] = array( 'url' => (string) $author['url'], 'name' => (string) $author ); } $this->authors = $authors; return $this->authors; case 'help': if( isset($this->xml->help) ) { foreach($this->xml->help->value as $help) { $this->help = (string) $help; } } else { $this->help = NULL; } return $this->help; case 'xml': if( $this->xml_url == null ) { $this->xml = null; } else { $this->xml = $this->cached_xml( $this->xml_url, 'mpango_plugin_xml_' . $this->post->slug ); } return $this->xml; case 'forum': if( $this->type == 'plugin' ) { $this->forum = $this->get_forum(); return $this->forum; } else { return NULL; } } } public function get_forum() { // Functionality discontinued return NULL; $forum = new stdClass(); $forum->new = 'https://habariproject.org/forums/post.php?CategoryID=1'; $forum->tag = $this->post->slug; $forum->url = 'https://habariproject.org/forums/search.php?PostBackAction=Search&Type=Topics&Tag=' . $forum->tag; $forum->atom = 'https://habariproject.org/forums/search.php?PostBackAction=Search&Type=Topics&Page=1&Feed=ATOM&Tag=' . $forum->tag . '&FeedTitle=Search+Results+Feed+%28Tag%3A+ ' . $forum->tag . '%29'; $forum->xml = $this->cached_xml( $forum->atom, NULL, FALSE ); $forum->entries = array(); foreach( $forum->xml->entry as $element ) { $entry = new stdClass(); $entry->title = (string) $element->title; $entry->url = (string) $element->link['href']; $entry->date = HabariDateTime::date_create( (string) $element->updated ); $entry->summary = Format::summarize( (string) $element->summary, 10 ) ; $forum->entries[] = $entry; } return $forum; } private function cached_xml( $url, $key = NULL, $force = FALSE ) { if( $key == null ) { $key = Utils::md5( $url ); } if( Cache::has( $key ) && $force == FALSE ) { $raw = Cache::get( $key ); $xml = new SimpleXMLElement( $raw ); } else { $xml = simplexml_load_file( $url ); Cache::set( $key, $xml->asXML() ); } return $xml; } } ?><file_sep><?php class Quoticious extends Plugin { function info() { return array( 'name' => 'Quoticious', 'version' => '1.0', 'url' => 'http://habariproject.org', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org', 'license' => 'Apache License 2.0', 'description' => 'Allows quotes to be collected' ); } /** * Registers this plugin for updates against the beacon */ public function action_update_check() { Update::add('Quoticious', 'cffb07c5-ab53-42e7-b42d-08133097244c', $this->info->version); } public function action_init() { Post::add_new_type('quote'); } public function action_form_publish ($form, $post) { if($post->content_type == Post::type('quote') || $form->content_type->value == Post::type('quote')) { $quote = $form->publish_controls->append('fieldset', 'quote', _t('Quote')); $quote->append('text', 'quote_author', 'null:null', _t('Author'), 'tabcontrol_text'); $quote->quote_author->value = $post->info->quote_author; $quote->append('text', 'quote_url', 'null:null', _t('URL'), 'tabcontrol_text'); $quote->quote_url->value = $post->info->quote_url; return $form; } } public function action_publish_post ( $post, $form ) { if($post->content_type == Post::type('quote') || $form->content_type->value == Post::type('quote')) { if( strlen( $form->quote->quote_author->value ) ) { $post->info->quote_author = $form->quote->quote_author->value; } if( strlen( $form->quote->quote_url->value ) ) { $post->info->quote_url = $form->quote->quote_url->value; } } } } ?><file_sep><!-- commentsform --> <div class="comments"> <h4 id="respond" class="reply">Leave a Reply</h4> <?php $post->comment_form()->out(); ?> </div> <!-- /commentsform --> <file_sep><?php class NicEditor extends Plugin { /* * NicEditor * */ /* Required Plugin Informations */ public function info() { return array( 'name' => 'NicEditor', 'version' => '0.3', 'url' => 'http://habariproject.org/', 'author' => 'The Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'NicEditor Plugin for Habari', 'copyright' => '2010' ); } /** * Add the JavaScript required for the NicEdit editor to the publish page */ public function action_admin_header($theme) { if ( $theme->page == 'publish' ) { Stack::add( 'admin_header_javascript', $this->get_url() . '/nicEditor/nicEdit.js', 'niceditor' ); } } /** * Instantiate the NicEdit editor and enable media silos */ public function action_admin_footer($theme) { if ( $theme->page == 'publish' ) { $iconsPath = $this->get_url() . '/nicEditor/nicEditorIcons.gif'; echo <<<NICEDIT <script type="text/javascript"> $('[@for=content]').removeAttr('for'); new nicEditor({iconsPath : "$iconsPath"}).panelInstance('content'); habari.editor = { insertSelection: function(value) { $(".nicEdit").append(value); } } </script> NICEDIT; } } /** * Enable update notices to be sent using the Habari beacon */ public function action_update_check() { Update::add( 'NicEdit', '2ba6f5fe-b634-4407-bea1-a358c20b146a', $this->info->version ); } } ?> <file_sep><?php class AccountManager extends Plugin { /** * Provide plugin info to the system */ public function info() { return array( 'name' => 'Account Manager', 'version' => '1.0', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Mozilla Account Manager plugin for Habari.', 'copyright' => '2010' ); } /** * Filter function called by the plugin hook `rewrite_rules` * Add a new rewrite rule to the database's rules. * * Call `AccountManager::act('host-meta')` when a request for the host-meta `/.well-known/host-meta` is received. * Call `AccountManager::act('amcd')` when a request for the Account Manager Control Document `/amcd` is received. * * @param array $db_rules Array of rewrite rules compiled so far * @return array Modified rewrite rules array, we added our custom rewrite rule */ public function filter_rewrite_rules( $db_rules ) { $db_rules[]= RewriteRule::create_url_rule( '"amcd"', 'AccountManager', 'amcd' ); // This could be used for when the extant forms require extra values to work than what client-side AM provides, otherwise remove: $db_rules[]= RewriteRule::create_url_rule( '"amcd"/method', 'AccountManager', 'amcd_method' ); return $db_rules; } /** * */ public function action_init( ) { if(User::identify()->loggedin) { header("X-Account-Management-Status: active; name='" . User::identify()->username . "'"); } else { header("X-Account-Management-Status: passive"); } header('X-Account-Management: ' . URL::get('amcd')); } /** * Act function called by the `Controller` class. * Dispatches the request to the proper action handling function. * * @param string $action Action called by request, we only support 'amcd' and 'host-meta' */ public function act( $action ) { switch ( $action ) { case 'amcd': self::amcd(); break; case 'amcd_method': self::amcd_method(); break; case 'host-meta': self::hostmeta(); break; } } /** */ public function amcd() { $json = array( 'methods' => array( 'username-password-form' => array ( // Username+Password profile 'connect' => array( 'method' => 'POST', 'path' => URL::get('user', array('page' => 'login')), 'params' => array( 'username' => 'habari_username', 'password' => '<PASSWORD>', ), ), 'disconnect' => array( 'method' => 'POST', 'path' => URL::get('user', array('page' => 'logout')), ), 'changepassword' => array( 'method' => 'POST', 'path' => URL::get('user', array('page' => 'logout')), ), 'sessionstatus' => array( 'method' => 'GET', 'path' => URL::get('user', array('page' => 'login')), ), 'accountstatus' => array( 'method' => 'GET', 'path' => URL::get('auth', array('page' => 'login')), ), ), ), ); /* Clean the output buffer, so we can output from the header/scratch. */ ob_clean(); header( 'Content-Type: application/json' ); echo json_encode($json); } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'AccountManager', '7b0c466c-16fe-4668-8366-50af0ba0dc5a', $this->info->version ); } } ?> <file_sep><?php define( 'IMPORT_BATCH', 100 ); /** * Chyrp Importer - Imports data from Chyrp * */ class ChyrpImport extends Plugin implements Importer { private $supported_importers = array(); const TYPE_MYSQL = 0; const TYPE_SQLITE = 1; /** * Initialize plugin. * Set the supported importers. */ public function action_init() { $this->supported_importers = array( _t( 'Chyrp Database' ) ); } /** * Return a list of names of things that this importer imports * * @return array List of importables. */ public function filter_import_names( $import_names ) { return array_merge( $import_names, $this->supported_importers ); } /** * Plugin filter that supplies the UI for the importer * * @param string $stageoutput The output stage UI * @param string $import_name The name of the selected importer * @param string $stage The stage of the import in progress * @param string $step The step of the stage in progress * @return output for this stage of the import */ public function filter_import_stage( $stageoutput, $import_name, $stage, $step ) { // Only act on this filter if the import_name is one we handle... if ( !in_array( $import_name, $this->supported_importers ) ) { // Must return $stageoutput as it may contain the stage HTML of another importer return $stageoutput; } $inputs = array(); // Validate input from various stages... switch ( $stage ) { case 1: if ( count( $_POST ) ) { $inputs = $_POST->filter_keys( 'db_type', 'db_name', 'db_host', 'db_user', 'db_pass'); foreach ( $inputs as $key => $value ) { $$key = $value; } $connect_string = $this->get_connect_string( $db_type, $db_host, $db_name ); if ( $this->chryp_connect( $connect_string, $db_user, $db_pass ) ) { $stage = 2; } else { $inputs['warning']= _t( 'Could not connect to the database using the values supplied. Please correct them and try again.' ); } } break; } // Based on the stage of the import we're on, do different things... switch ( $stage ) { case 1: default: $output = $this->stage1( $inputs ); break; case 2: $output = $this->stage2( $inputs ); } return $output; } /** * Create the UI for stage one of the import process * * @param array $inputs Inputs received via $_POST to the importer * @return string The UI for the first stage of the import process */ private function stage1( $inputs ) { $default_values = array( 'db_type' => self::TYPE_MYSQL, 'db_name' => '', 'db_host' => 'localhost', 'db_user' => '', 'db_pass' => '', 'warning' => '' ); $inputs = array_merge( $default_values, $inputs ); extract( $inputs ); if ( $warning != '' ) { $warning = "<p class=\"warning\">{$warning}</p>"; } $output = <<< IMPORT_STAGE1 <p>Habari will attempt to import from a Chyrp database.</p> {$warning} <p>Please provide the connection details the Chyrp database:</p> <div class="item clear"> <span class="pct25"><label for="db_type">Database Type</label></span> <span> <input type="radio" name="db_type" value="0" tab index="1" checked />MySQL <input type="radio" name="db_type" value="1" tab index="2" />SQLite </span> </div> <div class="item clear"> <span class="pct25"><label for="db_name">Database Name</label></span><span class="pct40"><input type="text" name="db_name" value="{$db_name}" tab index="4"></span> </div> <div class="item clear"> <span class="pct25"><label for="db_host">Database Host</label></span><span class="pct40"><input type="text" name="db_host" value="{$db_host}" tab index="5"></span> </div> <div class="item clear"> <span class="pct25"><label for="db_user">Database User</label></span><span class="pct40"><input type="text" name="db_user" value="{$db_user}" tab index="6"></span> </div> <div class="item clear"> <span class="pct25"><label for="db_pass">Database Password</label></span><span class="pct40"><input type="password" name="db_pass" value="{$db_<PASSWORD>}" tab index="7"></span> </div> <div class="clear"></div> <input type="hidden" name="stage" value="1"> </div> <div <div class="container transparent" <input type="submit" class="button" name="import" value="Import" /> </div> IMPORT_STAGE1; return $output; } /** * Create the UI for stage two of the import process * This stage kicks off the ajax import. * * @param array $inputs Inputs received via $_POST to the importer * @return string The UI for the second stage of the import process */ private function stage2( $inputs ) { $inputs = $inputs->filter_keys( 'db_type', 'db_name', 'db_host', 'db_user', 'db_pass'); foreach ( $inputs as $key => $value ) { $$key = $value; } $ajax_url = URL::get( 'auth_ajax', array( 'context' => 'chyrp_import_users' ) ); EventLog::log( sprintf( _t('Starting import from "%s"'), $db_name ) ); Options::set( 'import_errors', array() ); $vars = Utils::addslashes( array( 'host' => $db_host, 'name' => $db_name, 'user' => $db_user, 'pass' => $inputs['db_pass'] ) ); $output = <<< IMPORT_STAGE2 <p>Import In Progress</p> <div id="import_progress">Starting Import...</div> <script type="text/javascript"> // A lot of ajax stuff goes here. $( document ).ready( function() { $( '#import_progress' ).load( "{$ajax_url}", { db_type: "{$db_type}", db_host: "{$vars['host']}", db_name: "{$vars['name']}", db_user: "{$vars['user']}", db_pass: "{$vars['<PASSWORD>']}", userindex: 0 } ); } ); </script> IMPORT_STAGE2; return $output; } /** * Attempt to connect to the Chyrp database * * @param string $connect_string The connection string of the Habari database * @param string $db_user The user of the database * @param string $db_pass The <PASSWORD> for the database * @return mixed false on failure, DatabseConnection on success */ private function chryp_connect( $connect_string, $db_user, $db_pass ) { // Connect to the database or return false try { $db = DatabaseConnection::ConnectionFactory( $connect_string );; $db->connect( $connect_string, $db_user, $db_pass ); return $db; } catch( Exception $e ) { return false; } } private function get_connect_string( $db_type, $db_host, $db_name ) { switch ( $db_type ) { case self::TYPE_MYSQL: $connect_string = "mysql:host={$db_host};dbname={$db_name}"; break; case self::TYPE_SQLITE: $connect_string = "sqlite:{$db_name}"; break; } return $connect_string; } /** * The plugin sink for the auth_ajax_chyrp_import_posts hook. * Responds via authenticated ajax to requests for post importing. * * @param mixed $handler * @return */ public function action_auth_ajax_chyrp_import_users( $handler ) { $inputs = $_POST->filter_keys( 'db_type', 'db_name', 'db_host', 'db_user', 'db_pass', 'userindex' ); foreach ( $inputs as $key => $value ) { $$key = $value; } $connect_string = $this->get_connect_string( $db_type, $db_host, $db_name ); $db = $this->chryp_connect( $connect_string, $db_user, $db_pass ); if ( $db ) { DB::begin_transaction(); $new_users = $db->get_results( " SELECT login as username, password, email, users.id as old_id FROM users INNER JOIN posts ON posts.user_id = users.id GROUP BY users.id ", array(), 'User' ); $usercount = 0; _e('<p>Importing users...</p>'); foreach ( $new_users as $user ) { $habari_user = User::get_by_name($user->username); // If username exists if ( $habari_user instanceof User ) { $habari_user->info->old_id = $user->old_id; $habari_user->update(); } else { try { $user->info->old_id = $user->old_id; // This should probably remain commented until we implement ACL more, // or any imported user will be able to log in and edit stuff //$user->password = <PASSWORD>}' . $user->password; $user->exclude_fields( array( 'old_id' ) ); $user->insert(); $usercount++; } catch( Exception $e ) { EventLog::log($e->getMessage(), 'err', null, null, print_r(array($user, $e), 1)); Session::error( $e->getMessage() ); $errors = Options::get('import_errors'); $errors[] = $user->username . ' : ' . $e->getMessage(); Options::set('import_errors', $errors); } } } if ( DB::in_transaction() ) { DB::commit(); } $ajax_url = URL::get( 'auth_ajax', array( 'context' => 'chyrp_import_posts' ) ); $vars = Utils::addslashes( array( 'type' => $db_type, 'host' => $db_host, 'name' => $db_name, 'user' => $db_user, 'pass' => $db_pass ) ); echo <<< IMPORT_POSTS <script type="text/javascript"> // A lot of ajax stuff goes here. $( document ).ready( function(){ $( '#import_progress' ).load( "{$ajax_url}", { db_type: "{$db_type}", db_host: "{$vars['host']}", db_name: "{$vars['name']}", db_user: "{$vars['user']}", db_pass: "{$vars['pass']}", postindex: 0 } ); } ); </script> IMPORT_POSTS; } else { EventLog::log(sprintf(_t('Failed to import from "%s"'), $db_name), 'crit'); Session::error( $e->getMessage() ); echo '<p>'._t( 'Failed to connect using the given database connection details.' ).'</p>'; } } /** * The plugin sink for the auth_ajax_chyrp_import_posts hook. * Responds via authenticated ajax to requests for post importing. * * @param AjaxHandler $handler The handler that handled the request, contains $_POST info */ public function action_auth_ajax_chyrp_import_posts( $handler ) { $inputs = $_POST->filter_keys( 'db_type', 'db_name', 'db_host', 'db_user', 'db_pass', 'postindex' ); foreach ( $inputs as $key => $value ) { $$key = $value; } $connect_string = $this->get_connect_string( $db_type, $db_host, $db_name ); $db = $this->chryp_connect( $connect_string, $db_user, $db_pass ); if ( $db ) { DB::begin_transaction(); $postcount = $db->get_value( "SELECT count(id) FROM posts;" ); $min = $postindex * IMPORT_BATCH + ( $postindex == 0 ? 0 : 1 ); $max = min( ( $postindex + 1 ) * IMPORT_BATCH, $postcount ); // old_id was set when we imported the users $user_map = array(); $user_info = DB::get_results( "SELECT user_id, value FROM {userinfo} WHERE name='old_id';" ); foreach ( $user_info as $info ) { $user_map[$info->value] = $info->user_id; } // Posts // id INTEGER PRIMARY KEY AUTOINCREMENT, // feather VARCHAR(32) DEFAULT '', // clean VARCHAR(128) DEFAULT '', // url VARCHAR(128) DEFAULT '', // pinned BOOLEAN DEFAULT FALSE, // status VARCHAR(32) DEFAULT 'public', // user_id INTEGER DEFAULT 0, // created_at DATETIME DEFAULT NULL, // updated_at DATETIME DEFAULT NULL // // Post attributes // post_id INTEGER NOT NULL , // name VARCHAR(100) DEFAULT '', // value LONGTEXT, echo "<p>Importing posts {$min}-{$max} of {$postcount}.</p>"; $posts = $db->get_results( " SELECT attr_body.value as content, id, attr_title.value as title, user_id, created_at as pubdate, updated_at as updated, updated_at as modified, status FROM posts INNER JOIN post_attributes attr_title ON posts.id = attr_title.post_id AND attr_title.name = 'title' INNER JOIN post_attributes attr_body ON posts.id = attr_body.post_id AND attr_body.name = 'body' ORDER BY id DESC LIMIT {$min}, " . IMPORT_BATCH , array(), 'Post' ); $post_map = DB::get_column( "SELECT value FROM {postinfo} WHERE name='old_id';"); foreach ( $posts as $post ) { if ( in_array($post->id, $post_map) ) { continue; } $post_array = $post->to_array(); $post_array['content_type']= Post::type( 'entry' ); $p = new Post( $post_array ); $p->slug = $post->slug; if ( isset($user_map[$p->user_id]) ) { $p->user_id = $user_map[$p->user_id]; } else { $errors = Options::get('import_errors'); $errors[] = _t('Post author id %s was not found in the external database, assigning post "%s" (external post id #%d) to current user.', array($p->user_id, $p->title,$post_array['id']) ); Options::set('import_errors', $errors); $p->user_id = User::identify()->id; } $p->guid = $p->guid; // Looks fishy, but actually causes the guid to be set. $p->info->old_id = $post_array['id']; // Store the old post id in the post_info table for later try { $p->insert(); $p->updated = $post_array['updated']; $p->update(); } catch( Exception $e ) { EventLog::log($e->getMessage(), 'err', null, null, print_r(array($p, $e), 1)); Session::error( $e->getMessage() ); $errors = Options::get('import_errors'); $errors[] = $p->title . ' : ' . $e->getMessage(); Options::set('import_errors', $errors); } } if ( DB::in_transaction() ) { DB::commit(); } if ( $max < $postcount ) { $ajax_url = URL::get( 'auth_ajax', array( 'context' => 'chyrp_import_posts' ) ); $postindex++; $vars = Utils::addslashes( array( 'host' => $db_host, 'name' => $db_name, 'user' => $db_user, 'pass' => $db_pass ) ); echo <<< IMPORT_POSTS <script type="text/javascript"> $( '#import_progress' ).load( "{$ajax_url}", { db_type: "{$db_type}", db_host: "{$vars['host']}", db_name: "{$vars['name']}", db_user: "{$vars['user']}", db_pass: "{$vars['pass']}", postindex: {$postindex} } ); </script> IMPORT_POSTS; } else { EventLog::log('Import complete from "'. $db_name .'"'); echo '<p>' . _t( 'Import is complete.' ) . '</p>'; $errors = Options::get('import_errors'); if(count($errors) > 0 ) { echo '<p>' . _t( 'There were errors during import:' ) . '</p>'; echo '<ul>'; foreach($errors as $error) { echo '<li>' . $error . '</li>'; } echo '</ul>'; } } } else { EventLog::log(sprintf(_t('Failed to import from "%s"'), $db_name), 'crit'); Session::error( $e->getMessage() ); echo '<p>'._t( 'The database connection details have failed to connect.' ).'</p>'; } } } ?> <file_sep><?php $theme->display( 'header'); ?> <!-- to match charcoal theme --> </div></div> <div id="map" style="height: 500px;"></div> <!-- to match charcoal theme --> </div> <script type="text/javascript"> $(function(){ // Get the current viewport width and set the map canvas to be the full width var width = $(window).width(); $('#map').width( width ); map = null; infowindow = new google.maps.InfoWindow( ); <?php echo $theme->js_defaults; ?> map = new google.maps.Map(document.getElementById("map"), defaults); <?php foreach ( $theme->posts as $post ) { if ( $post->info->geolocation_enabled == 1 ) { ?> new_marker( new google.maps.LatLng(<?php echo $post->info->geolocation_coords; ?>), '<div><b><?php echo $post->title; ?></b></div><div><?php echo $post->content_excerpt; ?></div><div><a href="<?php echo $post->permalink; ?>">More...</a></div>' ); <?php } } ?> }); function new_marker( coords, message ) { var marker = new google.maps.Marker( { position: coords, map: map }); infowindow.setSize( new google.maps.Size(400,200) ); google.maps.event.addListener( marker, 'click', function(){ infowindow.close(); infowindow.setContent( message ); infowindow.open( map, marker ); }); } </script> <!-- to match charcoal theme --> <div id="page-bottom"><div id="wrapper-bottom"><div id="bottom-primary"> <?php $theme->display( 'footer'); ?><file_sep><?php class ExtendedLog extends Plugin { function action_admin_header() { $url = URL::get('auth_ajax', 'context=extendedlog'); $script = <<< SCRIPT var initi = itemManage.initItems; itemManage.initItems = function(){ initi(); $('.item .less').unbind('click').click(function(){ $('.extendedlog').remove(); $(this).parents('.item').after('<div class="extendedlog"><textarea readonly>Loading...</textarea></div>'); $('.extendedlog textarea').resizeable(); $.post( '{$url}', { log_id: $('.checkbox input', $(this).parents('.item')).attr('id').match(/\[([0-9]+)\]/)[1] }, function(result){ $('.extendedlog textarea').val(result) } ); }); } SCRIPT; Stack::add('admin_header_javascript', $script, 'extendedlog', array('jquery', 'admin')); } function action_auth_ajax_extendedlog($handler) { $log = EventLog::get(array('fetch_fn' => 'get_row', 'id' => $handler->handler_vars['log_id'], 'return_data' => true)); echo $log->data; } } ?><file_sep><?php /** * Geo Location Mashup plugin for Habari * * Adds a Google Maps mashup consisting of geolocation enabled content. * * This is a work in progress, so expect this to be broken a lot. * @todo filters on content_type to display * @todo custom markers based on content_type * * @author <NAME> **/ class GeoLocations_Mashup extends Plugin { private $config = array(); private $class_name; private $arrMapTypeId = array( 'ROADMAP' => 'Road Map', 'HYBRID' => 'Hybrid Map', 'SATELLITE' => 'Satellite Map', 'TERRAIN' => 'Terrain Map' ); private $arrMapControlType = array( 'DROPDOWN_MENU' => 'Dropdown Menu', 'HORIZONTAL_BAR' => 'Horizontal Bar', 'DEFAULT' => 'Default Style' ); private $arrMapNavControlStyle = array( 'SMALL' => 'Small, Zoom Only', 'ANDROID' => 'Android look alike', 'DEFAULT' => 'Default style', 'ZOOM_PAN' => 'Zoom and Pan' ); /** * default_options() * * Set the default options for the plugin **/ private static function default_options() { return array ( 'mapurl' => 'map', 'coords' => '43.05183,-87.913971', 'zoom' => '10', 'jumptoZoom' => '15', 'mapTypeId' => 'ROADMAP', 'mapControlType' => 'DROPDOWN_MENU', 'mapNavControl' => true, 'mapNavControlStyle' => 'SMALL' ); } /** * Add update beacon support. **/ public function action_update_check() { Update::add( 'GeoLocation Mashup', 'e868d76c-aced-4620-ac7f-bb7b24dbd952', $this->info->version ); } /** * On plugin activation, set the default options **/ public function action_plugin_activation( $file ) { if ( realpath( $file ) === __FILE__ ) { $this->class_name = strtolower( get_class( $this ) ); foreach ( self::default_options() as $name => $value ) { $current_value = Options::get( $this->class_name . '__' . $name ); if ( is_null( $current_value ) ) { Options::set( $this->class_name . '__' . $name, $value ); } } } } /** * On plugin init **/ public function action_init() { $this->class_name = strtolower( get_class( $this ) ); foreach ( self::default_options() as $name => $value ) { $this->config[$name] = Options::get( $this->class_name . '__' . $name ); } $this->add_template( 'page.map', dirname(__FILE__) . '/page.map.php' ); $this->add_rule( '"' . $this->config['mapurl'] . '"', 'geolocation_mashup' ); } /** * Respond to the user selecting configure on the plugin page **/ public function configure() { $ui = new FormUI( $this->class_name ); $ui->append( 'text', 'mapurl', 'option:' . $this->class_name . '__mapurl', _t( 'Map URL' ) ); $ui->mapurl->add_validator('validate_required'); $ui->append( 'text', 'coords', 'option:' . $this->class_name . '__coords', _t( 'Default Coordinates', $this->class_name ) ); $ui->append( 'text', 'zoom', 'option:' . $this->class_name . '__zoom', _t( 'Default Zoom', $this->class_name ) ); $ui->append( 'text', 'jumptoZoom', 'option:' . $this->class_name . '__jumptoZoom', _t( 'Jump to Zoom', $this->class_name ) ); $ui->append( 'select', 'mapTypeId', 'option:' . $this->class_name . '__mapTypeId', _t( 'Map Type' ), 'optionscontrol_select' ); $ui->mapTypeId->options = $this->arrMapTypeId; $ui->append( 'select', 'mapControlType', 'option:' . $this->class_name . '__mapControlType', _t( 'Map Control Type' ) ); $ui->mapControlType->options = $this->arrMapControlType; $ui->append( 'checkbox', 'mapNavControl', 'option:' . $this->class_name . '__mapNavControl', _t( 'Show Navigation Controls?' ) ); $ui->append( 'select', 'mapNavControlStyle', 'option:' . $this->class_name . '__mapNavControlStyle', _t( 'Navigation Control Style' ) ); $ui->mapNavControlStyle->options = $this->arrMapNavControlStyle; $ui->append( 'submit', 'save', _t( 'Save', $this->class_name ) ); $ui->set_option( 'success_message', _t( 'Options saved', $this->class_name ) ); return $ui; } /** * On action geolocation_mashup **/ public function action_plugin_act_geolocation_mashup( $handler ) { // Load Google Maps API Stack::add('template_header_javascript', 'http://maps.google.com/maps/api/js?sensor=false', 'googlemaps_api_v3' ); // Load up jquery Stack::add('template_header_javascript', 'http://localhost/habari/scripts/jquery.js', 'jquery' ); // Now create our page ready javascript $coords = preg_split( '/,/', $this->config['coords'] ); $js_defaults = sprintf( "defaults = { lat: %s, long: %s, center: %s, zoom: %s, jumptoZoom: %s, mapTypeControlOptions: %s, mapTypeId: %s, navigationControl: %s, navigationControlOptions: %s };", $coords[0], $coords[1], 'new google.maps.LatLng( ' . $coords[0] . ', ' . $coords[1] . ' )', $this->config['zoom'], $this->config['jumptoZoom'], '{ style: google.maps.MapTypeControlStyle.' . $this->config['mapControlType'] . ' }', 'google.maps.MapTypeId.' . $this->config['mapTypeId'], ( $this->config['mapNavControl'] ) ? 'true' : 'false', '{ style: google.maps.NavigationControlStyle.' . $this->config['mapNavControlStyle'] . '}' ); // Load defaults after google api //Stack::add('template_header_javascript', $js_defaults, 'geolocation_defaults', array( 'jquery', 'googlemaps_api_v3' ) ); // Makes sure home displays only entries - for now... $default_filters = array( 'content_type' => Post::type( 'entry' ), ); $posts = Posts::get( $default_filters ); $handler->theme->posts = $posts; $handler->theme->js_defaults = $js_defaults; $handler->theme->display( 'page.map' ); } } ?><file_sep><?php /* * Blogroll Plugin * Usage: <?php $theme->show_blogroll(); ?> * A sample blogroll.php template is included with the plugin. This can be copied to your * active theme and modified to fit your preference. * * @todo Update wiki docs, and inline code docs * @todo Fix css/layout, it's a bit "hacky hacky kluge" right now * @todo Create .pot file for translations */ require_once "blogs.php"; require_once "bloginfo.php"; require_once "blog.php"; require_once "blogrollopmlhandler.php"; class Blogroll extends Plugin { const VERSION= '0.5-beta'; const DB_VERSION= 003; public function info() { return array( 'name' => 'Blogroll', 'version' => self::VERSION, 'url' => 'http://wiki.habariproject.org/en/plugins/blogroll', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Displays a blogroll on your blog' ); } public function action_plugin_activation( $file ) { if ( $file == str_replace( '\\','/', $this->get_file() ) ) { DB::register_table( 'blogroll' ); DB::register_table( 'bloginfo' ); DB::register_table( 'tag2blog' ); if ( ! CronTab::get_cronjob( 'blogroll:update' ) ) { CronTab::add_hourly_cron( 'blogroll:update', 'blogroll_update_cron', 'Updates the blog updated timestamp from weblogs.com' ); } Options::set( 'blogroll__db_version', self::DB_VERSION ); Options::set( 'blogroll__use_updated', true ); Options::set( 'blogroll__max_links', '10' ); Options::set( 'blogroll__sort_by', 'id' ); Options::set( 'blogroll__direction', 'ASC' ); Options::set( 'blogroll__list_title', 'Blogroll' ); if ( $this->install_db_tables() ) { Session::notice( _t( 'Created the Blogroll database tables.', 'blogroll' ) ); } else { Session::error( _t( 'Could not install Blogroll database tables.', 'blogroll' ) ); } } } public function action_plugin_deactivation( $file ) { if ( $file == str_replace( '\\','/', $this->get_file() ) ) { CronTab::delete_cronjob( 'blogroll:update' ); // should we remove the tables here? } } public function install_db_tables() { switch ( DB::get_driver_name() ) { case 'mysql': $schema= "CREATE TABLE " . DB::table('blogroll') . " ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, url VARCHAR(255) NOT NULL, feed VARCHAR(255) NOT NULL, owner VARCHAR(255) NOT NULL, updated VARCHAR(12) NOT NULL, rel VARCHAR(255) NOT NULL, description TEXT, UNIQUE KEY id (id) ); CREATE TABLE " . DB::table('bloginfo') . " ( blog_id INT UNSIGNED NOT NULL, name VARCHAR(255) NOT NULL, type SMALLINT UNSIGNED NOT NULL DEFAULT 0, value TEXT, PRIMARY KEY (blog_id,name) ); CREATE TABLE " . DB::table('tag2blog') . " ( tag_id INT UNSIGNED NOT NULL, blog_id INT UNSIGNED NOT NULL, PRIMARY KEY (tag_id,blog_id), KEY blog_id (blog_id) );"; break; case 'sqlite': $schema= "CREATE TABLE " . DB::table('blogroll') . " ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR(255) NOT NULL, url VARCHAR(255) NOT NULL, feed VARCHAR(255) NOT NULL, owner VARCHAR(255) NOT NULL, updated VARCHAR(12) NOT NULL, rel VARCHAR(255) NOT NULL, description TEXT ); CREATE TABLE " . DB::table('bloginfo') . " ( blog_id INTEGER UNSIGNED NOT NULL, name VARCHAR(255) NOT NULL, type SMALLINT UNSIGNED NOT NULL DEFAULT 0, value TEXT, PRIMARY KEY (blog_id, name) ); CREATE TABLE " . DB::table('tag2blog') . " ( tag_id INTEGER UNSIGNED NOT NULL, blog_id INTEGER UNSIGNED NOT NULL, PRIMARY KEY (tag_id, blog_id) ); CREATE INDEX IF NOT EXISTS tag2blog_blog_id ON " . DB::table('tag2blog') . "(blog_id);"; break; } return DB::dbdelta( $schema ); } public function action_update_check() { Update::add( 'blogroll', '0420cf10-db83-11dc-95ff-0800200c9a66', $this->info->version ); } public function action_init() { DB::register_table( 'blogroll' ); DB::register_table( 'bloginfo' ); DB::register_table( 'tag2blog' ); if ( Options::get( 'blogroll__db_version' ) && self::DB_VERSION > Options::get( 'blogroll__db_version' ) ) { $this->install_db_tables(); EventLog::log( 'Updated Blogroll.' ); Options::set( 'blogroll__db_version', self::DB_VERSION ); } } public function filter_plugin_config( $actions, $plugin_id ) { if ( $this->plugin_id() == $plugin_id ){ $actions[]= _t( 'Configure', 'blogroll' ); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $this->plugin_id() == $plugin_id ) { switch ( $action ) { case _t( 'Configure', 'blogroll' ): $form= new FormUI( 'blogroll' ); $title= $form->append( 'text', 'list_title', 'option:blogroll__list_title', _t( 'List title: ', 'blogroll' ) ); $max= $form->append( 'text', 'max_links', 'option:blogroll__max_links', _t( 'Max. displayed links: ', 'blogroll') ); $sort_bys= array_merge( array_combine( array_keys( Blog::default_fields() ), array_map( 'ucwords', array_keys( Blog::default_fields() ) ) ), array( 'random' => _t('Randomly', 'blogroll') ) ); $sortby= $form->append( 'select', 'sort_by', 'option:blogroll__sort_by', _t( 'Sort By: ', 'blogroll'), $sort_bys ); $orders= array( 'ASC' => _t('Ascending' ,'blogroll'), 'DESC' => _t('Descending' ,'blogroll') ); $order= $form->append( 'select', 'direction', 'option:blogroll__direction', _t( 'Order: ', 'blogroll'), $orders ); $update= $form->append( 'checkbox', 'use_update', 'option:blogroll__use_update', _t( 'Use Weblogs.com to get updates? ', 'blogroll') ); $form->append( 'submit', 'save', 'Save' ); $form->out(); break; } } } public function filter_adminhandler_post_loadplugins_main_menu( $menus ) { $menus['blogroll_manage'] = array( 'url' => URL::get( 'admin', 'page=blogroll_manage'), 'title' => _t('Manage Blogroll'), 'text' => _t('Manage Blogroll'), 'selected' => false, 'hotkey' => 'B' ); $menus['blogroll_publish'] = array( 'url' => URL::get( 'admin', 'page=blogroll_publish'), 'title' => _t('Publish Blogroll'), 'text' => _t('Publish Blogroll'), 'selected' => false ); return $menus; } public function action_admin_theme_post_blogroll_manage( $handler, $theme ) { extract( $handler->handler_vars ); if ( isset( $change ) && isset( $blog_ids ) ) { $count= count( $blog_ids ); $blog_ids= (array) $blog_ids; switch ( $change ) { case 'delete': foreach ( $blog_ids as $blog_id ) { $blog= Blog::get( $blog_id ); $blog->delete(); } Session::notice( sprintf( _n('Deleted %d blog', 'Deleted %d blogs', $count, 'blogroll'), $count ) ); break; case 'auto_update': foreach ( $blog_ids as $blog_id ) { $blog= Blog::get( $blog_id ); if ( $info= Blogs::get_info_from_url( $blog->feed?$blog->feed:$blog->url ) ) { foreach ( $info as $key => $value ) { $value= trim( $value ); if ( $value ) { $blog->$key= $value; } } $blog->update(); } else { Session::error( sprintf( _t('Could not fetch info for %s', 'blogroll'), $blog->name ) ); $count--; } } Session::notice( sprintf( _n('Automatically updated %d blog', 'Automatically updated %d blogs', $count, 'blogroll'), $count ) ); break; } } elseif ( !empty( $opml_file ) || ( isset( $_FILES['userfile'] ) && is_uploaded_file( $_FILES['userfile']['tmp_name'] ) ) ) { $file= !empty( $opml_file ) ? RemoteRequest::get_contents( $opml_file ) : file_get_contents( $_FILES['userfile']['tmp_name'] ); try { $xml= new SimpleXMLElement( $file ); $count= $this->import_opml( $xml->body ); Session::notice( sprintf( _n('Imported %d blog from %s', 'Imported %d blogs from %s', $count, 'blogroll'), $count, (string) $xml->head->title ) ); } catch ( Exception $e ) { Session::error( _t('Sorry, could not parse that OPML file. It may be malformed.', 'blogroll') ); } } Utils::redirect( URL::get( 'admin', 'page=blogroll_manage' ) ); exit; } public function action_admin_theme_post_blogroll_publish( $handler, $theme ) { $params= array_intersect_key( $handler->handler_vars, array_flip( array('name', 'url', 'feed', 'description', 'owner', 'tags') ) ); extract( $handler->handler_vars ); if ( !empty( $quick_link ) ) { $link= $quick_link; if ( strpos( $quick_link, 'http://' ) !== 0 ) { $quick_link= 'http://' . $quick_link; } if ( $info= Blogs::get_info_from_url( $quick_link ) ) { $params= array_merge( $params, $info ); } else { $_POST['url']= $quick_link; $_POST['feed']= $quick_link; Session::add_to_set( 'last_form_data', $_POST, 'get' ); Session::error( sprintf( _t('Could not fetch info from %s. Please enter the information manually.', 'blogroll'), $quick_link ) ); Utils::redirect( URL::get( 'admin', 'page=blogroll_publish' ) ); exit; } } if ( ( empty( $params['name'] ) || empty( $params['url'] ) ) ) { Session::error( _t('Blog Name and URL are required feilds.', 'blogroll') ); Session::add_to_set( 'last_form_data', $_POST, 'get' ); } else { if ( !empty( $id ) ) { $blog= Blog::get( $id ); foreach ( $params as $key => $value ) { $blog->$key= $value; } $blog->update(); Session::notice( sprintf( _t('Updated blog %s', 'blogroll'), $blog->name ) ); Session::add_to_set( 'last_form_data', array_merge( $_POST, $params ), 'get' ); } elseif ( $params ) { $blog= new Blog( $params ); if ( $blog->insert() ) { Session::notice( sprintf( _t('Successfully added blog %s', 'blogroll'), $blog->name ) ); $_POST['id']= $blog->id; } else { Session::notice( sprintf( _t( 'Could not add blog %s', 'blogroll'), $blog->name ) ); } Session::add_to_set( 'last_form_data', $_POST, 'get' ); } } if ( !empty( $quick_link ) && !empty( $redirect_to ) ) { $msg= sprintf( _t('Successfully added blog %s. Now going back.', 'blogroll'), htmlspecialchars( $blog->name ) ); echo "<html><head></head><body onload=\"alert('$msg');location.href='$redirect_to';\">"; Session::messages_out(); echo "</body></html>"; exit; } Utils::redirect( URL::get( 'admin', 'page=blogroll_publish' ) ); exit; } public function action_admin_theme_get_blogroll_manage( $handler, $theme ) { Stack::add( 'admin_stylesheet', array( $this->get_url() . '/templates/blogroll.css', 'screen' ) ); $theme->feed_icon= $this->get_url() . '/templates/feed.png'; $theme->display( 'blogroll_manage' ); exit; } public function action_admin_theme_get_blogroll_publish( $handler, $theme ) { Stack::add( 'admin_stylesheet', array( $this->get_url() . '/templates/blogroll.css', 'screen' ) ); extract( $handler->handler_vars ); if ( !empty( $quick_link_bookmarklet ) ) { Session::add_to_set( 'last_form_data', array('quick_link'=>$quick_link_bookmarklet, 'redirect_to'=>$quick_link_bookmarklet), 'post' ); Utils::redirect( URL::get( 'admin', 'page=blogroll_publish' ) ); exit; } if ( !empty( $id ) ) { $blog= Blog::get( $id ); $theme->tags= htmlspecialchars( Utils::implode_quoted( ',', $blog->tags ) ); } else { $blog= new Blog; $theme->tags= ''; } foreach ( $blog->to_array() as $key => $value ) { $theme->$key= $value; } $theme->relationships= Plugins::filter( 'blogroll_relationships', array('external'=>'External', 'nofollow'=>'Nofollow', 'bookmark'=>'Bookmark') ); $controls= array( 'Extras' => $theme->fetch( 'blogroll_publish_extras' ), 'Tags' => $theme->fetch( 'publish_tags' ), ); $theme->controls= Plugins::filter( 'blogroll_controls', $controls, $blog ); $theme->display( 'blogroll_publish' ); exit; } public function filter_available_templates( $templates, $class ) { $templates= array_merge( $templates, array('blogroll_manage','blogroll_publish','blogroll','blogroll_publish_extras') ); return $templates; } public function filter_include_template_file( $template_path, $template_name, $class ) { if ( ! file_exists( $template_path ) ) { switch ( $template_name ) { case 'blogroll_manage': return dirname( __FILE__ ) . '/templates/blogroll_manage.php'; case 'blogroll_publish_extras': return dirname( __FILE__ ) . '/templates/blogroll_publish_extras.php'; case 'blogroll_publish': return dirname( __FILE__ ) . '/templates/blogroll_publish.php'; case 'blogroll': return dirname( __FILE__ ) . '/templates/blogroll.php'; } } return $template_path; } public function theme_show_blogroll( $theme, $user_params= array() ) { $theme->blogroll_title= Options::get( 'blogroll__list_title' ); // Build the params array to pass it to the get() method $order_by= Options::get( 'blogroll__sort_by' ); $direction= Options::get( 'blogroll__direction'); $params= array( 'limit' => Options::get( 'blogroll__max_links' ), 'order_by' => $order_by . ' ' . $direction, ); $theme->blogs= Blogs::get( $params ); return $theme->fetch( 'blogroll' ); } public function filter_blogroll_update_cron( $success ) { if ( Options::get( 'blogroll__use_updated' ) ) { $request= new RemoteRequest( 'http://www.weblogs.com/rssUpdates/changes.xml', 'GET' ); $request->add_header( array( 'If-Modified-Since', Options::get('blogroll__last_update') ) ); if ( $request->execute() ) { try { $xml= new SimpleXMLElement( $request->get_response_body() ); } catch ( Exception $e ) { // log the failure here! } $atts= $xml->attributes(); $updated= strtotime( (string) $atts['updated'] ); foreach ( $xml->weblog as $weblog ) { $atts= $weblog->attributes(); $match= array(); $match['url']= (string) $atts['url']; $match['feed']= (string) $atts['rssUrl']; $update= $updated - (int) $atts['when']; if ( DB::exists( DB::table( 'blogroll' ), $match ) ) { DB::update( DB::table( 'blogroll' ), array( 'updated' => $update ), $match ); } } Options::set( 'blogroll__last_update', gmdate( 'D, d M Y G:i:s e' ) ); } return true; } else { return false; } } public function filter_habminbar( $menu ) { $menu['blogroll']= array( 'Blogroll', URL::get( 'admin', 'page=blogroll_publish' ) ); return $menu; } public function filter_rewrite_rules( $rules ) { $rules[] = new RewriteRule(array( 'name' => 'blogroll_opml', 'parse_regex' => '/^blogroll\/opml\/?$/i', 'build_str' => 'blogroll/opml', 'handler' => 'BlogrollOPMLHandler', 'action' => 'blogroll_opml', 'priority' => 2, 'rule_class' => RewriteRule::RULE_PLUGIN, 'is_active' => 1, 'description' => 'Rewrite for Blogroll OPML feed.' )); return $rules; } private function import_opml( SimpleXMLElement $xml ) { $count= 0; foreach ( $xml->outline as $outline ) { $atts= (array) $outline->attributes(); $params= $this->map_opml_atts( $atts['@attributes'] ); if ( isset( $params['url'] ) && isset( $params['name'] ) ) { $blog= new Blog( $params ); $blog->insert(); $count++; } if ( $outline->children() ) { $count+= $this->import_opml( $outline ); } } return $count; } private function map_opml_atts( $atts ) { $atts= array_map( 'strval', $atts ); $valid_atts= array_intersect_key( $atts, array_flip( array('name', 'url', 'feed', 'description', 'owner', 'updated') ) ); foreach ( $atts as $key => $val ) { switch ( $key ) { case 'htmlUrl': $valid_atts['url']= $atts['htmlUrl']; break; case 'xmlUrl': $valid_atts['feed']= $atts['xmlUrl']; break; case 'text': $valid_atts['name']= $atts['text']; break; } } return $valid_atts; } } ?> <file_sep><!-- header --> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr"> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title><?php $theme->title(); ?></title> <link rel="alternate" type="application/atom+xml" title="Atom 1.0" href="<?php $theme->feed_alternate(); ?>" /> <link rel="edit" type="application/atom+xml" title="Atom Publishing Protocol" href="<?php URL::out('atompub_servicedocument'); ?>" /> <link rel="EditURI" type="application/rsd+xml" title="RSD" href="<?php URL::out('rsd'); ?>" /> <link rel="stylesheet" type="text/css" media="screen" href="<?php Site::out_url('theme'); ?>/style.css" /> <?php $theme->header(); ?> </head> <body<?php $theme->body_class(); ?>> <div id="container"> <div id="header"> <ul id="nav"> <li id="site-name"> <a href="<?php Site::out_url('habari'); ?>"><?php Options::out('title'); ?> &raquo;</a> <ul> <?php foreach ($pages as $tab) { // Menu tabs ?> <li class="<?php echo 'nav-' , $tab->slug; ?>"><a href="<?php echo $tab->permalink; ?>" title="<?php echo $tab->title; ?>"><?php echo $tab->title; ?></a></li> <?php } ?> </ul> </li> </ul> </div> <hr /> <!-- /header --> <file_sep><?php /** * ResurrectionTheme is a custom Theme class for teh Resurrection theme * * @package Habari */ // We must tell Habari to use ResurrectionTheme as the custom theme class: define( 'THEME_CLASS', 'Contrast' ); /** * A custom theme for Resurrection output */ class Contrast extends Theme { } ?><file_sep><?php $theme->display('header'); ?> <form name="create-content" id="create-content" method="post" action="<?php URL::out( 'admin', 'page=publish' ); ?>"> <div class="publish"> <div class="container"> <?php if(Session::has_messages()) {Session::messages_out();} ?> </div> <div class="container"> <p>Users and developers hang out here. Ask a question or just say 'hi'.</p> <iframe id="irc" scrolling="no" frameborder="0" src="http://embed.mibbit.com/?server=irc.freenode.net&channel=%23habari&nick=<?php echo $nick; ?>&noServerNotices=true&noServerMotd=true"> </iframe> <p>type /nick to change your nickname, or /help for available commands</p> </div> </div> </form> <?php $theme->display('footer'); ?> <file_sep><?php if(count($posts) > 0): ?> <ol> <?php foreach($posts as $post): ?> <li> <a href="<?php echo $post->permalink; ?>" title="<?php echo $post->title; ?> was published on <?php $post->pubdate->out('F j, Y'); ?>"> <?php echo $post->title; ?> </a> </li> <?php endforeach; ?> </ol> <?php else: ?> <p class="nothing">No posts could be found matching that query.</p> <?php endif; ?><file_sep><?php /** * DeMorganTheme is a custom Theme class. * * @package Habari */ // We must tell Habari to use DeMorganTheme as the custom theme class: define('THEME_CLASS', 'DeMorganTheme'); /** * A custom theme for DeMorgan output */ class DeMorganTheme extends Theme { private $handler_vars = array(); /** * Execute on theme init to apply these filters to output */ public function action_init_theme() { if (!Plugins::is_loaded('HabariMarkdown')) { // Apply Format::autop() to post content... Format::apply('autop', 'post_content_out'); } // Truncate content excerpt at "<!--more-->"... Format::apply_with_hook_params('more', 'post_content_out'); // Apply Format::autop() to comment content... Format::apply('autop', 'comment_content_out'); // Apply Format::tag_and_list() to post tags... Format::apply('tag_and_list', 'post_tags_out'); $this->load_text_domain('demorgan'); } public function add_template_vars() { //Theme Options $this->assign('home_tab', 'Blog'); //Set to whatever you want your first tab text to be. if (!$this->assigned('pages')) { $this->assign('pages', Posts::get(array('content_type' => 'page', 'status' => Post::status('published'), 'nolimit' => 1))); } if (!$this->assigned('user')) { $this->assign('user', User::identify()); } if (!$this->assigned('recent_comments')) { $this->assign('recent_comments', Comments::get(array('limit'=>10, 'status'=>Comment::STATUS_APPROVED, 'type'=>Comment::COMMENT, 'orderby'=>'date DESC'))); } if (!$this->assigned('recent_entries')) { $this->assign('recent_entries', Posts::get(array('limit'=>10, 'content_type'=>1, 'status'=>2, 'orderby'=>'pubdate DESC'))); } parent::add_template_vars(); } public function filter_theme_call_header($return, $theme) { if ($this->request->display_search) { echo '<meta name="robots" content="noindex,nofollow">'; } elseif ($this->request->display_entries_by_date || $this->request->display_entries_by_tag) { echo '<meta name="robots" content="noindex,follow">'; } return $return; } /* public function filter_theme_call_footer($return, $theme) { var_dump($this); return $return; } */ public function filter_post_tags_class($tags) { if (!is_array($tags)) $tags = array($tags); return count($tags) > 0 ? 'tag-' . implode(' tag-', array_keys($tags)) : 'no-tags'; } public function theme_body_class($theme) { // Assigning <body> class(es) $body_class = array(); if ($this->request->display_home) { $body_class[] = 'home'; $body_class[] = 'multiple'; } else if ($this->request->display_entries) { $body_class[] = 'multiple'; } else if ($this->request->display_entries_by_date) { $body_class[] = 'date-archive'; $body_class[] = 'archive'; $body_class[] = 'multiple'; } else if ($this->request->display_entries_by_tag) { $body_class[] = 'tag-archive'; $body_class[] = 'archive'; $body_class[] = 'multiple'; } else if ($this->request->display_entry) { $body_class[] = 'entry-' . $this->posts->slug; $body_class[] = 'entry'; $body_class[] = 'single'; } else if ($this->request->display_page) { $body_class[] = 'page-' . $this->posts->slug; $body_class[] = 'page'; $body_class[] = 'single'; } else if ($this->request->display_post) { // Other content-types $post_type_name = Post::type_name($this->posts->content_type); $body_class[] = $post_type_name . '-' . $this->posts->slug; $body_class[] = $post_type_name; $body_class[] = 'single'; } else if ($this->request->display_search) { $body_class[] = 'search'; $body_class[] = 'multiple'; } else if ($this->request->display_404) { $body_class[] = 'four04'; } //Get unique items $body_class = array_flip(array_flip($body_class)); return count($body_class) > 0 ? ' class="' . implode(' ', $body_class) . '"' : ''; } public function theme_title($theme) { $title = ''; if (count($this->handler_vars) === 0) { $this->handler_vars = Controller::get_handler()->handler_vars; } if ($this->request->display_entries_by_date && count($this->handler_vars) > 0) { $date_string = ''; $date_string .= isset($this->handler_vars['year']) ? $this->handler_vars['year'] : '' ; $date_string .= isset($this->handler_vars['month']) ? '‒' . $this->handler_vars['month'] : '' ; $date_string .= isset($this->handler_vars['day']) ? '‒' . $this->handler_vars['day'] : '' ; $title = sprintf(_t('%1$s &raquo; Chronological Archives of %2$s', 'demorgan'), $date_string, Options::get('title')); } else if ($this->request->display_entries_by_tag && isset($this->handler_vars['tag'])) { $tag = (count($this->posts) > 0) ? $this->posts[0]->tags[$this->handler_vars['tag']] : $this->handler_vars['tag'] ; $title = sprintf(_t('%1$s &raquo; Taxonomic Archives of %2$s', 'demorgan'), htmlspecialchars($tag), Options::get('title')); } else if (($this->request->display_entry || $this->request->display_page) && isset($this->posts)) { $title = sprintf(_t('%1$s ¶ %2$s', 'demorgan'), strip_tags($this->posts->title_out), Options::get('title')); } else if ($this->request->display_search && isset($this->handler_vars['criteria'])) { $title = sprintf(_t('%1$s &raquo; Search Results of %2$s', 'demorgan'), htmlspecialchars($this->handler_vars['criteria']), Options::get('title')); } else { $title = Options::get('title'); } if ($this->page > 1) { $title = sprintf(_t('%1$s &rsaquo; Page %2$s', 'demorgan'), $title, $this->page); } return $title; } public function theme_mutiple_h1($theme) { $h1 = ''; if (count($this->handler_vars) === 0) { $this->handler_vars = Controller::get_handler()->handler_vars; } if ($this->request->display_entries_by_date && count($this->handler_vars) > 0) { $date_string = ''; $date_string .= isset($this->handler_vars['year']) ? $this->handler_vars['year'] : '' ; $date_string .= isset($this->handler_vars['month']) ? '‒' . $this->handler_vars['month'] : '' ; $date_string .= isset($this->handler_vars['day']) ? '‒' . $this->handler_vars['day'] : '' ; $h1 = '<h1>' . sprintf(_t('Posts written in %s', 'demorgan'), $date_string) . '</h1>'; } else if ($this->request->display_entries_by_tag && isset($this->handler_vars['tag'])) { $tag = (count($this->posts) > 0) ? $this->posts[0]->tags[$this->handler_vars['tag']] : $this->handler_vars['tag'] ; $h1 = '<h1>' . sprintf(_t('Posts tagged with %s', 'demorgan'), htmlspecialchars($tag)) . '</h1>'; } else if ($this->request->display_search && isset($this->handler_vars['criteria'])) { $h1 = '<h1>' . sprintf(_t('Search results for “%s”', 'demorgan'), htmlspecialchars($this->handler_vars['criteria'])) . '</h1>'; } return $h1; } } ?> <file_sep><?php /* * Recent Comments Plugin * Usage: <?php $theme->show_recentcomments(); ?> * A sample recentcomments.php template is included with the plugin. This can be copied to your * active theme and modified to fit your preference. */ Class RecentComments extends Plugin { /** * Provides Plugin information. **/ public function info() { return array( 'name'=>'Recent Comments', 'version'=>'1.3', 'url'=>'http://habariproject.org/', 'author'=>'Habari Community', 'authorurl'=>'http://habariproject.org/', 'license'=>'Apache License 2.0', 'description'=>'Displays the most recent comments in your blog sidebar' ); } /** * Implement the update notification feature */ public function action_update_check() { Update::add( 'RecentComments', '6d49a362-db63-11dc-95ff-0800200c9a66', $this->info->version ); } /** * Set default values for unset option * * @param unknown_type $file */ public function action_plugin_activation( $file ) { $default_options= array ( 'title' => 'Recent Comments', 'format' => '[[user]] on [[post]]', 'dateformat' => 'Mj n:ia', 'count' => '5' ); if ( Plugins::id_from_file( $file ) == Plugins::id_from_file( __FILE__ ) ) { foreach ( $default_options as $name => $value ) { $current_value= Options::get( 'recentcomments__' . $name ); if ( !isset( $current_value) ) Options::set( 'recentcomments__' . $name, $value ); } } } /** * Adds a Configure action to the plugin * * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The id of a plugin * @return array The array of actions */ public function filter_plugin_config( $actions, $plugin_id ) { if ( $this->plugin_id() == $plugin_id ){ $actions[]= 'Configure'; } return $actions; } /** * Creates a UI form to handle the plguin configurations * * @param string $plugin_id The id of a plugin * @param array $actions An array of actions that apply to this plugin */ public function action_plugin_ui( $plugin_id, $action ) { if ( $this->plugin_id()==$plugin_id && $action=='Configure' ) { $form= new FormUI( strtolower(get_class( $this ) ) ); $form->append( 'text', 'title', 'option:recentcomments__title', 'Title: ' ); $form->append( 'text','format', 'option:recentcomments__format','List item format (use [[user]], [[post]] and/or [[date]]): ' ); $form->format->add_validator( 'validate_required' ); $form->append( 'text','dateformat', 'option:recentcomments__dateformat','Date fomrat <i>(if [[date]] is used)</i>: ' ); $form->append( 'text','count', 'option:recentcomments__count','Number of comments to display:' ); $form->count->add_validator( 'validate_required' ); $form->append( 'submit', 'save', 'Save' ); $form->out(); } } /** * Compiles and formats the recent comments list * * @return string An HTML unorderd list of the recent comments */ public function theme_show_recentcomments( $theme ){ //Get the plugin options $limit= Options::get(strtolower(get_class($this)) . '__count' ); $format= Options::get( strtolower(get_class( $this ) ) . '__format' ); $dateformat=Options::get(strtolower(get_class($this)) . '__dateformat' ); $theme->recentcomments_title= Options::get(strtolower(get_class($this)) . '__title' ); //Assign default values if options not set if (empty($limit)) $limit='5'; if (empty($format)) $format='[[user]] on [[post]]'; if (empty($dateformat)) $dateformat='Mj n:ia'; $status=Comment::STATUS_APPROVED; $commentarray=array('limit'=>$limit, 'status'=>$status, 'type'=>Comment::COMMENT, 'orderby'=>'date DESC'); $comments=Comments::get($commentarray); $list= array(); foreach ($comments as $comment){ $name='<a href="'.$comment->url.'" rel="external">'.$comment->name.'</a>'; $post='<a href="'.$comment->post->permalink.'">'.$comment->post->title.'</a>'; $datearray=date_parse($comment->date); $date=date($dateformat,mktime($datearray['hour'],$datearray['minute'],0,$datearray['month'],$datearray['day'],$datearray['year'])); $list[]="<li>".str_replace('[[user]]',$name, str_replace('[[post]]',$post,str_replace('[[date]]',$date,$format)))."</li>\n"; } $theme->recentcomments_links= $list; return $theme->fetch( 'recentcomments' ); } public function action_init() { $this->add_template('recentcomments', dirname(__FILE__) . '/recentcomments.php'); } } ?><file_sep> <div id="ft"><?php $theme->area('footer'); ?></div> </div> <?php $theme->footer(); ?> </body> </html> <file_sep><?php if (count($tags) > 0) { echo '<ul id="breezy-taxonomy-archive">'; if ($show_tag_post_count) { foreach ($tags as $tag) { if ($tag->count > 0) { printf('<li class="tag"><a href="%1$s" rel="tag">%2$s</a> <span class="post-count" title="%3$s">%4$d</span></li>', URL::get('display_entries_by_tag', array('tag' => $tag->slug)), $tag->tag, sprintf(_n('%1$d Post', '%1$d Posts', $tag->count, $this->class_name), $tag->count), $tag->count); } } } else { foreach ($months as $month => $count) { if ($tag->count > 0) { printf('<li class="tag"><a href="%1$s" rel="tag">%2$s</a></li>', URL::get('display_entries_by_tag', array('tag' => $tag->slug)), $tag->tag); } } } echo '</ul>'; } ?><file_sep><?php class Helpify extends Plugin { public function action_update_check() { Update::add( $this->info->name, 'a1477d5c-dc2d-42dd-91e8-d341723466b7', $this->info->version ); } /** * Add template **/ public function action_init() { $this->add_template( 'help', dirname(__FILE__) . '/help.php' ); } /** * Add media files **/ public function action_admin_header() { Stack::add('admin_stylesheet', array(URL::get_from_filesystem(__FILE__) . '/helpify.css', 'screen'), 'helpify'); Stack::add( 'admin_header_javascript', URL::get_from_filesystem(__FILE__) . '/helpify.js', 'helpify', array('jquery', 'jquery.hotkeys') ); } /** * Create plugin configuration **/ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t('Configure'); } return $actions; } /** * Create configuration panel */ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure') : $form = new FormUI( strtolower( get_class( $this ) ) ); $form->append( 'textarea', 'help', strtolower( get_class( $this ) ) . '__help', _t('Help') ); $form->help->raw = true; $form->append( 'submit', 'save', _t('Save') ); $form->out(); break; } } } /** * Add the help to the publish form */ public function action_form_publish($form, $post) { $selector = $form->append('wrapper', 'help_container'); $selector->class = 'container'; $theme = Themes::create(); $theme->help = Options::get( strtolower( get_class( $this ) ) . '__help' ); $content = $theme->fetch( 'help' ); $selector->append( 'static', 'help', $content ); $form->move_after($selector, $form->silos); return $form; } } ?><file_sep><?php /* * HTMLEverywhere Plugin * Usage: * <?php echo $html_sidebar; ?> * <?php echo $html_footer; ?> * <?php echo $html_header(); ?> * A simple plugin to include HTML code directly in your theme header,sidebar and footer. * */ class HTMLEverywhere extends Plugin { /*Create empty options in the DB*/ public function action_plugin_activation( $file ) { Options::set( 'htmleverywhere_header' ); Options::set( 'htmleverywhere_sidebar' ); Options::set( 'htmleverywhere_footer' ); } /*Delete stored options in the DB*/ public function action_plugin_deactivation( $file ) { Options::delete( 'htmleverywhere_header' ); Options::delete( 'htmleverywhere_sidebar' ); Options::delete( 'htmleverywhere_footer' ); } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure') : $ui = new FormUI( strtolower( get_class( $this ) ) ); $head = $ui->append( 'textarea', 'htmlheader', 'option:htmleverywhere_header', _t( 'Your header code:', 'htmleverywhere' ) ); $head->raw = true; $side = $ui->append( 'textarea', 'htmlsidebar', 'option:htmleverywhere_sidebar', _t( 'Your sidebar code:', 'htmleverywhere' ) ); $side->raw = true; $foot = $ui->append( 'textarea', 'htmlfooter', 'option:htmleverywhere_footer', _t( 'Your footer code:', 'htmleverywhere' ) ); $foot->raw = true; $ui->append( 'submit', 'savecode', _t( 'Save code', 'htmleverywhere' ) ); $ui->on_success( array($this, 'formui_submit') ); $ui->out(); } } } /*Action available for this plugin*/ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t( 'Configure' ); } return $actions; } /*Save button was pressed*/ public function formui_submit( FormUI $form ) { Session::notice( _t( 'HTML code saved', 'htmleverywhere' ) ); $form->save(); } function action_add_template_vars( $theme ) { $theme->html_header = Options::get( 'htmleverywhere_header' ); $theme->html_sidebar = Options::get( 'htmleverywhere_sidebar' ); $theme->html_footer = Options::get( 'htmleverywhere_footer' ); } /*Check for updates*/ function action_update_check() { Update::add( 'HTML everywhere', '84226c4b-793e-4c11-9873-4e11fe8e8dd5', $this->info->version ); } } ?> <file_sep><?php class postPass extends Plugin { const PASSWORD_SET_PROMPT = '[Password set. Delete to remove]'; public function info() { return array ( 'name' => 'Post Pass', 'version' => '0.6-0.2', 'author' => 'Habari Community', 'license' => 'Apache License 2.0', 'description' => 'Allows you to password protect your entries.', ); } public function set_priorities() { return array( 'filter_post_content' => 9, ); } public function action_init() { $this->add_template( 'post_password_form', dirname($this->get_file()) . '/post_password_form.php' ); } public function filter_post_content( $content, Post $post ) { if ( $post->info->password ){ // if user logged in, show post // make sure it's not just the anonymous user! $user = User::identify(); if ( ( $user instanceof User ) && ($user != User::anonymous() ) ) { return $content; } $session = Session::get_set('post_passwords', false); $token = Utils::crypt( '42' . $post->info->password . $post->id . Options::get('GUID') ); // if password was submitted verify it if ( Controller::get_var('post_password') && Controller::get_var('post_password_id') == $post->id ) { $pass = InputFilter::filter(Controller::get_var('post_password')); if ( Utils::crypt($pass, $post->info->password) ) { Session::add_to_set('post_passwords', $token, $post->id); $session[$post->id] = $token; } else { Session::error( _t('That password was incorrect.', 'postpass') ); } } // if password is stored in session verify it if ( isset($session[$post->id]) && $session[$post->id] == $token ) { return $content; } else { $theme = Themes::create(); $theme->post = $post; return $theme->fetch('post_password_form'); } } else { return $content; } } public function action_publish_post( Post $post, FormUI $form ) { if ($form->postpass->value == '') { unset($post->info->password); } else if ($form->postpass->value == _t(self::PASSWORD_SET_PROMPT)){ // do nothing } else { $post->info->password = Utils::crypt($form->postpass->value); } } public function action_form_publish( FormUI $form, Post $post) { // add password feild to settings splitter $settings = $form->settings; $settings->append('text', 'postpass', 'null:null', _t('Password', '<PASSWORD>'), 'tabcontrol_text'); if (isset($post->info->password)) { $settings->postpass->value = _t(self::PASSWORD_SET_PROMPT); } } } ?> <file_sep><?php class eventsContent extends Plugin { /** * Required plugin info() implementation provides info to Habari about this plugin. */ public function info() { return array ( 'name' => 'EventsContent', 'url' => 'http://www.squareweave.com.au', 'author' => 'Luke @ Squareweave', 'authorurl' => 'http://luke.giuliani.com.au', 'version' => 0.1, 'description' => 'Adds the event Content-Type', 'license' => 'ASL 2.0', ); } /** * Create help file */ public function help() { $str= ''; $str.= '<p>EventsContent adds the event content type to add an event.</p>'; $str.= '<h3>Installation Instructions</h3>'; $str.= '<p>Your theme needs to have a <code>event.single</code> template, or a generic <code>single</code> template. If it does not, you can usually copy <code>entry.single</code> to <code>event.single</code> and use it.</p>'; return $str; } /** * Add update beacon support **/ public function action_update_check() { Update::add( $this->info->name, 'c330c3fe-3f34-47ff-b5c7-51b2269cfaed', $this->info->version ); } /** * Register content type **/ public function action_plugin_activation( $plugin_file ) { // add the content type. Post::add_new_type( 'event' ); // Give anonymous users access $group = UserGroup::get_by_name('anonymous'); $group->grant('post_event', 'read'); } public function action_plugin_deactivation( $plugin_file ) { Post::deactivate_post_type( 'event' ); } /** * Register templates **/ public function action_init() { // Create templates $this->add_template('event.single', dirname(__FILE__) . '/event.single.php'); } /** * Create name string. This is where you make what it displays pretty. **/ public function filter_post_type_display($type, $foruse) { $names = array( 'event' => array( 'singular' => _t('Event'), 'plural' => _t('Events'), ) ); return isset($names[$type][$foruse]) ? $names[$type][$foruse] : $type; } /** * Modify publish form. We're going to add the custom 'address' field, as we like * to hold our events at addresses. */ public function action_form_publish($form, $post) { // only edit the form if it's an event if ($post->content_type == Post::type('event')) { // just want to add a text field $address= $form->append('text', 'url', 'null:null', _t('Event Address'), 'admincontrol_text'); $address->value= $post->info->address; // put it after the content $form->move_after($address, $form->content); } } /** * Save our data to the database */ public function action_publish_post( $post, $form ) { if ($post->content_type == Post::type('event')) { $this->action_form_publish($form, $post); // Address exists because we made it in action_form_publish() $post->info->address = $form->address->value; } } /** * Add the 'events' type to the list of templates that we can use. */ public function filter_template_user_filters($filters) { if(isset($filters['content_type'])) { $filters['content_type']= Utils::single_array( $filters['content_type'] ); $filters['content_type'][]= Post::type('event'); } return $filters; } } ?><file_sep><div id="magicArchives"> <div id="archive_controller"> <div class="section search"> <a id="archive_previous" href="#previous" title="<?php _e('Older'); ?>">&laquo; <strong><?php _e('Older'); ?></strong></a> <label for="archive_search">Search</label><input type="text" name="archive_search" value="" id="archive_search"> <a id="archive_next" href="#next" title="<?php _e('Newer'); ?>"><strong><?php _e('Newer'); ?> &raquo;</strong></a> </div> <div class="section toggle"> <span id="archive_total">Total Entries: <strong>250</strong></span> <a id="archive_toggle_tags" href="#tags" title="</php _e('Show Tags'); ?>">Filter by Tags</a> </div> <div class="section tags" id="archive_tags"> <?php // Utils::debug($tags); foreach ($tags as $tag) : ?> <span id="<?php echo 'tag_' . $tag->id ?>" class="item tag wt<?php echo MagicArchives::tag_weight($tag->count, 10); ?>"> <span class="checkbox"><input type="checkbox" class="checkbox" name="checkbox_ids[<?php echo $tag->id; ?>]" id="checkbox_ids[<?php echo $tag->id; ?>]"></span><label for="checkbox_ids[<?php echo $tag->id; ?>]"><?php echo $tag->tag; ?></label><sup><?php echo $tag->count; ?></sup> </span> <?php endforeach; ?> </div> </div> <div id="archive_posts"> <?php $theme->display('archive_posts'); ?> </div> </div><file_sep><?php class BlogrollOPMLHandler extends ActionHandler { public function act_blogroll_opml() { $opml= new SimpleXMLElement( '<opml version="1.1"></opml>' ); $head= $opml->addChild( 'head' ); $head->addChild( 'title', Options::get( 'title' ) ); $head->addChild( 'dateCreated', gmdate( 'D, d M Y G:i:s e' ) ); $body= $opml->addChild( 'body' ); $blogs= Blogs::get(); foreach ( $blogs as $blog ) { $outline= $body->addChild( 'outline' ); $outline->addAttribute( 'text', $blog->name ); $outline->addAttribute( 'htmlUrl', $blog->url ); $outline->addAttribute( 'xmlUrl', $blog->feed ); $outline->addAttribute( 'type', 'link' ); $feilds= array_diff_key( $blog->to_array(), array_flip( array('id', 'name', 'url', 'feed') ) ); foreach ( $feilds as $key => $value ) { if ( $value ) { $outline->addAttribute( $key, $value ); } } } $opml= Plugins::filter( 'blogroll_opml', $opml, $this->handler_vars ); $opml= $opml->asXML(); ob_clean(); // header( 'Content-Type: application/opml+xml' ); header( 'Content-Type: text/xml' ); print $opml; } } ?><file_sep><?php class EmailBodyPart { public $body; public $headers = array(); public function __construct($body) { $this->parse_body_part($body); } public function parse_body_part($body) { list($headers, $body) = explode("\n\n", $body, 2); $this->body = $body; $this->headers = new EmailHeaders(trim($headers)); } } <file_sep><?php $active_theme= Options::get( 'theme_dir' ); $all_themes= Themes::get_all_data(); $selected_themes= Options::get( 'themeswitcher__selected_themes' ); ?> <div class="sb-switcher"> <h2>Theme Switcher</h2> <form action="" method="post" name="themeswitcher"> <select name="theme_dir" onChange="this.form.submit()"> <?php foreach( $selected_themes as $selected_theme ) { $theme= $all_themes[$selected_theme]; ?> <option value="<?php echo $theme['dir']; ?>"<?php echo ($theme['dir'] == $active_theme) ? 'selected' : ''; ?>><?php echo $theme['info']->name; ?> <?php echo $theme['info']->version; ?></option> <?php } ?> </select> <input type="submit" style="display: none;" name="themeswitcher_submit" value="Switch"> </form> </div><file_sep><?php //define('CPG_URL', get_settings('siteurl') . '/wp-content/plugins/cpg'); //define('CPG_PHOTO_DIRECTORY', 'cpgphotos'); //define('CPG_SERVER_ADD_DIRECTORY', ''); class CpgOptions extends Singleton { const DEBUG = false; const QUALITY = 95; private $options = null; protected static function instance() { return self::getInstanceOf(get_class()); } public static function setDebug($val = self::DEBUG) { self::instance()->set('debug', $val); } public static function getDebug() { return self::instance()->get('debug', self::CPG_DEBUG); } public static function setQuality($val = self::QUALITY) { self::instance()->set('quality', $val); } public static function getQuality() { return self::instance()->get('quality', self::QUALITY); } public static public function setDbVersion($val) { self::instance()->set('dbVersion', $val); } public static function getDbVersion() { return self::instance()->get('dbVersion', 0); } ////////////////////////////////////////////////////////// // private methods ////////////////////////////////////////////////////////// private function get($key, $defaultVal = null) { if (!isset($this->options)) { $this->options = Options::get('cpg_options'); if ($this->options == null) $this->options = array(); } if (isset($this->options[$key])) return $this->options[$key]; else return $defaultVal; } private function set($key, $value) { if (!isset($this->options[$key]) || $this->options[$key] != $value) { $this->options[$key] = $value; Options::set('cpg_options', $this->options); } } } ?><file_sep><?php echo $fireeagle_form; ?><file_sep><?php class HConsole extends Plugin { private $code = array(); public function info() { return array ( 'name' => 'HConsole', 'version' => '0.1', 'author' => 'Habari Community', 'license' => 'Apache License 2.0', 'description' => 'A live Habari Console.', ); } public function alias() { return array ( 'template_footer' => array( 'action_admin_footer', 'action_template_footer' ) ); } public function action_init() { Stack::add( 'template_header_javascript', Site::get_url('scripts') . '/jquery.js', 'jquery' ); if ( User::identify()->loggedin && $_POST->raw('hconsole_code') ) { $wsse = Utils::WSSE( $_POST['nonce'], $_POST['timestamp'] ); if ( $_POST['PasswordDigest'] == $wsse['digest'] ) { $this->code = $this->parse_code(rawurldecode($_POST->raw('hconsole_code'))); foreach( $this->code['hooks'] as $i => $hook ) { $functions = $this->get_functions($hook['code']); if ( empty($functions) ) { trigger_error( "Parse Error in $i. No function to register.", E_USER_WARNING ); } else { eval($hook['code']); foreach ( $functions as $function ) { if ( $i == 'action_init' ) { call_user_func($function); } else { Plugins::register($function, $hook['type'], $hook['hook']); } } } } } } } public function action_hconsole_debug() { if ( isset($this->code['debug']) ) { eval( $this->code['debug'] ); } } public function template_footer() { if ( User::identify()->loggedin ) { $wsse = Utils::wsse(); $code = $_POST->raw('hconsole_code'); $display = empty($_POST['hconsole_code']) ? 'display:none;' : ''; echo <<<GOO <div > <a href="#" style="width:80px; padding:2px; background:#c00; text-align:center; position:fixed; bottom:0; right:0; font-size:11px; z-index:999; color:white; display:block;" onclick="jQuery('#hconsole').toggle('slow'); return false;">^ HConsole</a> </div> <div id="hconsole" style='$display position:fixed; width:100%; bottom:0; left:0; padding:0; margin:0; background:#ccc; z-index:998;'> <form method='post' action='' style="padding:1em 2em; margin:0"> <textarea cols='100' rows='7' name='hconsole_code'>{$code}</textarea> <input type='submit' value='run' /> <input type="hidden" id="nonce" name="nonce" value="{$wsse['nonce']}"> <input type="hidden" id="timestamp" name="timestamp" value="{$wsse['timestamp']}"> <input type="hidden" id="PasswordDigest" name="PasswordDigest" value="{$wsse['digest']}"> </form> <pre style="border:none; padding:1em 2em; margin:0; background:none; overflow:auto; max-height:150px;"> GOO; Plugins::act('hconsole_debug'); echo "</pre></div>"; } } private function get_functions ( $code ) { $tokens = token_get_all( "<?php $code ?>"); $functions = array(); foreach ( $tokens as $i => $token ) { if ( is_array($token) && $token[0] == T_FUNCTION ) { if ( $tokens[$i+1][0] == T_STRING) { $functions[] = $tokens[$i+1][1]; } elseif ( $tokens[$i+1][0] == T_WHITESPACE && $tokens[$i+2][0] == T_STRING) { $functions[] = $tokens[$i+2][1]; } } } return $functions; } private function parse_code( $code ) { $tokens = token_get_all( "<?php $code ?>"); $hooks = array(); $debug = array(); $flag = false; $braket = 1; for ( $i = 0; $i < count($tokens); $i++ ) { $token = $tokens[$i]; if ( $flag ) { if ( $braket == 0 ) { $hooks[$flag]['end'] = $i-1; $flag = false; $braket = 1; } if ( $token == '}' ) { $braket--; } elseif ( $token == '{' ) { $braket++; } continue; } if ( is_array($token) && $token[0] == T_STRING && preg_match('@^(action|filter|theme|xmlrpc)_(.+)$@i', $token[1], $m) ) { $hooks[$m[0]]['hook'] = $m[2]; $hooks[$m[0]]['type'] = $m[1]; $flag = $m[0]; if ($tokens[$i+1] == '{') { $hooks[$m[0]]['start'] = $i+2; $i+=3; } elseif ($tokens[$i+1][0] == T_WHITESPACE && $tokens[$i+2] == '{') { $hooks[$m[0]]['start'] = $i+3; $i+=2; } else { trigger_error( "Parse Error in $flag", E_USER_ERROR ); } } elseif ( is_array($token) && ($token[0] == T_CLOSE_TAG || $token[0] == T_OPEN_TAG) ) { continue; } else { $debug[] = $token; } } foreach ( $hooks as $i => $hook ) { if ( empty($hook['end']) ) { trigger_error( "Parse Error in $i. No closing braket", E_USER_ERROR ); unset($hooks[$i]); continue; } $toks = array_slice( $tokens, $hook['start'], $hook['end']-$hook['start']); $hooks[$i]['code'] = ''; foreach ( $toks as $token ) { $hooks[$i]['code'] .= is_array($token) ? $token[1] : $token; } } return array( 'hooks' => $hooks, 'debug' => implode(array_map(create_function('$a', 'return is_array($a)?$a[1] : $a;'), $debug)) ); } } ?> <file_sep><ul id="fluffytag"> <?php foreach( $theme->fluffy as $tag ) { echo '<li class="step-' . $tag->step . '"><a href="' . URL::get( 'display_entries_by_tag', array ( 'tag' => $tag->tag_slug ), false ) . '" rel="tag" title="' . $tag->tag_text .'">' . $tag->tag_text . "</a></li>\n"; } ?> </ul> <file_sep><?php /** * Provides a silo to access Diigo bookmarks. * * @category PHP * @package diigosilo * @author <NAME> <<EMAIL>> * @copyright 2008 <NAME> * @license http://www.apache.org/licenses/LICENSE-2.0.txt Apache Software Licence 2.0 * @version 0.2 * @link http://www.pivwan.net/weblog/plugin-diigosilo */ // Load used classes. include_once(dirname(__FILE__).'/httpClient.class.php'); include_once(dirname(__FILE__).'/diigo.class.php'); define('DIIGO_PLUGIN_VERSION','0.2'); class DiigoSilo extends Plugin implements MediaSilo { const SILO_NAME = 'Diigo'; static $cache = array(); /** * Provide plugin info to the system */ public function info() { return array('name' => 'Diigo Media Silo', 'version' => DIIGO_PLUGIN_VERSION, 'url' => 'http://www.pivwan.net/weblog/plugin-diigosilo/', 'author' => 'Pierre-Yves "pivwan" Gillier', 'authorurl' => 'http://www.pivwan.net/weblog/', 'license' => 'Apache Software License 2.0', 'description' => 'Implements Diigo integration', 'copyright' => '2008', ); } public function is_auth() { return true; } /** * Return basic information about this silo * name- The name of the silo, used as the root directory for media in this silo */ public function silo_info() { if($this->is_auth()) { return array('name' => self::SILO_NAME); } else { return array(); } } public function silo_dir($path) { $section = strtok($path, '/'); $results = array(); $diigo = new DiigoAPI(Options::get('diigosilo__username_' . User::identify()->id),Options::get('diigosilo__password_' . User::identify()->id)); switch($section) { case 'bookmarks': $bookmarks = $diigo->getBookmarks(); foreach($bookmarks as $bookmark) { $results[] = new MediaAsset( self::SILO_NAME.'/bookmarks/'.base64_encode($bookmark->url), false, array( 'title' => $bookmark->title,'filetype'=>'diigo', 'link_url' => $bookmark->url, ) ); } break; case 'tags': //$tags = $diigo->getTags(); $results[] = new MediaAsset( self::SILO_NAME . '/tags/' . "demo", true, array( 'title'=>'Tag de d&eacute;mo' ) ); break; case '': $results[] = new MediaAsset( self::SILO_NAME . '/bookmarks', true, array( 'title' => _t('Bookmarks') ) ); $results[] = new MediaAsset( self::SILO_NAME . '/tags', true, array( 'title' => _t('Tags') ) ); $results[] = new MediaAsset( self::SILO_NAME . '/lists', true, array( 'title' => _t('Lists') ) ); break; } return $results; } public function silo_get( $path, $qualities = null ) { } public function silo_put( $path, $filedata ) { } public function silo_delete( $path ) { } public function silo_highlights() {} public function silo_permissions( $path ) {} // PLUGIN FUNCTIONS /** * Add actions to the plugin page for this plugin * The authorization should probably be done per-user. * * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id */ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()) { $actions[] = _t('Configure'); } return $actions; } public function action_plugin_ui($plugin_id, $action) { if ($plugin_id == $this->plugin_id()) { switch ($action) { case _t('Configure'): $ui = new FormUI(strtolower(get_class($this))); $username = $ui->append( 'text', 'username_'.User::identify()->id, 'diigosilo__username_'.User::identify()->id, _t('Username:') ); $password = $ui->append( 'password', '<PASSWORD>_'.User::identify()->id, '<PASSWORD>password_'.User::identify()->id, _t('Password:') ); $ui->append( 'submit', 'save', _t('Save') ); $ui->out(); break; } } } public function updated_config($ui) { return true; } public function action_admin_footer( $theme ) { if ($theme->page == 'publish') { echo <<< DIIGO <script type="text/javascript"> habari.media.output.diigo = function(fileindex, fileobj) { habari.editor.insertSelection('<a href="' + fileobj.link_url + '">' + fileobj.title + '</a>'); } habari.media.preview.diigo = function(fileindex, fileobj) { var stats = ''; return '<div class="mediatitle">' + fileobj.title + '</div><div class="mediastats"><a href="' + fileobj.link_url + '">Link</a></div>'; } </script> DIIGO; } } } ?> <file_sep><ul id="breezyarchives"> <li class="type"><h3><?php echo $chronology_title; ?></h3><?php $theme->chronology_archives(); ?></li> <li class="type"><h3><?php echo $taxonomy_title; ?></h3><?php $theme->taxonomy_archives(); ?></li> </ul><file_sep><?php class OpenID_Delegation extends Plugin { private $config= array(); public function info() { return array( 'name' => 'OpenID Delegation', 'url' => 'http://mikelietz.org/code', 'author' =>'<NAME>', 'authorurl' => 'http://mikelietz.org/', 'version' => '0.1', 'description' => 'Enables site address to be used as a OpenID identifier, when using a third-party OpenID provider.', 'license' => 'Apache License 2.0', ); } public function action_update_check() { Update::add( 'OpenID Delegation', 'DC735D26-9021-11DD-B91C-207A56D89593', $this->info->version ); } function set_priorities() { return array( 'theme_header' => 11, ); } public function action_init() { $class_name= strtolower( get_class( $this ) ); $this->config['provider'] = Options::get( $class_name . '__provider' ); $this->config['identity'] = Options::get( $class_name . '__identity' ); $this->config['is2'] = Options::get( $class_name . '__is2' ); } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t( 'Configure' ); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t( 'Configure' ): $class_name = strtolower( get_class( $this ) ); $ui = new FormUI( $class_name ); $provider = $ui->append( 'text', 'provider', $class_name . '__provider', _t( 'Address of your identity server (required)' ) ); $provider->add_validator( 'validate_required' ); $provider->add_validator( 'validate_url' ); $identity = $ui->append( 'text', 'identity', $class_name . '__identity', _t( 'Your OpenID identifier with that identity provider (required)' ) ); $identity->add_validator( 'validate_required' ); $identity->add_validator( 'validate_url' ); $is2 = $ui->append( 'checkbox','is2', $class_name . '__is2', _t( 'Add links for OpenID 2.0 (must be supported by your provider)' ) ); $ui->append( 'submit', 'save', 'save' ); $ui->out(); break; } } } public function theme_header( $theme ) { if( isset($theme) && $theme->request->display_home ) { return $this->add_links(); } } private function add_links() { $out = ''; $provider = $this->config['provider']; $identity = $this->config['identity']; $is2 = $this->config['is2']; if ( isset( $provider) and isset( $identity ) ) { $out = "\t<link rel=\"openid.server\" href=\"" . $provider . "\">\n"; $out .= "\t<link rel=\"openid.delegate\" href=\"" . $identity . "\">\n"; if ($is2) { $out .= "\t<link rel=\"openid2.provider\" href=\"" . $provider . "\">\n"; $out .= "\t<link rel=\"openid2.local_id\" href=\"" . $identity . "\">\n"; } return $out; } } } ?> <file_sep><?php /** * Flickr Gallr - Display Flickr photos in a gallery on your site * */ class Gallr extends Plugin { // Version info const VERSION = '0.1'; // API key const KEY = '22595035de2c10ab4903b2c2633a2ba4'; /** * Required plugin info() implementation provides info to Habari about this plugin. */ public function info() { return array ( 'name' => 'Flickr Gallr', 'url' => 'http://habariproject.org', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org', 'version' => self::VERSION, 'description' => 'Display Flickr photos in a gallery on your site.', 'license' => 'ASL', ); } /** * Add update beacon support **/ public function action_update_check() { Update::add( $this->info->name, '45D26E5A-64E5-11DD-92F3-D09255D89593', $this->info->version ); } /** * Plugin config **/ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t('Configure'); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure') : $ui = new FormUI( strtolower( get_class( $this ) ) ); $ui->append( 'text', 'username', 'gallr__username', _t('User ID:') ); $ui->append('submit', 'save', _t( 'Save' ) ); $ui->set_option('success_message', _t('Options saved')); $ui->out(); break; } } } public function grab($method, $vars = array()) { $url = 'http://api.flickr.com/services/rest/'; $url.= '?method='.$method; foreach($vars as $key => $val) { $url.= '&'.$val.'='.$val; } Utils::debug($url); } } ?> <file_sep><?php class LastRecent extends Plugin { private $api_key= '<KEY>'; private $cache_expiry= '7200'; private $uuid= 'eeaf6421-abca-4999-95d0-512d328d2462'; private $user= null; private $limit= 3; private $images= 1; public function action_init() { $this->add_template( 'lastfm', dirname( __FILE__ ) . '/lastfm.php' ); $this->user= Options::get( 'lastrecent__user' ); $this->limit= Options::get( 'lastrecent__limit' ); $size= Options::get( 'lastrecent__images' ); switch( $size ) { case 'none': $this->images= null; break; case 'small': $this->images= 0; break; case 'medium': $this->images= 1; break; case 'large': $this->images= 2; break; } } public function action_plugin_activation( $file ) { if ( realpath( $file ) == __FILE__ ) { // a cronjob to fetch the data from last.fm CronTab::add_hourly_cron( 'lastrecent', 'lastrecent', 'Fetch recent tracks from last.fm' ); } } function action_plugin_deactivation( $file ) { if ( Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__) ) { CronTab::delete_cronjob( 'lastrecent' ); Cache::expire( 'lastrecent' ); } } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t('Configure'); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _('Configure') : $ui = new FormUI( strtolower( get_class( $this ) ) ); $user= $ui->append( 'text', 'user', 'lastrecent__user', _t('Last.fm username: ' ) ); $limit= $ui->append( 'select', 'limit', 'lastrecent__limit', _t('Number of tracks to display: ') ); $options= array(); for ( $i= 1; $i<= 10; $i++ ) { $options[$i]= $i; } $limit->options= $options; $images= $ui->append( 'select', 'images', 'lastrecent__images', _t('Show images: ') ); $images->options= array( 'none' => 'none', 'small' => 'small', 'medium' => 'medium', 'large' => 'large' ); $ui->append( 'submit', 'save', _t('Save') ); $ui->out(); break; } } } public function update_config( $ui ) { return true; } public function filter_lastrecent( $result ) { $lastrecent= $this->get_lastrecent(); Cache::set( 'lastrecent', $lastrecent, $this->cache_expiry ); return $result; } public function theme_lastrecent( $theme ) { if ( Cache::has( 'lastrecent' ) ) { $theme->lastfm_tracks= Cache::get( 'lastrecent' ); } else { $theme->lastfm_tracks= $this->get_lastrecent(); Cache::set( 'lastrecent', $theme->lastfm_tracks, $this->cache_expiry ); } return $theme->fetch( 'lastfm' ); } private function get_lastrecent() { $recent= ''; try { $last= new RemoteRequest( 'http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&api_key=' . $this->api_key . '&user=' . urlencode( $this->user ) . '&limit=' . $this->limit ); $last->set_timeout( 5 ); $result= $last->execute(); if ( Error::is_error( $result ) ) { throw $result; } $response= $last->get_response_body(); $xml= new SimpleXMLElement( $response ); $recent= '<ul id="lastrecent">'; foreach( $xml->recenttracks->track as $track ) { $recent.= '<li><a href="' . $track->url . '">'; if ( null !== $this->images ) { $recent.= '<img src="' . $track->image[$this->images] . '" /><br>'; } $recent.= $track->name . '</a> by ' . $track->artist . '</li>'; } $recent.= '</ul>'; } catch( Exception $e ) { $recent['error']= $e->getMessage(); } return $recent; } public function action_update_check() { Update::add( 'RecentLast', $this->uuid, $this->info->version ); } } ?> <file_sep><?php class SimpleTagList extends Plugin { /** * Add help text to plugin configuration page **/ public function help() { $help = _t( 'To use, add <code>&lt;?php $theme->tag_links(); ?&gt;</code> to your theme where you want the list output.' ); return $help; } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Simple Tag List', 'da67e437-e3b9-4d7a-bad8-5ab55b6d801b', $this->info->version ); } /** * On plugin init, add the template included with this plugin to the available templates in the theme */ public function action_init() { $this->add_template( 'simpletaglist', dirname(__FILE__) . '/simpletaglist.php' ); } /** * Add simplified tag array to the available template vars * @param Theme $theme The theme that will display the template **/ public function theme_tag_links( $theme ) { $theme->tag_links = Tags::get(); return $theme->fetch( 'simpletaglist' ); } } ?> <file_sep><?php /** * Random Quotes plugin for Habari 0.5+ * * Usage: <?php $theme->randomquote(); ?> * * @package randomquotes */ class RandomQuotes extends Plugin { const VERSION = '0.1'; const OPTION_NAME = 'randomquotes__filename'; /** * Add help for the plugin admin **/ public function help() { return _t( 'To use, add the following to your theme: <code>&lt;?php $theme->randomquote(); ?&gt;</code>. See also the included quote.php file.' ); } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Random Quotes', '9de12fcf-6c5c-43ad-8d94-c9eb398034e8', $this->info->version ); } /** * Outputs the options form on the plugin page. **/ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { $form = new FormUI( 'randomquotes' ); $control = $form->append('select', 'control', self::OPTION_NAME, _t( 'Quotations file' ) ); foreach( $this->get_all_filenames() as $filename => $file ) { $control->options[$filename] = $file->info->name . ": " . $file->info->description; } $control->add_validator( 'validate_required' ); $form->append( 'submit', 'save', _t( 'Save' ) ); $form->out(); } } /** * Outputs the "configure" button on the plugin page. **/ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t('Configure'); } return $actions; } /** * get the absolute path to the smilies folder for given package name. * * @param string $package_name the smilies package name **/ private function get_path() { return dirname( $this->get_file() ); } /** * Gets an array of all filenames that are available. * * @return array An array of filenames. **/ public function get_all_filenames() { $files = array(); foreach ( glob( $this->get_path() . "/files/*.xml" ) as $file ) { $filename = basename ( $file, ".xml" ); $files[$filename]= simplexml_load_file( $file ); } return $files; } /** * On plugin activation, pick a random quote file. **/ public function action_plugin_activation( $file ) { if( Plugins::id_from_file( $file ) == Plugins::id_from_file( __FILE__ ) ) { if ( Options::get( self::OPTION_NAME ) == null ) { $files = array(); $files = glob( $this->get_path() . "/files/*.xml" ); Options::set( self::OPTION_NAME, basename( $files[ rand( 0,count( $files )-1 ) ], ".xml" ) ); } } } public function theme_randomquote ( $theme ) { $filename = Options::get( self::OPTION_NAME ); $file = simplexml_load_file ( $this->get_path() . "/files/$filename.xml" ); $whichone = rand(0,count($file->quote)-1); $theme->quote_text = $file->quote[$whichone]; $theme->quote_author = $file->quote[$whichone]->attributes()->by; return $theme->fetch( 'quote' ); } /** * On plugin init, add the template included with this plugin to the available templates in the theme **/ public function action_init() { $this->add_template('quote', dirname(__FILE__) . '/quote.php'); } } ?> <file_sep><?php $theme->display('header'); ?> <div class="container"> <div class="item clear"> <div class="pct20">&nbsp;</div> <div class="pct80"><?php $post->updated->out('F jS, Y H:i:s'); ?></div> </div> <div class="item clear"> <div class="pct20"> <label><?php echo _t( 'Title' ); ?></label> </div> <div class="pct80"> <?php echo $post->title; ?> </div> </div> <div class="item clear"> <div class="pct20"> <label><?php echo _t( 'Author' ); ?></label> </div> <div class="pct80"> <?php echo $post->author->username; ?> </div> </div> <div class="item clear"> <div class="pct20"> <label><?php echo _t( 'Content' ); ?></label> </div> <div class="pct80"> <?php echo $post->content; ?> </div> </div> </div> <form action="<?php URL::out( 'admin', 'page=revision_diff' ); ?>" method="get"> <div class="container"> <?php foreach ( $revisions as $i => $revision ): ?> <div class="item clear"> <div class="head"> <span class="checkboxandtitle"> <?php if ( $i == 0 ): ?> <input type="radio" name="old_revision_id" value="<?php echo $revision->id; ?>" disabled="disabled" /> <?php else: ?> <input type="radio" name="old_revision_id" value="<?php echo $revision->id; ?>" /> <?php endif; ?> <input type="radio" name="new_revision_id" value="<?php echo $revision->id; ?>" /> <span class="title"><a href="<?php URL::out( 'admin', 'page=revision&revision_id=' . $revision->id ); ?>"><?php $revision->modified->out('H:i:s, F jS, Y'); ?></a> by <?php echo $revision->author->username; ?></span> </span> <?php if ( $i != 0 ): ?> <ul class="dropbutton"> <li><a href="<?php URL::out( 'admin', 'page=revision&action=rollback&revision_id=' . $revision->id ); ?>"><?php echo _t( 'Rollback' ); ?></a></li> </ul> <?php endif; ?> </div> </div> <?php endforeach; ?> </div> <div class="container transparent"> <div class="item controls"> <input type="submit" value="<?php echo _t( 'Compare selected revisions' ); ?>" class="submitbutton" /> </div> </div> </form> <?php $theme->display('footer'); ?> <file_sep><?php class GoogleAds extends Plugin { /** * When the plugin is initialized, register the block templates and set up supporting data. */ public function action_init() { $this->add_template( "block.googlead", dirname( __FILE__ ) . "/block.googlead.php" ); } private function get_code() { $code = <<<ENDAD <script type="text/javascript"><!-- google_ad_client = "CLIENTCODE"; google_ad_slot = "ADSLOT"; google_ad_width = ADWIDTH; google_ad_height = ADHEIGHT; //--></script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> ENDAD; return $code; } /** * Ad Block * * Handle google ad block output * * @param Block $block The block instance to be configured * @param Theme $theme The active theme */ public function action_block_content_googlead( $block, $theme ) { $code = $this->get_code(); $replace = array( 'CLIENTCODE' => $block->clientcode, 'ADSLOT' => $block->adslot, 'ADWIDTH' => $block->adwidth, 'ADHEIGHT' => $block->adheight ); $code = str_replace( array_keys( $replace ), array_values( $replace ), $code ); $block->code = $code; } /** * Allow configuration of the of the configuration setting for this ad block * * @param FormUI $form The configuration form for this block * @param Block $block The block instance to be configured */ public function action_block_form_googlead( $form, $block ) { $form->append( 'text', 'clientcode', $block, 'Ad Client Code: ' ); $form->append( 'text', 'adslot', $block, 'Ad Slot ID: ' ); $form->append( 'text', 'adwidth', $block, 'Ad Width: '); $form->append( 'text', 'adheight', $block, 'Ad Height: '); $form->append( 'submit', 'save', _t( 'Save' ) ); } /** * Add available blocks to the list of possible block types. * * @param array $block_list an Associative array of the internal names and display names of blocks * * @return array The modified $block_list array */ public function filter_block_list( $block_list ) { $block_list['googlead'] = _t( 'Google Ad' ); return $block_list; } // This section is legacy public function configure() { $ui = new FormUI( strtolower( get_class( $this ) ) ); $clientcode = $ui->append( 'text', 'clientcode', 'googleads__clientcode', _t( 'Ad Client Code' ) ); $adslot = $ui->append( 'text', 'adslot', 'googleads__adslot', _t( 'Ad Slot ID' ) ); $adwidth = $ui->append( 'text', 'adwidth', 'googleads__adwidth', _t( 'Ad Width' ) ); $adheight = $ui->append( 'text', 'adheight', 'googleads__adheight', _t( 'Ad Height' ) ); $ui->append( 'submit', 'save', _t('Save') ); $ui->out(); } private static function getvar( $var ) { return Options::get( 'googleads__' . $var ); } function action_theme_sidebar_bottom() { $code = $this->get_code(); $replace = array( 'CLIENTCODE' => self::getvar( 'clientcode' ), 'ADSLOT' => self::getvar( 'adslot' ), 'ADWIDTH' => self::getvar( 'adwidth' ), 'ADHEIGHT' => self::getvar( 'adheight' ) ); $code = str_replace( array_keys( $replace ), array_values( $replace ), $code ); echo $code; } // End legacy section } ?> <file_sep><?php /** * Revision * * @package revision * @version $Id$ * @author ayunyan <<EMAIL>> * @author freakerz (@1271) * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link http://ayu.commun.jp/habari-revision */ require_once( 'revision_diff.php'); class Revision extends Plugin { /** * plugin information * * @access public * @retrun void */ public function info() { return array( 'name' => 'Revision', 'version' => '0.02', 'url' => 'http://ayu.commun.jp/habari-postrevision', 'author' => 'ayunyan', 'authorurl' => 'http://ayu.commun.jp/', 'license' => 'Apache License 2.0', 'description' => '', 'guid' => '01bcbf1c-2958-11dd-b5d6-001b210f913f' ); } /** * action: plugin_activation * * @access public * @param string $file * @return void */ public function action_plugin_activation( $file ) { if ( Plugins::id_from_file( $file ) != Plugins::id_from_file( __FILE__ ) ) return; Post::add_new_type( 'revision' ); } /** * action: init * * @access public * @return void */ public function action_init() { $this->load_text_domain( 'portrevision' ); $this->add_template( 'revision', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . 'index.php' ); $this->add_template( 'revision_diff', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . 'diff.php' ); } /** * action: update_check * * @access public * @return void */ public function action_update_check() { Update::add($this->info->name, $this->info->guid, $this->info->version); } /** * action: post_insert_after * * @access public * @param object $post * @return void */ public function action_post_insert_after( $post ) { if ( $post->content_type == Post::type( 'revision' ) ) return; $revision = 1; $rev_post = clone $post; $rev_post->id = null; $rev_post->slug = 'revision-' . $revision . ':' . $rev_post->slug; $rev_post->content_type = Post::type( 'revision' ); $rev_post->info->revision = $revision; $rev_post->info->revision_post_id = $post->id; DB::insert( DB::table( 'posts' ), array_diff_key( $rev_post->to_array(), $rev_post->list_excluded_fields() ) ); $rev_post->info->commit( DB::last_insert_id() ); } /** * action: post_update_after * * @access public * @param object $post * @return void */ public function action_post_update_after( $post ) { if ( $post->content_type == Post::type( 'revision' ) ) return; $rev_count = DB::get_row( 'SELECT COUNT(*) AS count FROM {posts} LEFT JOIN {postinfo} ON {posts}.id = {postinfo}.post_id WHERE {postinfo}.name = \'revision_post_id\' AND {postinfo}.value = :post_id', array( 'post_id' => $post->id ) ); $revision = $rev_count->count + 1; $rev_post = clone $post; $rev_post->id = null; $rev_post->slug = 'revision-' . $revision . ':' . $rev_post->slug; $rev_post->content_type = Post::type( 'revision' ); $rev_post->info->revision = $revision; $rev_post->info->revision_post_id = $post->id; DB::insert( DB::table( 'posts' ), array_diff_key( $rev_post->to_array(), $rev_post->list_excluded_fields() ) ); $rev_post->info->commit( DB::last_insert_id() ); } /** * action: admin_theme_get_revision * * @access public * @param object $handler * @param object $theme * @return void */ public function action_admin_theme_get_revision( $handler, $theme ) { if ( isset( $handler->handler_vars['action'] ) && method_exists( $this, 'act_' . $handler->handler_vars['action'] ) ) { call_user_func( array( $this, 'act_' . $handler->handler_vars['action'] ), $handler, $theme ); exit; } if ( empty( $handler->handler_vars['revision_id'] ) ) { Session::notice( sprintf( _t( 'missing parameter: %s' ), 'revision_id' ) ); Utils::redirect( URL::get( 'admin', 'page=dashboard' ) ); return; } $post = Posts::get( array( 'id' => $handler->handler_vars['revision_id'], 'fetch_fn' => 'get_row' ) ); $theme->assign( 'post', $post ); $theme->assign( 'revisions', Posts::get( array( 'info' => array( 'revision_post_id' => $post->info->revision_post_id ), 'orderby' => 'modified DESC', 'nolimit' => true ) ) ); $theme->display( 'revision' ); exit; } /** * local admin action: rollback * * @access private * @param object $handler * @param object $theme * @return void */ private function act_rollback( $handler, $theme ) { if ( empty( $handler->handler_vars['revision_id'] ) ) { Session::notice( sprintf( _t( 'missing parameter: %s' ), 'revision_id' ) ); Utils::redirect( URL::get( 'admin', 'page=dashboard' ) ); return; } $revision = Posts::get( array( 'id' => $handler->handler_vars['revision_id'], 'fetch_fn' => 'get_row' ) ); if ( !$revision ) { Session::notice( _t( 'specify revision not found.' ) ); Utils::redirect( URL::get( 'admin', 'page=dashboard' ) ); return; } $post = Posts::get( array( 'id' => $revision->info->revision_post_id, 'fetch_fn' => 'get_row' ) ); $post->title = $revision->title; $post->content = $revision->content; $post->update(); Utils::redirect( URL::get( 'admin', 'page=publish&id=' . $post->id ) ); } /** * action: admin_theme_get_revision_diff * * @access public * @param object $handler * @param object $theme * @return void */ public function action_admin_theme_get_revision_diff( $handler, $theme ) { if ( empty( $handler->handler_vars['old_revision_id'] ) || empty( $handler->handler_vars['new_revision_id'] ) ) { Session::notice( sprintf( _t( 'missing parameter: %s' ), 'old_revision_id or new_revision_id' ) ); Utils::redirect( URL::get( 'admin', 'page=dashboard' ) ); return; } $old_post = Posts::get( array( 'id' => $handler->handler_vars['old_revision_id'], 'fetch_fn' => 'get_row' ) ); $new_post = Posts::get( array( 'id' => $handler->handler_vars['new_revision_id'], 'fetch_fn' => 'get_row' ) ); $theme->assign( 'old_post', $old_post ); $theme->assign( 'new_post', $new_post ); $content_diff = RevisionDiff::format_diff( $old_post->content, $new_post->content ); $theme->assign( 'content_diff', $content_diff ); $theme->assign( 'revisions', Posts::get( array( 'info' => array( 'revision_post_id' => $old_post->info->revision_post_id ), 'orderby' => 'modified DESC', 'nolimit' => true ) ) ); $theme->display('revision_diff'); exit; } /** * filter: adminhandler_post_loadplugins_main_menu * * @access public * @param array $mainmenu * @return array */ public function filter_adminhandler_post_loadplugins_main_menu( $mainmenu ) { $post_type_id = Post::type( 'revision' ); unset( $mainmenu['create']['submenu']['create_' . $post_type_id] ); unset( $mainmenu['manage']['submenu']['manage_' . $post_type_id] ); return $mainmenu; } /** * filter: publish_controls * * @access public * @param array * @return array */ public function action_form_publish( $controls, $post ) { if ( empty( $post->id ) ) return $controls; $rev_posts = Posts::get( array( 'info' => array( 'revision_post_id' => $post->id ), 'orderby' => 'modified DESC', 'nolimit' => true ) ); $contents = '<div class="container">'; if ( $rev_posts->count() ) { $contents .= '<ul>'; foreach ( $rev_posts as $rev_post ) { $contents .= sprintf('<li><a href="%s">%s by %s</a></li>', URL::get( 'admin', 'page=revision&revision_id=' . $rev_post->id ), $rev_post->modified->format('F jS, Y H:i:s'), $rev_post->author->username ); } $contents .= '</ul>'; } else { $contents .= '<p>'._t('No revisions available.').'</p>'; } $contents .= '</div>'; $controls->publish_controls->append('fieldset', 'revisions', _t('Revisions')); $controls->publish_controls->revisions->append('static', 'revisions_list', $contents); } } ?><file_sep> <footer role="contentinfo"> <?php $theme->area( 'footer' ); ?> <p><a href="http://www.habariproject.org/" rel="generator">Habari</a> &amp; <a href="http://blog.bcse.tw/null-theme">Null Theme</a></p> </footer> </div> <?php $theme->footer(); ?> </body> </html><file_sep><?php $theme->display('header');?> <div class="create"> <?php echo $form; ?> </div> <div id="options_view" class="container settings"> <div style="float:right"> <?php _e( 'Options counts: Total [<strong>%d</strong>] Inactive [<strong>%d</strong>]', array( $this->opts_count_total, $this->opts_count_inactive ) ); _e( ' Core deletes: [<strong>%s</strong>]', array( (empty($opts_local['allow_delete_core']) ? 'disabled' : 'enabled') ) ); _e( ' Other deletes: [<strong>%s</strong>]', array( (empty($opts_local['allow_delete_other']) ? 'disabled' : 'enabled') ) ); ?> </div> </div> <div class="container"> <h2><?php _e('All known Habari options'); ?></h2> <div class="head clear"> <span class="title pct25">Name</span> <span class="title pct5">Genre</span> <span class="title pct10">Plugin</span> <span class="title pct5">Ser?</span> <span class="title pct10">Active?</span> <span class="title pct30">Value</span> <span class="title pct15">Actions</span> </div> <div class="manage view_options"> <?php foreach($options as $option_name => $option): ?> <div class="item clear"> <span class="message pct25 minor less"> <strong><?php echo substr ( $option_name, 0, 35 ); ?></strong> </span> <span class="message pct25 major more"> <strong><?php echo $option_name; ?></strong> </span> <span class="title pct5 minor"> <?php _e( '%s', array( $option['genre'] ) ); ?> </span> <span class="title pct10 minor"> <?php _e( '%s', array( $option['plugin_name'] ) ); ?> </span> <span class="title pct5 minor"> <?php _e( '%s', array( ($option['type'] === '1' ? 'yes' : 'no') ) ); ?> </span> <span class="title pct10 minor"> <?php _e( '%s', array( ($option['active'] === 'no' ? 'no' : $option['active']) ) ); ?> </span> <span class="message pct30 minor less"> <?php echo substr( Utils::htmlspecialchars($option['value']), 0, 60 ); ?> </span> <span class="message pct30 minor more"> <?php if ( isset( $option['value_unserialized'] ) && count( $option['value_unserialized'] ) > 0): ?> <div class="container settings"> <h2>Unserialized version of the value</h2> <ul> <?php foreach ( $option['value_unserialized'] as $name => $value ): ?> <li class="item clear"> <span class="title pct20 minor"><?php echo $name; ?></span> <span class="title pct80 minor"><?php echo Utils::htmlspecialchars($value); ?></span> </li> <?php endforeach; ?> </ul> </div> <?php else: echo Utils::htmlspecialchars($option['value']); endif; ?> </span> <span class="select pct15 minor"> <ul class="dropbutton"> <li><a href="<?php URL::out('admin', array('page'=>'options_edit', 'action'=>'edit', 'option_name'=>$option_name)); ?>"><?php _e('Edit'); ?></a></li> <?php if ( $option['delete_allowed'] ): ?> <li><a href="<?php URL::out('admin', array('page'=>'options_view', 'action'=>'delete', 'option_name'=>$option_name)); ?>"><?php _e('Delete'); ?></a></li> <?php endif; ?> </ul> </span> </div> <?php endforeach; ?> </div> </div> <?php $theme->display('footer');?> <file_sep><?php /** * habaridiggbarkiller Plugin * * A plugin for Habari that removes the diggbar frame * adapted from http://farukat.es/journal/2009/04/225-javascript-diggbar-killer-not-blocker * * @package habaridiggbarkiller */ class habaridiggbarkiller extends Plugin { /** * Add update beacon support **/ public function action_update_check() { Update::add( 'habaridiggbarkiller', '506FC1DE-263A-11DE-8510-152456D89593', $this->info->version ); } public function action_template_header() { ?> <!-- habaridiggbarkiller --> <script type="text/javascript"> if (top !== self && document.referrer.match(/digg\.com\/\w{1,8}/)) { top.location.replace(self.location.href); } </script> <!-- habaridiggbarkiller END --> <?php } } ?> <file_sep><?php foreach($content->posts as $post) { $theme->content($post); } ?><file_sep><!-- commentsform --> <?php // Do not delete these lines if ( ! defined('HABARI_PATH' ) ) { die( _t('Please do not load this page directly. Thanks!') ); } ?> <div class="comments"> <h4 id="respond" class="reply"><?php _e('Leave a Reply'); ?></h4> <?php if ( Session::has_messages() ) { Session::messages_out(); } ?> <form action="<?php URL::out( 'submit_feedback', array( 'id' => $post->id ) ); ?>" method="post" id="commentform"> <div id="comment-personaldetails"> <p> <input type="text" name="name" id="name" value="<?php echo $commenter_name; ?>" size="22" tabindex="1"> <label for="name"><small><strong><?php _e('Name'); ?></strong></small><span class="required"><?php if (Options::get('comments_require_id') == 1) : ?> *<?php _e('Required'); ?><?php endif; ?></span></label> </p> <p> <input type="text" name="email" id="email" value="<?php echo $commenter_email; ?>" size="22" tabindex="2"> <label for="email"><small><strong><?php _e('Mail'); ?></strong> (<?php _e('will not be published'); ?>)</small><span class="required"><?php if (Options::get('comments_require_id') == 1) : ?> *<?php _e('Required'); ?><?php endif; ?></span></label> </p> <p> <input type="text" name="url" id="url" value="<?php echo $commenter_url; ?>" size="22" tabindex="3"> <label for="url"><small><strong><?php _e('Website'); ?></strong></small></label> </p> </div> <p> <textarea name="content" id="content" cols="40" rows="10" tabindex="4"> <?php echo $commenter_content; ?> </textarea> </p> <p> <input name="submit" type="submit" id="submit" tabindex="5" value="<?php _e('Submit'); ?>"> </p> <div class="clear"></div> </form> </div> <!-- /commentsform --> <file_sep><?php include ('header.php'); ?> <!-- page.single --> <div id="content"> <div id="post-<?php echo $post->id; ?>" class="page"> <div class="post"> <div class="post-info"> <h2 class="posttitle"> <a href="<?php echo $post->permalink; ?>" title="<?php echo $post->title; ?>"> <?php echo $post->title_out; ?> </a> </h2> <?php if ( $user ) : ?> <span class="entry-edit"> <a href="<?php URL::out( 'admin', 'page=publish&slug=' . $post->slug); ?>" title="Edit post"> (edit)</a> </span> <?php endif; ?><br/> </div> <!-- post-info --> <div class="postentry"> <?php echo $post->content_out; ?> </div> <!-- .post-content --> </div> <!-- .post --> </div> <!-- #post-id .post --> </div> <!-- #content --> <?php include('sidebar.php'); ?> <!-- /page.single --> <?php include('footer.php'); ?> <file_sep><?php include_once( 'markitup/parsers/markdown/markdown.php' ); class MarkUp extends Plugin { /** * Required Plugin Information **/ public function info() { return array( 'name' => 'markUp', 'license' => 'Apache License 2.0', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'version' => '0.3', 'description' => 'Adds easy html or markdown tag insertion to Habari\'s editor', 'copyright' => '2008' ); } /** * Set options to defaults */ public function action_plugin_activation( $file ) { if ( realpath( $file ) == __FILE__ ) { $type = Options::get( 'Markup__markup_type' ); if ( empty( $type ) ) { Options::set( 'Markup__markup_type', 'html' ); } $skin = Options::get( 'Markup__skin' ); if( empty( $skin ) ) { Options::set( 'Markup__skin', 'simple' ); } } } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t( 'Configure' ); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { $types = array( 'html' => 'html', 'markdown' => 'markdown', ); $skins = array( 'simple' => 'Simple', 'markitup' => 'MarkItUp', ); if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t( 'Configure' ): $form = new FormUI( 'markup' ); $form->append( 'select', 'markup_type', 'Markup__markup_type', _t( 'Markup Type ' ) ); $form->markup_type->options = $types; $form->append( 'select', 'skin', 'Markup__skin', _t( 'Editor Skin&nbsp;&nbsp;&nbsp; ' ) ); $form->skin->options = $skins; $form->append( 'submit', 'save', _t( 'Save' ) ); $form->on_success( array( $this, 'config_success' ) ); $form->out(); break; } } } public static function config_success( $ui ) { $ui->save(); Session::notice( 'Markup settings updated.' ); } public function action_admin_header( $theme ) { if ( $theme->page == 'publish' ) { $set = Options::get( 'Markup__markup_type' ); switch( $set ) { case 'markdown': $dir = 'markdown'; break; case 'html': default: $dir = 'html'; } $skin = Options::get( 'Markup__skin' ); Stack::add( 'admin_header_javascript', $this->get_url() . '/markitup/jquery.markitup.pack.js' ); Stack::add( 'admin_header_javascript', $this->get_url() . '/markitup/sets/' . $dir . '/set.js' ); Stack::add( 'admin_stylesheet', array( $this->get_url() . '/markitup/skins/' . $skin . '/style.css', 'screen' ) ); Stack::add( 'admin_stylesheet', array( $this->get_url() . '/markitup/sets/' . $dir . '/style.css', 'screen' ) ); } } public static function filter_post_content_out( $content, $post ) { $markup = Options::get( 'Markup__markup_type' ); switch( $markup ) { case 'markdown': return Markdown( $content ); break; case 'html': default: return $content; } } public function action_admin_footer($theme) { if ( $theme->page == 'publish' ) { $skin = Options::get( 'Markup__skin' ); $set = ( ( 'markitup' == $skin ) ? Options::get( 'Markup__markup_type' ) : '' ); echo <<<MARKITUP <script type="text/javascript"> $(document).ready(function() { mySettings.nameSpace = '$set'; mySettings.resizeHandle= false; $("#content").markItUp(mySettings); $('label[for=content].overcontent').attr('style', 'margin-top:30px;margin-left:5px;'); $('#content').focus(function(){ $('label[for=content]').removeAttr('style'); }).blur(function(){ if ($('#content').val() == '') { $('label[for=content]').attr('style', 'margin-top:30px;margin-left:5px;'); } else { $('label[for=content]').removeAttr('style'); } }); }); </script> MARKITUP; } } public function action_update_check() { Update::add( 'markUp', 'F695D390-2687-11DD-B5E1-2D6F55D89593', $this->info->version ); } } ?><file_sep><?php /** * @package Habari * @subpackage Gravatar * * To use, add <?php $theme->gravatar($comment); ?> * */ /** * All plugins must extend the Plugin class to be recognized. */ class Gravatar extends Plugin { /** * Required method for all plugins. * * @return array Various informations about this plugin. */ public function info() { return array( 'name' => 'Gravatar', 'version' => '1.3.1', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Gravatar plugin for Habari', 'copyright' => '2008' ); } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Gravatar', 'c33ba010-3b9a-11dd-ae16-0800200c9a66', $this->info->version ); } /** * Return a URL to the author's Gravatar based on his e-mail address. * * @param object $comment The Comment object to build a Gravatar URL from. * @return string URL to the author's Gravatar. */ public function theme_gravatar( $theme, $comment ) { // The Gravar ID is an hexadecimal md5 hash of the author's e-mail address. $query_arguments = array( 'gravatar_id' => md5( $comment->email ) ); // Retrieve the Gravatar options. $options = Options::get( 'gravatar__default', 'gravatar__size', 'gravatar__rating' ); foreach ( $options as $key => $value ) { if ( $value != '' ) { // We only want "default, size, rating". list( $junk, $key ) = explode( '__', $key ); $query_arguments[$key] = $value; } } // Ampersands need to be encoded to &amp; for HTML to validate. $query = http_build_query( $query_arguments, '', '&amp;' ); $url = "http://www.gravatar.com/avatar.php?" . $query; $theme->gravatar = $url; $theme->gravatar_size = isset($options['gravatar__size']) ? $options['gravatar__size'] : 32; $theme->commentor = $comment->name; return $theme->fetch('gravatar'); } /** * Add our menu to the FormUI for plugins. * * @param array $actions Array of menu items for this plugin. * @param string $plugin_id A unique plugin ID, it needs to match ours. * @return array Original array with our added menu. */ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id ) { $actions[] = 'Configure'; } return $actions; } /** * Handle calls from FormUI actions. * Show the form to manage the plugin's options. * * @param string $plugin_id A unique plugin ID, it needs to match ours. * @param string $action The menu item the user clicked. */ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id ) { switch ( $action ) { case 'Configure': $ui = new FormUI( 'gravatar' ); $g_s_d = $ui->append( 'text', 'default', 'gravatar__default', '<dl><dt>Default Gravatar</dt><dd>An optional "default" parameter may follow that specifies the full, URL encoded URl, protocol included of a GIF, JPEG or PNG image that should be returned if either the request email address has no associated gravatar, or that gravatar has a rating higher than is allowed by the "rating" parameter.</dd></dl>' ); $g_s_s = $ui->append( 'text', 'size', 'gravatar__size', '<dl><dt>Size</dt><dd>An optional "size" parameter may follow that specifies the desired width and height of the gravatar. Valid vaues are from 1 to 80 inclusive. Any size other than 80 will cause the original gravatar image to be downsampled using bicubic resampling before output.</dd></dl>' ); //mark size as required $g_s_s->add_validator( 'validate_required' ); $g_s_r = $ui->append( 'select', 'rating', 'gravatar__rating', '<dl><dt>Rating</dt><dd>An optional "rating" parameter may follow with a value of [ G | PG | R | X ] that determines the highest rating (inclusive) that will be returned.</dd></dl>', array( 'G' => 'G', 'PG' => 'PG', 'R' => 'R', 'X' => 'X' ) ); $ui->append( 'submit', 'save', _t('Save') ); $ui->out(); break; } } } /** * On plugin init, add the template included with this plugin to the available templates in the theme */ public function action_init() { $this->add_template('gravatar', dirname(__FILE__) . '/gravatar.php'); } } ?> <file_sep><?php include 'header.php'; ?> <div class="post"> <h2 class="posttitle" id="post">Error!</h2> <div class="postentry">The content you were looking for isn't here!</div> </div> <?php include 'sidebar.php'; ?> <?php include 'footer.php'; ?> <file_sep><?php /** * Lipsum Plugin Class * **/ class Lipsum extends Plugin { private $thumbs = array(); /** * Return information about this plugin * @return array Plugin info array **/ function info() { return array ( 'name' => 'Lipsum', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'version' => '1.0', 'description' => 'Creates random sample data to test themes and plugins', 'license' => 'Apache License 2.0', ); } /** * Adds a Configure action to the plugin * * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The id of a plugin * @return array The array of actions */ public function filter_plugin_config( $actions, $plugin_id ) { if ( $this->plugin_id() == $plugin_id ){ $actions[]= 'Configure'; } return $actions; } /** * Creates a UI form to handle the plugin configuration * * @param string $plugin_id The id of a plugin * @param array $actions An array of actions that apply to this plugin */ public function action_plugin_ui( $plugin_id, $action ) { if ( $this->plugin_id()==$plugin_id && $action=='Configure' ) { $form = new FormUI( strtolower(get_class( $this ) ) ); $form->append( 'text', 'num_posts', 'option:lipsum__num_posts', _t('Number of posts to create:')); $form->num_posts->add_validator( 'validate_required' ); $form->append( 'submit', 'save', _t( 'Save' ) ); $form->on_success( array( $this, 'update_num_posts' ) ); $form->out(); } } function action_plugin_activation( $file ) { if(Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__)) { set_time_limit(0); $user = User::get_by_name( 'lipsum' ); if ( !$user ) { $user = User::create(array ( 'username'=>'lipsum', 'email'=>'<EMAIL>', 'password'=>md5('q' . rand(0,65535)), )); } $time = time() - 160; $num_posts = Options::get( 'lipsum__num_posts' ); if ( ! $num_posts ) { Options::set( 'lipsum__num_posts', 20); $num_posts = 20; } for($z = 0; $z < $num_posts; $z++) { $this->make_post( $user, $time = $time - rand(3600, 3600*36) ); } Session::notice("Created {$num_posts} sample posts with random comments."); } } function action_plugin_deactivation( $file ) { if(Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__)) { set_time_limit(0); $posts = Posts::get(array('info'=>array('lipsum' => true), 'nolimit'=>true)); $count = 0; foreach($posts as $post) { $post->delete(); $count++; } Session::notice("Removed {$count} sample posts and their comments."); } } function update_num_posts( $form ) { $num_posts = $form->num_posts->value; $num_posts = is_numeric($num_posts) ? (int) $num_posts : 20; $current_count = (int) Posts::get( array( 'info' => array( 'lipsum' => true ), 'count' => true ) ); if ( $num_posts == $current_count ) { return $form->get( false ); } // remove some posts if the $num_posts is less than the current count if ( $num_posts < $current_count ) { $limit = $current_count - $num_posts; $posts = Posts::get( array( 'info' => array('lipsum' => true), 'limit' => $limit ) ); $count = 0; foreach( $posts as $post) { $post->delete(); $count++; } Session::notice("Removed {$count} sample posts and their comments."); } // otherwise, we need to add some posts else { $user = User::get_by_name( 'lipsum' ); $time = time() - 160; $count = 0; for ( $i = $current_count + 1; $i <= $num_posts; $i++ ) { $this->make_post( $user, $time = $time - rand(3600, 3600*36) ); $count++; } Session::notice( "Created {$count} sample posts with random comments."); } // return the form to redisplay it return $form->get( false ); } /** * make_post * Makes a single post and adds a random number of comments (between 0 and 6) * to the post * @param object $user The Lipsum user * @param timestamp $time The published timestamp of the new posts */ private function make_post( $user, $time ) { $post = Post::create(array( 'title' => $this->get_title(), 'content' => $this->get_content(1, 3, 'some', array('thumb'=>1, 'ol'=>1, 'ul'=>1), 'cat'), 'user_id' => $user->id, 'status' => Post::status('published'), 'content_type' => Post::type('entry'), 'tags' => 'lipsum', 'pubdate' => HabariDateTime::date_create( $time++ ), )); $post->info->lipsum = true; $post->info->commit(); $addcomments = mt_rand(0,6); $comment_time = $time; for($q = 0; $q < $addcomments; $q++) { $comment = Comment::create(array( 'post_id' => $post->id, 'name' => $this->num2word(rand(1, 9999)), 'url' => 'http://example.com/', 'content' => $this->get_content(1, 2, 'none', array(), 'cat'), 'status' => Comment::STATUS_APPROVED, 'type' => Comment::COMMENT, 'date' => HabariDateTime::date_create( $comment_time = $comment_time + rand(3600, 3600*24) ), )); $comment->info->lipsum = true; $comment->info->commit(); } } private function get_pgraph() { $start = array("Nam quis nulla", "Integer malesuada", "In an enim", "Sed vel lectus", "Donec odio urna,", "Phasellus rhoncus", "Aenean id ", "Vestibulum fermentum", "Pellentesque ipsum", "Nulla non", "Proin in tellus", "Vivamus luctus", "Maecenas sollicitudin", "Etiam egestas", "Lorem ipsum dolor sit amet,", "Nullam feugiat,", "Aliquam erat volutpat", "Mauris pretium",); $mid = array(" a arcu imperdiet", " tempus molestie,", " porttitor ut,", " iaculis quis,", " metus id velit", " lacinia neque", " sed nisl molestie", " sit amet nibh", " consectetuer adipiscing", " turpis at pulvinar vulputate,", " erat libero tristique tellus,", " nec bibendum odio risus"," pretium quam", " ullamcorper nec,", " rutrum non,", " nonummy ac,", " augue id magna",); $end = array(" nulla. "," malesuada. "," lectus. "," sem. "," pulvinar. "," faucibus fringilla. "," dignissim sagittis. "," egestas leo. "," metus. "," erat. "," elit. "," sit amet ante. "," volutpat. "," urna. "," rutrum. ",); $ipsum_text = ''; $lines = rand(1,6); for($l = 0; $l < $lines; $l++) { $line = $start[rand(0,count($start)-1)]; $mids = rand(1,3); for($z = 0; $z < $mids; $z++) $line .= $mid[rand(0,count($mid)-1)]; $line .= $end[rand(0,count($end)-1)]; $ipsum_text .= $line; } $ipsum_text .= "\n\n"; return $ipsum_text; } private function num2word($i) { $word = ''; $phon = array('do', 're', 'mi', 'fa', 'so', 'la', 'ti', 'ko', 'fu', 'jan'); do { $word = $phon[$i % 10] . $word; $i = floor($i/10); } while($i >0); return $word; } private function get_title() { $text = $this->get_pgraph(1); $text = strtolower($text); $text = preg_replace('/[^a-z\s]/', '', $text); $text = explode(' ', $text); $words = rand(2, 8); $title = ''; for($i = 0; $i < $words; $i++) { $title .= $text[rand(0, count($text)-1)] . ' '; } $title = ucwords(trim($title)); return $title; } private function get_thumb_tag($tags) { if(count($this->thumbs) == 0) { $searchurl = 'http://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=420fb7714e08dbcc97ac8228df21d985&license=4,2&per_page=10&tags=' . urlencode(implode(',', $tags)); $results = RemoteRequest::get_contents($searchurl); preg_match_all('/<photo.*id="([0-9]+)".*owner="([^"]+)".*secret="([0-9a-f]+)".*server="([0-9]+)".*title="([^"]+)".*\/>/', $results, $matches, PREG_SET_ORDER); foreach($matches as $match) { list($fulltag, $id, $owner, $secret, $server, $title) = $match; $imgurl = "http://static.flickr.com/{$server}/{$id}_{$secret}_m.jpg"; $flickrurl = "http://flickr.com/photos/{$owner}/{$id}"; $styles = array ( ' style="float:left;"', ' style="float:right;"', ' style="display:block;"', ); $style = $styles[rand(0,count($styles)-1)]; $this->thumbs[] = "<a href=\"{$flickrurl}\"{$style}><img src=\"{$imgurl}\" alt=\"{$title}\"></a>"; } } return (count($this->thumbs) > 0) ? $this->thumbs[rand(0,count($this->thumbs)-1)] : ''; } private function get_content($min, $max, $more, $features, $imgtags) { $lipsum_text = ''; $howmany = rand($min, $max); for($i = 0; $i < $howmany; $i++) { if(isset($features['thumb'])) { if(rand(1, $max - $i + 1) == 1) { $lipsum_text .= $this->get_thumb_tag(explode(' ',$imgtags)); unset($features['thumb']); } } $lipsum_text .= $this->get_pgraph(); if(isset($features['ol'])) { if(rand(1, $max - $i + 1) == 1) { $listitems = rand(3,10); $lipsum_text .= "<ol>\n"; for($z = 0; $z < $listitems; $z++) { $lipsum_text .= "\t<li>" . $this->get_title() . "</li>\n"; } $lipsum_text .= "</ol>\n"; unset($features['ol']); } } if(isset($features['ul'])) { if(rand(1, $max - $i + 1) == 1) { $listitems = rand(3,10); $lipsum_text .= "<ul>\n"; for($z = 0; $z < $listitems; $z++) { $lipsum_text .= "\t<li>" . $this->get_title() . "</li>\n"; } $lipsum_text .= "</ul>\n"; unset($features['ul']); } } switch($more) { case 'none': break; case 'some': if(rand(1,2) == 1) break; case 'all': if($i==0 && $howmany > 1) { $lipsum_text .= '<!--more-->'; } } } return $lipsum_text; } } ?> <file_sep><?php class Loupable extends Plugin { public function action_init() { $this->add_template('loupe.public', dirname(__FILE__) . '/loupe.public.php'); } public function action_init_theme() { Stack::add( 'template_stylesheet', array( URL::get_from_filesystem(__FILE__) . '/loupable.css', 'screen' ), 'loupable' ); Stack::add( 'template_header_javascript', Site::get_url('scripts') . '/jquery.js', 'jquery' ); Stack::add( 'template_header_javascript', URL::get_from_filesystem(__FILE__) . '/loupable.js', 'loupable' ); } public function action_add_template_vars($theme, $handler_vars) { $items = array(); if(isset($theme->request->display_home) && $theme->request->display_home) { $posts = Posts::get(array('content_type' => Post::type('entry'), 'status' => Post::status('published'), 'nolimit' => true, 'orderby' => 'pubdate ASC')); foreach($posts as $post) { $item = array(); $item['url'] = $post->permalink; $item['title'] = $post->title; $item['time'] = strtotime($post->pubdate); $items[] = $item; } } $theme->timeline_items = $items; } } ?><file_sep>Plugin: Keywords 1.1 URL: http://peeters.22web.net/project-habari-keywords Plugin Author: <NAME> - http://peeters.22web.net Licenses: Keywords : Apache Software License 2.0 DESCRIPTION ----------- Keywords is a simple, yet effective Habari plugin which allows you to add HTML Meta tags Keywords and Desctription for each post you create. The plugin is inspired by MetaSEO plugin by Habari Community, which was not compatible with the 0.7 Habari version when I was building my first Habari site. INSTALLATION ------------ 1. Download the archive to your server 2. Extract the contents to a temporary location (not strictly necessary, but just being safe) 3. Move the keywords directory to /path/to/your/habari/user/plugins/ 4. Add following tags in your theme's header.php template inside the <head>...</head> tag: <meta name="keywords" content="your, default, keywords"> <meta name="description" content="Your default description."> 5. Refresh your plugins page and activate the plugin 6. In each post you create, fill in the 'Meta' section UPGRADE ------- The upgrade procedure is as per the installation procedure. HOW IT WORKS ------------ * Keywords plugin checks, if there are any keywords and description filled in for currently displayed post. * It replaces your default meta keywords and meta description tag contents with the values you filled in. * If no keywords or description is filled or if you're not currently viewing any post, no replacing is preformed and default meta tags in your template are displayed. REVISION HISTORY ---------------- 1.1 - Some code cleanup, GUID support was added. 1.0 - Initial release If you encounter any problems, please feel free to leave a comment on the post that relates to the release.<file_sep><?php class RelativelyPopular extends Plugin { public $n_periods; public $interval; public $day; public $now; /** * Add the necessary template as a block * **/ public function action_init() { // init $n = Options::get( 'relativelypopular__number_of_periods' ); // number of periods if( $n == null || strval($n)!=strval(intval($n))) $n = 30; $this->n_periods = $n; $interval = Options::get( 'relativelypopular__period_length_days' ); // period length in days if( $interval == null || strval($interval)!=strval(floatval($interval))) $interval = 1; $this->interval = $interval; // a figure that can be reliably used in integer division to obtain a continuous sequence // of numbers across a discontinuity, such as at the end of a year if we're counting days 0-365 $this->day = intval(time()/(60*60*24*$interval)); $this->now = $this->day%(2*$n); // store 2n time periods so we accurately track provided there is one visit in n $this->add_template( 'block.relativelypopular', dirname(__FILE__) . '/block.relativelypopular.php' ); } /** * Add to the list of possible block types * **/ public function filter_block_list( $block_list ) { $block_list[ 'relativelypopular' ] = _t( 'Relatively Popular Posts', 'relativelypopular' ); return $block_list; } /** * Create a configuration form for this plugin * **/ public function configure() { $form = new FormUI( 'relativelypopular' ); $form->append( 'checkbox', 'loggedintoo', 'relativelypopular__loggedintoo', _t( 'Track visits of logged-in users too', 'relativelypopular' ) ); $form->append( 'text', 'number_of_periods', 'relativelypopular__number_of_periods', _t( 'Number of periods to track [default=30]', 'relativelypopular' ) ); $form->append( 'text', 'period_length_days', 'relativelypopular__period_length_days', _t( 'Tracking period length (days) [default=1]', 'relativelypopular' ) ); $form->append( 'submit', 'save', 'Save' ); $form->out(); } /** * Create a configuration form for the block **/ public function action_block_form_relativelypopular( $form, $block ) { $content = $form->append( 'text', 'quantity', $block, _t( 'Posts to show:', 'relativelypopular' ) ); $form->append( 'submit', 'save', _t( 'Save', 'relativelypopular' ) ); } /** * Log the entry page view, when appropriate. * */ public function action_add_template_vars( $theme, $handler_vars ) { // If there is only one post if ( $theme->post instanceof Post && count( $theme->posts ) == 1 ) { // Only track users that aren't logged in, unless specifically overridden if ( !User::identify()->loggedin || Options::get( 'relativelypopular__loggedintoo' ) ) { $set = Session::get_set( 'relativelypopular', false ); $post = $theme->post; // this code is actually executed about 9 times per page request on my system, // so this check here is essential otherwise we bias the results by a factor of 9 if ( !in_array( $post->id, $set ) ){ // load fields $visits = $post->info->visits; $visits_activity = $post->info->visits_activity; // check if fields currently exist and contain the requsite valid data, otherwise reinitalise if ( $visits_activity == null || count(explode('#', $visits_activity))!=2*$this->n_periods) { $visits_activity = implode('#', array_fill(0, 2*$this->n_periods, 0)); } $activity = explode('#', $visits_activity); if(!array_key_exists($this->now, $activity)) { $activity += array($this->now=>0); } // increment the quantity for the period we're currently in and blank the $n_periods fields following it $activity[$this->now] += 1; for($i=1; $i<=$this->n_periods; $i++) { $next = ($this->day+$i)%(2*$this->n_periods); if(!array_key_exists($next, $activity)) { $activity += array($next=>0); } $activity[$next] = 0; } // evaluate the total hits for this time period and store it along with the activity trace $post->info->visits = array_sum($activity); $post->info->visits_activity = implode('#', $activity); $post->info->commit(); Session::add_to_set( 'relativelypopular', $post->id ); } } } if(!isset($theme->RelativelyPopular)) { $theme->RelativelyPopular = $this; } } /** * Display a template with the popular entries */ public function theme_relativelypopular($theme, $limit = 5) { $theme->relativelypopular = Posts::get( array( 'content_type' => 'entry', 'has:info' => 'visits', 'orderby' => 'CAST(hipi1.value AS UNSIGNED) DESC', // As the postinfo value column is TEXT, ABS() forces the sorting to be numeric 'limit' => $limit ) ); return $theme->display( 'relativelypopular' ); } /** * Populate a block with the popular entries **/ public function action_block_content_relativelypopular( $block, $theme ) { if ( ! $limit = $block->quantity ) { $limit = 5; }; $block->relativelypopular = Posts::get( array( 'content_type' => 'entry', 'has:info' => 'visits', 'orderby' => 'CAST(hipi1.value as UNSIGNED) DESC', // As the postinfo value column is TEXT, ABS() forces the sorting to be numeric 'limit' => $limit ) ); } /** * Display a histogram of blocks (sparkline) wherever the theme requests it **/ public function sparkline($content) { $act = explode('#', $content->info->visits_activity); $max = max($act); $sparkblocks = array('▁', '▂', '▃', '▄', '▅', '▆', '▇'); for($i=0; $i<$this->n_periods; $i++) { $k = ($this->now+$this->n_periods+1+$i)%(2*$this->n_periods); $this_act = (array_key_exists($k, $act) ? $act[$k] : 1); echo $sparkblocks[round(6*$this_act/$max)]; } } } ?> <file_sep><?php class Macros extends Plugin { const GUID = 'a59c173e-6b2f-4917-afef-616fd8d615f4'; const PLUGIN_NAME = 'Macros'; const PLUGIN_TOKEN = '<PASSWORD>'; const VERSION = '0.1alpha'; const MARKER_OPEN = '<!--+'; const MARKER_CLOSE = '+-->'; /* * Split the string into tokens the way the shell would. * Adapted shamelessly (but with enormous respect and gratitude) from * Perl 5.8.8's Test::ParseWords::old_shellwords function. */ public function shellsplit($text_p='') { $text = trim($text_p); $a_tokens = array(); /* * The regexes are fairly complex, so let's predefine them to keep * the logic readable. */ $p = array( /* * "-quoted string */ '^"(([^"\\\\]|\\\\.)*)"', /* * Unterminated "-quoted string */ '^"', /* * '-quoted string */ "^'(([^'" . '\\\\]|\\\\.)*)' . "'", /* * Unterminated '-quoted string */ "^'", /* * Explicit slosh followed by anything */ '^\\\\(.)', /* * String of non-whitespace, non-slosh, non-quote charactersa */ '^([^\s\\\\' . "'" . '"]+)', ); while ($text) { $field = ''; while (true) { if (preg_match('#' . $p[0] . '#', $text, $bits)) { $text = preg_replace('#' . $p[0] . '#', '', $text, 1); $snippet = preg_replace('#\\\\(.)#', '\1', $bits[1]); } else if (preg_match('#' . $p[1] . '#', $text)) { trigger_error("Unmatched double quote: $text\n", E_USER_WARNING); return array(); } else if (preg_match('#' . $p[2] . '#', $text, $bits)) { $text = preg_replace('#' . $p[2] . '#', '', $text); $snippet = preg_replace('#\\\\(.)#', '\1', $bits[1]); } else if (preg_match('#' . $p[3] . '#', $text)) { trigger_error("Unmatched single quote: $text\n", E_USER_WARNING); return array(); } else if (preg_match('#' . $p[4] . '#', $text, $bits)) { $text = preg_replace('#' . $p[4] . '#', '', $text, 1); $snippet = $bits[1]; } else if (preg_match('#' . $p[5] . '#', $text, $bits)) { $text = preg_replace('#' . $p[5] . '#', '', $text, 1); $snippet = $bits[1]; } else { $text = trim($text); break; } $field .= $snippet; } $a_tokens[] = $field; } return $a_tokens; } /* * Stuff to be added to the document header when we're doing an * admin/configuration panel. */ public function action_admin_header($theme) { $vars = Controller::get_handler_vars(); $js_xid2def = ''; if (($theme->page == 'plugins') && isset($vars['configure']) && ($this->plugin_id == $vars['configure'])) { Stack::add('admin_stylesheet', array($this->get_url() . '/macros.css', 'screen'), 'macros', array('admin')); $macros = DB::get_results('SELECT * FROM ' . DB::table('macro') . ' ORDER BY name ASC'); $js_xid2def .= "\n \$(document).ready(function(){\n" . " mDefs = [];\n" . " mDefs[0] = ['', false, false, 0, '', ''];\n"; foreach ($macros as $macro) { $xid = $macro->xid; $nargs = $macro->nargs; $enabled = $macro->enabled; $name = HTMLentities("'" . $macro->name . "'"); $desc = HTMLentities("'" . $macro->description . "'"); $def = HTMLentities("'" . $macro->definition . "'"); $container = $macro->container ? 'true' : 'false'; $eval = $macro->eval ? 'true' : 'false'; $js_xid2def .= " mDefs[$xid] = [" . $name . ', ' /* [0] */ . $enabled . ', ' /* [1] */ . $container . ', ' /* [2] */ . $eval . ', ' /* [3] */ . $nargs . ', ' /* [4] */ . $desc . ', ' /* [5] */ . $def /* [6] */ . "];\n"; } $js_xid2def .= " \$('#mName select')" . ".change(function(){\n" . " mNum = \$(this).val();\n" . " \$('#mEnabled input[type=\"checkbox\"]')" . ".attr('checked', mDefs[mNum][1]);\n" . " \$('#mDefinition input').val($('<input value=\"' + mDefs[mNum][6] + '\"/>').val());\n" . " \$('#mContainer input[type=\"checkbox\"]')" . ".attr('checked', mDefs[mNum][2]);\n" . " \$('#mEval input[type=\"checkbox\"]')" . ".attr('checked', mDefs[mNum][3]);\n" . " \$('#mNargs input[type=\"text\"]')" . ".val($('<input value=\"' + mDefs[mNum][4] + '\"/>').val());\n" . " \$('#mDescription input[type=\"text\"]')" . ".val($('<input value=\"' + mDefs[mNum][5] + '\"/>').val());\n" . " \$('#mDefinition input[type=\"text\"]')" . ".val($('<input value=\"' + mDefs[mNum][6] + '\"/o>').val())});\n" . " })\n"; Stack::add('admin_header_javascript', $js_xid2def, 'macros', 'admin'); } } public function action_update_check() { Update::add(self::PLUGIN_NAME, self::GUID, $this->info->version); } /* * Admin-type methods */ public function action_plugin_activation($file) { DB::register_table('macro'); /* * Create the database table, or upgrade it */ $dbms = DB::get_driver_name(); $sql = 'CREATE TABLE ' . DB::table('macro') . ' ' . '('; if ($dbms == 'sqlite') { $sql .= 'xid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, '; } else if ($dbms == 'mysql') { $sql .= 'xid INT(9) NOT NULL AUTO_INCREMENT, ' . 'UNIQUE KEY xid (xid), '; } else { $sql .= 'xid INT(9) NOT NULL AUTO_INCREMENT, ' . 'UNIQUE KEY xid (xid), '; } $sql .= 'name VARCHAR(255), ' . 'enabled INTEGER DEFAULT 1, ' . 'modified INTEGER, ' . 'description TEXT, ' . 'definition TEXT NOT NULL, ' . 'container INTEGER DEFAULT 0, ' . 'nargs INTEGER DEFAULT 0, ' . 'eval INTEGER DEFAULT 0' . ')'; if (! DB::dbdelta($sql)) { // Utils::debug(DB::get_errors()); } if ($file == str_replace('\\', '/', $this->get_file())) { ACL::create_token(self::PLUGIN_TOKEN, _t('Allow use of Macros plugin'), 'Category', false); $group = UserGroup::get_by_name('admin'); $group->grant(self::PLUGIN_TOKEN); } } public function action_plugin_deactivation($file) { if ($file == str_replace('\\', '/', $this->get_file())) { ACL::destroy_token(self::PLUGIN_TOKEN); } } /* * Add a configuration panel for us. */ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()) { $actions[] = _t('Configure'); } return $actions; } /* * And here's the actual configuration panel itself. */ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id == $this->plugin_id()) { $macros = DB::get_results('SELECT * FROM ' . DB::table('macro') . ' ORDER BY name ASC'); switch ($action) { case _t('Configure'): $ui = new FormUI(strtolower(get_class($this))); $ui->append('checkbox', 'nElideDisabled', '1', _t('Elide references to disabled macros')); $ui->append('fieldset', 'setAdd', 'Add a macro'); $setAdd = $ui->setAdd; /* * Fields to add a macro. */ $setAdd->append(new FormControlText('nName', null, _t('Macro name:'))); $setAdd->nName->class = 'block'; $setAdd->nName->value = ''; $setAdd->append('checkbox', 'nEnabled', '1', _t('Macro is enabled')); $setAdd->append(new FormControlText('nDescription', null, _t('Description:'))); $setAdd->nDescription->class = 'block'; $setAdd->nDescription->value = ''; $setAdd->nDescription->size = 50; $setAdd->append('textarea', 'nDefinition', null, _t('Macro definition:')); $setAdd->nDefinition->value = ''; // $setAdd->nDefinition->size = 64; $setAdd->append('fieldset', 'setAddAdvanced', 'Advanced options'); $setAdv = $setAdd->setAddAdvanced; $setAdv->append(new FormControlText('nNargs', '0', _t('Number of arguments:'))); $setAdv->nNargs->size = 2; $setAdv->nNargs->value = '0'; // <a class="help" href="http://ken.coar.org/habari/admin/plugins?configure=a51b1bc8&configaction=Configure&help=_help">?</a> $setAdv->append('checkbox', 'nContainer', '1', _t('Is a container (has start and end tags)')); $setAdv->append('checkbox', 'nEval', '1', _t('Evaluable (definition contains ' . 'PHP code to be evaluated)')); /* * Only allow editing and deletion if we already have * some macros defined. */ if ($n = count($macros)) { $anames = array('' => 0); $adefs = array(); foreach ($macros as $macro) { $anames[$macro->name] = $macro->xid; $adefs[$macro->name] = $macro->definition; } /* * First, the modification stuff. */ $ui->append('fieldset', 'setModify', 'Modify a macro'); $setModify = $ui->setModify; $setModify->append(new FormControlSelect('mName', null, _t('Select macro to modify'))); $setModify->mName->size = 1; $setModify->mName->options = array_flip($anames); $setModify->append('checkbox', 'mEnabled', '1', _t('Macro is enabled')); if ($aDefs[$setModify->mName->value]->enabled) { $setModify->mEnabled->checked = 'checked'; } $setModify->append(new FormControlText('mDescription', null, _t('Description:'))); $setModify->mDescription->class = 'block'; $setModify->mDescription->value = ''; $setModify->mDescription->size = 50; $setModify->append(new FormControlText('mDefinition', null, _t('Definition:'))); $setModify->mDefinition->class = 'block'; $setModify->mDefinition->value = ''; $setModify->mDefinition->size = 50; $setModify->append('fieldset', 'setModAdvanced', 'Advanced options'); $setAdv = $setModify->setModAdvanced; $setAdv->append('checkbox', 'mContainer', '1', _t('Is a container')); $setAdv->append('checkbox', 'mEval', '1', _t('Is evaluable')); $setAdv->append(new FormControlText('mNargs', null, _t('Argument count:'))); $setAdv->mNargs->size = 2; $setAdv->mNargs->value = '0'; /* * Now the deletion stuff. */ $ui->append('fieldset', 'setDelete', 'Delete macros'); $setDelete = $ui->setDelete; $setDelete->class = 'cbox-left'; foreach ($anames as $name => $xid) { if (! $xid) { continue; } $setDelete->append('checkbox', 'macro_' . $xid, $xid, $name); } } $ui->append('submit', 'save', 'Save'); $ui->on_success(array($this, 'handle_config_form')); $ui->out(); break; } } } /* * An Admin Form Hath Been Submitted-eth. */ public function handle_config_form($ui) { $macros = DB::get_results('SELECT * FROM ' . DB::table('macro') . ' ORDER BY name ASC'); $macroById = array(); foreach ($macros as $macro) { $macrosById[$macro->xid] = $macro; } $setAdd = $ui->setAdd; $setAddAdv = $setAdd->setAddAdvanced; $setMod = $ui->setModify; $setModAdv = $setMod->setModAdvanced; $setDel = $ui->setDelete; if ($name = $ui->nName->value) { $desc = $setAdd->nDescription->value; $desc = html_entity_decode($desc); $def = $setAdd->nDefinition->value; $def = html_entity_decode($def); $nargs = $setAddAdv->nNargs->value; $container = $setAddAdv->nContainer->value ? 1 : 0; $eval = $setAddAdv->nEval->value ? 1 : 0; DB::insert(DB::table('macro'), array('name' => $name, 'description' => $desc, 'definition' => $def, 'nargs' => $nargs, 'container' => $container, 'eval' => $eval)); // Utils::debug(DB::get_errors()); } /* * Modify an abbreviation. */ $xid = $setMod->mName->value; if ($xid) { $desc = $setMod->mDescription->value; $desc = html_entity_decode($desc); $def = $setMod->mDefinition->value; $def = html_entity_decode($def); $nargs = $setModAdv->mNargs->value; $container = $setModAdv->mContainer->value ? 1 : 0; $eval = $setModAdv->mEval->value ? 1 : 0; // Utils::debug(array($def, $prefix, $postfix, $abbrevById[$xid])); if (($def != $macrosById[$xid]->definition) || ($desc != $macrosById[$xid]->description) || ($nargs != $abbrevById[$xid]->nargs) || ($container != $macrosById[$xid]->container) || ($eval != $macrosById[$xid]->eval)) { DB::update(DB::table('macro'), array('definition' => $def, 'description' => $desc, 'nargs' => $nargs, 'container' => $container, 'eval' => $eval), array('xid' => $xid)); // Utils::debug(DB::get_errors()); } } /* * Delete some? */ $a_delboxes = $setDel->controls; foreach ($a_delboxes as $id => $formctl) { if ($formctl->value) { preg_match('/^macro_(\d+)$/', $id, $pieces); DB::delete(DB::table('macro'), array('xid' => $pieces[1])); // Utils::debug(DB::get_errors()); } } $ui->save; return false; } public function action_init() { DB::register_table('macro'); Stack::add('template_stylesheet', array($this->get_url() . '/macros.css', 'screen'), 'macros'); } /* * Do the actual replacement of any macros. Don't make any * changes to text inside tags! */ public function filter_post_content_out($content, $post) { $macros = DB::get_results('SELECT * FROM ' . DB::table('macro')); $content = " $content "; $redelim = Utils::regexdelim( $content ); /* * Save any markup tags so we don't insert into the * middle of one. */ $regex = $redelim . '(<[^!+][^>]*>)' . $redelim . 'siS'; $saved_markup = array(); while (preg_match($regex, $content, $matched)) { $saved_markup[] = $matched[1]; $pattern = sprintf('%s\Q%s\E%ss', $redelim, $matched[1], $redelim); $content = preg_replace($pattern, "<!-- SAVED_MARKUP -->" . count($saved_markup) . "<!-- /SAVED_MARKUP -->", $content); } $raw = $content; /* * Process the macros in turn. Restart from scratch after any * replacements, to allow inner references of one macro by another. */ while (true) { /* * Keep track of how many of the macros we've done. */ $mNum = 0; foreach ($macros as $macro) { $mNum++; $prefix = sprintf('%s\Q%s\E\s*\Q%s\E', $redelim, Macros::MARKER_OPEN, $macro->name); if ($macro->nargs) { $prefix .= '\s+(.*?)'; } $prefix .= sprintf('\s*\Q%s\E', Macros::MARKER_CLOSE); $postfix = $redelim . 's'; if ($macro->container) { $prefix = sprintf('%s(.*?)\Q%s\E\s*/%s\s*\Q%s\E', $prefix, Macros::MARKER_OPEN, $macro->name, Macros::MARKER_CLOSE); } $pattern = $prefix . $postfix; // Utils::debug('pattern=|' . $pattern . '|'); /* * If we don't have a match, move on to the next macro. */ if (! preg_match($pattern, $raw, $matched)) { continue; } /* * Position of the next matched group expression. */ $mPos = 1; /* * Got a match! Do it! Exactly what we do is dependent on the * macro definition.. */ $replacement = $macro->definition; if ($macro->nargs) { $args = array_slice($this->shellsplit($matched[$mPos++]), 0, $macro->nargs); $replacement = vsprintf($replacement, $args); } if ($macro->eval) { $replacement = eval('?' . '>' . $replacement); } $repregex = sprintf('%s\Q%s\E%sms', $redelim, $matched[0], $redelim); if ($macro->container) { /* * Do something special if we have a container * macro; the content is treated specially. */ } // Utils::debug(array($repregex, $replacement, $raw)); $raw = preg_replace($repregex, $replacement, $raw, 1); // Utils::debug(array($repregex, $replacement, $raw)); /* * Return to the outer loop (i.e., restart with the first * macro again, in case this insertion added some). */ break; } /* * Skip out if we've gone through all the macros. */ if ($mNum >= count($macros)) { break; } } /* * Done with the macros; now restore any saved markup. */ for ($i = 1; $i <= count($saved_markup); $i++) { $regex = sprintf('%s\Q<!-- SAVED_MARKUP -->' . '%s' . '<!-- /SAVED_MARKUP -->\E%ss', $redelim, $i, $redelim); $raw = preg_replace($regex, $saved_markup[$i - 1], $raw); } $content = trim($raw); return $content; } } /* * Local Variables: * mode: C * c-file-style: "bsd" * tab-width: 4 * indent-tabs-mode: nil * End: */ ?> <file_sep><?php class fluffytag extends Plugin { private $cache_name = 'fluffytag'; /** * Add update beacon support **/ public function action_update_check() { Update::add( 'FluffyTag', 'F1AC0F36-246D-11DE-B61E-0D8056D89593', $this->info->version ); } /** * Makes sure everything is setup proper. **/ public function action_plugin_activation( $file ) { if(Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__)) { if ( Options::get( 'fluffytag__num' ) == null ) { Options::set( 'fluffytag__num', 'true' ); } if ( Options::get( 'fluffytag__steps' ) == null ) { Options::set( 'fluffytag__steps', '10' ); } if ( Options::get( 'fluffytag__expire' ) == null ) { Options::set( 'fluffytag__expire', '36000000' ); // We're updating the cache everytime a post change... } } } public function action_plugin_deactivation( $file ) { if ( realpath( $file ) == __FILE__ ) { Cache::expire( $this->cache_name ); } } /** * Plugin init action, executed when plugins are initialized. */ public function action_init() { $this->add_template( 'fluffytag', dirname(__FILE__) . '/fluffytag.php' ); } /** * Add actions to the plugin page for this plugin * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id **/ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = 'Configure'; } return $actions; } /** * Executes when the admin plugins page wants to display the UI for a particular plugin action. * Displays the plugin's UI. * * @param string $plugin_id The unique id of a plugin * @param string $action The action to display **/ public function action_plugin_ui( $plugin_id, $action ) { // Display the UI for this plugin? if ( $plugin_id == $this->plugin_id() ) { // Depending on the action specified, do different things switch ( $action ) { case _t( 'Configure' ): $ui = new FormUI( get_class( $this ) ); $hide_tags = $ui->append( 'text', 'hide_tags', 'option:' . 'fluffytag__hide', _t( 'Tag(s) to be hidden (seperate with ",")' ) ); $steps = $ui->append( 'text', 'steps_tag', 'option:' . 'fluffytag__steps', _t( 'No. of steps (if you change this you will also need to change fluffytag.css accordingly)' ) ); $cache_expire = $ui->append( 'text', 'cache_expire', 'option:' . 'fluffytag__expire', _t( 'Time the cache should save result (sec)' ) ); $ui->append( 'submit', 'save', _t( 'Save' ) ); $ui->set_option( 'success_message', _t( 'Configuration saved' ) ); $ui->on_success( array( $this, 'updated_config' ) ); $ui->out(); break; case _t( 'Clear Cache' ): Cache::expire( $this->cache_name ); echo '<p>' . _t( 'Cache has been cleared.' ) . '</p>'; break; } } } public function updated_config( $ui ) { $ui->save(); Cache::expire( $this->cache_name ); return false; } public function theme_fluffytag($theme) { /*if ( Cache::has( $this->cache_name ) ) { $fluffy = Cache::get( $this->cache_name ); } else {*/ $fluffy = $this->build_cloud(); Cache::set( $this->cache_name, $fluffy, Options::get( 'fluffytag__expire' ) ); //} $theme->fluffy = $fluffy; return $theme->fetch( 'fluffytag' ); } private function get_hide_tag_list() { if ( '' != ( Options::get( 'fluffytag__hide' ) ) ) { return explode( ',', Options::get( 'fluffytag__hide' ) ); } else { return array(); } } public function action_template_header() { Stack::add( 'template_stylesheet', array( $this->get_url(true) . 'fluffytag.css', 'screen' ) , 'fluffytag' ); } /* * Based on the number of steps and tag max count do some magic. */ private function build_cloud() { $tags = Tag::get(); $max = Tags::max_count(); $hide = $this->get_hide_tag_list(); $tag_array = array(); $step = $max / Options::get( 'fluffytag__steps' ); foreach($tags as $tag) { if( !( empty( $tag->slug ) || in_array( $tag->slug, $hide ) || in_array( $tag->tag, $hide ) ) ) $tag_array[] = array( 'tag' => $tag->tag, 'slug' => $tag->slug, 'step' => ceil( $tag->count / $step ) ); } //print_r( $tag_array ); return $tag_array; } /* * Lets make sure we're always up to date. */ public function action_post_insert_after( $post ) { if ( Post::status_name( $post->status ) == 'published' ) { Cache::expire( $this->cache_name ); } } public function action_post_update_after( $post ) { if ( Post::status_name( $post->status ) == 'published' ) { Cache::expire( $this->cache_name ); } } public function action_post_delete_after( $post ) { if ( Post::status_name( $post->status ) == 'published' ) { Cache::expire( $this->cache_name ); } } public function action_tag_insert_after( $tag ) { Cache::expire( $this->cache_name ); } public function action_tag_update_after( $tag ) { Cache::expire( $this->cache_name ); } public function action_tag_delete_after( $tag ) { Cache::expire( $this->cache_name ); } } ?> <file_sep><?php class Code_Escape extends Plugin { const VERSION = '0.1'; public function info ( ) { return array ( 'name' => 'Code Escape', 'url' => 'http://habariproject.org', 'author' => 'The Habari Community', 'authorurl' => 'http://habariproject.org', 'version' => self::VERSION, 'description' => 'Runs htmlspecialchars() on any &lt;code&gt; blocks in your post.', 'license' => 'Apache License 2.0' ); } public function filter_post_content_out ( $content, $post ) { $content = preg_replace_callback('/<code>(.*?)<\/code>/s', array( 'self', 'escape_code' ), $content); return $content; } public static function escape_code ( $matches ) { $string = $matches[1]; $string = htmlspecialchars( $string ); $string = '<code>' . $string . '</code>'; return $string; } public function action_update_check ( ) { Update::add( 'Code Escape', '3ede3d2c-cb4f-4a37-9ac5-c5918fef7257', $this->info->version ); } } ?> <file_sep><?php include 'header.php'; ?> <div id="content"> <h2 class="title"><?php _e('Not Found'); ?></h2> <div class="entry"> <p><?php _e('The page you were looking for was not found.'); ?></p> </div> </div> <?php include 'footer.php'; ?><file_sep><!-- comments --> <div id="comments"> <?php if ($post->comments->moderated->count) { ?> <h2><?php printf(_n('%1$s Response', '%1$s Responses', $post->comments->moderated->count, 'demorgan'), '<span class="comment-count">' . $post->comments->moderated->count . '</span>'); ?></h2> <?php //Show Comments if ($post->comments->comments->moderated->count) { ?> <ul id="comment-list"> <?php $i = 1; foreach ($post->comments->comments->moderated as $comment) { $class = 'comment'; if ($comment->status === Comment::STATUS_UNAPPROVED) { $class .= '-unapproved'; } //Using email to identify author if ($comment->email === $post->author->email) { $class .= ' author'; } else { $class .= ' guest'; } //Even or Odd $class .= ($i % 2 === 0) ? ' even' : ' odd' ; $i++; ?> <li id="comment-<?php echo $comment->id; ?>" class="<?php echo $class; ?>"> <div class="comment-content"> <?php echo $comment->content_out; ?> </div> <div class="comment-author vcard"> <?php $theme->gravatar($comment); ?> <?php if ($comment->url) { ?> <a class="url" href="<?php echo $comment->url_out; ?>" rel="external"> <?php } ?> <span class="fn n"><?php echo $comment->name; ?></span> <?php if ($comment->url) { ?> </a> <?php } ?> <?php _e('on', 'demorgan'); ?> <a class="comment-permalink" href="<?php echo $post->permalink; ?>#comment-<?php echo $comment->id; ?>" title="<?php _e('Permanent Link to this comment', 'demorgan'); ?>" rel="bookmark"> <abbr class="comment-date published" title="<?php echo $comment->date->out(HabariDateTime::ISO8601); ?>"><?php echo $comment->date->out('F j, Y ‒ g:i a'); ?><?php if ($comment->status === Comment::STATUS_UNAPPROVED) { ?> <em><?php _e('In moderation', 'demorgan'); ?></em><?php } ?></abbr> </a> </div> </li> <?php } ?> </ul> <?php } //Show Pingbacks if ($post->comments->pingbacks->approved->count) { ?> <ul id="pingback-list"> <?php foreach ($post->comments->pingbacks->approved as $pingback) { ?> <li id="pingback-<?php echo $pingback->id; ?>" class="pingback"> <a href="<?php echo $pingback->url; ?>" rel="external"><?php echo $pingback->name; ?></a> <?php _e('on', 'demorgan'); ?> <a class="pingback-permalink" href="<?php echo $post->permalink; ?>#pingback-<?php echo $pingback->id; ?>" title="<?php _e('Permanent Link to this pingback', 'demorgan'); ?>" rel="bookmark"> <abbr class="pingback-date published" title="<?php echo $pingback->date_iso; ?>"><?php echo $pingback->date_out; ?></abbr> </a> </li> <?php } ?> </ul> <?php } } ?> </div> <!-- /comments --> <?php if (!$post->info->comments_disabled) { $theme->display('commentform'); } ?> <file_sep> </div> <div id="footer"> <?php Options::out('title'); _e(' is powered by'); ?> <a href="http://www.habariproject.org/" title="Habari">Habari</a> and <a rel="nofollow" href="http://wiki.habariproject.org/en/Available_Themes#Georgia">Georgia</a><br> <a href="<?php URL::out( 'atom_feed', array( 'index' => '1' ) ); ?>">Atom Entries</a> and <a href="<?php URL::out( 'atom_feed_comments' ); ?>">Atom Comments</a> <?php $theme->footer(); ?> </div> </div> <?php // Uncomment this to view your DB profiling info // include 'db_profiling.php'; ?> </body> </html><file_sep><?php /** * Twiple! Tweetback * adding Twiple! Tweetback to your posts. * * @package twiple_tweetback * @version $Id$ * @author ayunyan <<EMAIL>> * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link http://ayu.commun.jp/habari-twiple-tweetback * @link http://twiple.jp/ */ class TwipleTweetback extends Plugin { /** * plugin information * * @access public * @retrun void */ public function info() { return array( 'name' => 'Twiple! Tweetback', 'version' => '0.1', 'url' => 'http://ayu.commun.jp/habari-twiple-tweetback', 'author' => 'ayunyan', 'authorurl' => 'http://ayu.commun.jp/', 'license' => 'Apache License 2.0', 'description' => 'adding Twiple! Tweetback to your posts.', 'guid' => '42604d65-e6ea-11dd-bd4c-001b210f913f', ); } /** * action: plugin_activation * * @access public * @param string $file * @return void */ public function action_plugin_activation($file) { if (Plugins::id_from_file($file) != Plugins::id_from_file(__FILE__)) return; Options::set('twiple_tweetback__auto_insert', 1); Options::set('twiple_tweetback__default_style', 1); Options::set('twiple_tweetback__limit', 30); Options::set('twiple_tweetback__load_message', ''); Options::set('twiple_tweetback__notweets_message', ''); } /** * action: init * * @access public * @return void */ public function action_init() { $this->load_text_domain('twiple_tweetback'); } /** * action: update_check * * @access public * @return void */ public function action_update_check() { Update::add($this->info->name, $this->info->guid, $this->info->version); } /** * action: plugin_ui * * @access public * @param string $plugin_id * @param string $action * @return void */ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id != $this->plugin_id()) return; if ($action == _t('Configure')) { $form = new FormUI(strtolower(get_class($this))); $form->append('checkbox', 'auto_insert', 'twiple_tweetback__auto_insert', _t('Auto Insert:', 'twiple_tweetback')); $form->append('checkbox', 'default_style', 'twiple_tweetback__default_style', _t('Default Style:', 'twiple_tweetback')); $limit = $form->append('text', 'limit', 'twiple_tweetback__limit', _t('Display Limit: ', 'twiple_tweetback')); $limit->add_validator('validate_regex', '/^[0-9]+$/'); $form->append('text', 'load_message', 'twiple_tweetback__load_message', _t('Loading Message: ', 'twiple_tweetback')); $form->append('text', 'notweets_message', 'twiple_tweetback__notweets_message', _t('No Tweets Message: ', 'twiple_tweetback')); $form->append('submit', 'save', _t('Save')); $form->out(); } } /** * filter: plugin_config * * @access public * @return array */ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()) { $actions[]= _t('Configure'); } return $actions; } /** * action: template_header * * @access public * @return void */ public function action_template_header($theme) { if ($theme->request->display_entry == true || $theme->request->display_page == true) { $load_message = Options::get('twiple_tweetback__load_message'); $notweets_message = Options::get('twiple_tweetback__notweets_message'); ?> <script type="text/javascript" src="http://static.twiple.jp/js/tweetback.js"></script> <script type="text/javascript"> tweetback.options.default_style = <?php Options::out('twiple_tweetback__default_style'); ?>; tweetback.options.limit = <?php Options::out('twiple_tweetback__limit'); ?>; <?php if (!empty($load_message)): ?> tweetback.options.load_message = '<?php echo htmlspecialchars($load_message, ENT_QUOTES); ?>'; <?php endif; ?> <?php if (!empty($notweets_message)): ?> tweetback.options.notweets_message = '<?php echo htmlspecialchars($notweets_message, ENT_QUOTES); ?>'; <?php endif; ?> </script> <?php } } /** * filter: post_content_out * * @access public * @return string */ public function filter_post_content_out($content, $post) { if (Options::get('twiple_tweetback__auto_insert') == 1) $content .= '<div id="tweetback"></div>'; return $content; } } ?><file_sep><html> <head><title>Habari ScratchPad</title></head> <body> <?php $form->out(); ?> </body> </html> <file_sep><?php /* * Modified / fixed from the original by <NAME> (a.k.a. rob1n) http://robinadr.com/ * http://robinadr.com/projects/footnotes * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ class Footnotes extends Plugin { const VERSION = '2.4'; private $footnotes; private $current_id; private $post; const FLICKR_KEY = '22595035de2c10ab4903b2c2633a2ba4'; public function info() { return array( 'name' => 'Footnotes', 'url' => 'http://habariproject.org', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org', 'version' => self::VERSION, 'description' => 'Use footnotes in your posts. Syntax: &lt;footnote&gt;Your footnote&lt;/footnote&gt;, wherever you want the reference point to be. Everything is done automatically. You can also cite a source using a url attribute like this &lt;footnote url="http://foo.bar/foo/"&gt;Title&lt;/footnote&gt;. Also now supports ((WP-Footnotes syntax, for compatibility.)).', 'license' => 'Apache License 2.0' ); } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t('Configure'); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure') : $form = new FormUI( strtolower( get_class( $this ) ) ); $form->append( 'static', 'why_suppress', _t('<small>If you suppress the list, you can add them manually using the $post->footnotes array.</small>') ); $form->append( 'checkbox', 'suppress_list', 'footnotes__suppress_list', _t('Don\'t append the footnote list to posts') ); $form->append( 'submit', 'save', _t('Save') ); $form->out(); break; } } } public function filter_post_content( $content, $post ) { // If we're on the publish page, replacement will be destructive. // We don't want that, so return here. $controller = Controller::get_handler(); if ( isset( $controller->action ) && $controller->action == 'admin' && isset($controller->handler_vars['page']) && $controller->handler_vars['page'] == 'publish' ) { return $content; } // If there are no footnotes, save the trouble and just return it as is. if ( strpos( $content, '<footnote' ) === false && strpos( $content, ' ((' ) === false ) { return $content; } $this->footnotes = array(); $this->current_id = $post->id; $this->post = $post; $return = preg_replace_callback( '/(?:<footnote(\s+url=[\'"].*[\'"])?>|\s\(\()(.*)(?:\)\)|<\/footnote>)/Us', array($this, 'add_footnote'), $content ); if ( count( $this->footnotes ) == 0 ) { return $content; } $post->footnotes = $this->footnotes; $append = ''; if ( !Options::get('footnotes__suppress_list') ) { $append.= '<ol class="footnotes">' . "\n"; foreach ( $this->footnotes as $i => $footnote ) { // if there was a url if ( is_array($footnote) ) { switch ( $footnote['type'] ) { case "flickr": $append .= '<li id="footnote-' . $this->current_id . '-' . $i . '" class="cite '. $footnote['type'] . '">'; $append .= '<a href="' . $footnote['photo']['url'] . '" title="' . $footnote['photo']['title'] . '">Photo</a>'; $append .= ' by <a href="' . $footnote['owner']['url'] . '" title="' . $footnote['owner']['name'] . '">' . $footnote['owner']['username'] . '</a>'; $append .= ' on <a href="http://flickr.com">Flickr</a>'; $append .= ' <a href="#footnote-link-' . $this->current_id . '-' . $i . '">&#8617;</a>'; $append .= "</li>\n"; break; case "vanilla": $append .= '<li id="footnote-' . $this->current_id . '-' . $i . '">'; $append .= '<a href="' . $footnote['url'] . '" title="' . $footnote['text'] . '">' . $footnote['text'] . '</a>'; $append .= ' <a href="#footnote-link-' . $this->current_id . '-' . $i . '">&#8617;</a>'; $append .= "</li>\n"; break; } } else { $append .= '<li id="footnote-' . $this->current_id . '-' . $i . '">'; $append .= $footnote; $append .= ' <a href=" ' . URL::get('display_entry', array('slug' => $this->post->slug)) . '#footnote-link-' . $this->current_id . '-' . $i . '">&#8617;</a>'; $append .= "</li>\n"; } } $append .= "</ol>\n"; } return $return . $append; } private function add_footnote( $matches ) { $url = $matches[1]; $footnote = $matches[2]; if ( $url != '' ) { $url = preg_replace('/\s+url=[\'"](.*)[\'"]/', '$1', $url); $url_parts = array(); $info = array(); // It's a link to a flickr photo if ( preg_match('/http:\/\/flickr.com\/photos\/(\w*)\/(\d*)/', $url, $url_parts) ) { $user = $url_parts[1]; $photo = $url_parts[2]; if ( Cache::has('footcite__' . $photo) ) { $fetch = Cache::get('footcite__' . $photo); } else { $fetch = RemoteRequest::get_contents('http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key='.self::FLICKR_KEY.'&photo_id='.$photo); Cache::set('footcite__' . $photo, $fetch); } $xml = new SimpleXMLElement($fetch); $info['type'] = 'flickr'; $info['photo'] = array( 'title' => (string) $xml->photo->title, 'id' => $photo, 'url' => (string) $xml->photo->urls->url[0] ); $info['owner'] = array( 'username' => (string) $xml->photo->owner['username'], 'name' => (string) $xml->photo->owner['realname'], 'id' => (string) $xml->photo->owner['nsid'], 'url' => 'http://www.flickr.com/photos/' . $user . '/' ); } else { $info['type'] = 'vanilla'; $info['url'] = $url; $info['text'] = $footnote; } $footnote = $info; } $i = count( $this->footnotes ) + 1; $this->footnotes[$i] = $footnote; $id = $this->current_id . '-' . $i; return '<sup class="footnote-link" id="footnote-link-' . $id . '"><a href="' . URL::get('display_entry', array('slug' => $this->post->slug)) . '#footnote-' . $id . '" rel="footnote">' . $i . '</a></sup>'; } public function action_update_check () { Update::add( 'Footnotes', '021e0510-a3cc-4a9b-9faa-193596f04dcb', self::VERSION ); } } ?> <file_sep><?php /** * Linkoid Plugin * **/ class Linkoid extends Plugin { /** * function info * Returns information about this plugin * @return array Plugin info array **/ function info() { return array ( 'name' => 'Linkoid', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'version' => '1.0', 'description' => 'Displays posts that are tagged with a specific tag in a different place using a separate template', 'license' => 'Apache License 2.0', ); } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Linkoid', '34257e00-3942-11dd-ae16-0800200c9a66', $this->info->version ); } /** * Add actions to the plugin page for this plugin * * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id */ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()){ $actions[] = 'Configure'; } return $actions; } /** * Respond to the user selecting an action on the plugin page * * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook */ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id == $this->plugin_id()){ switch ($action){ case 'Configure' : $ui = new FormUI(strtolower(get_class($this))); $links = $ui->append('text', 'count', 'linkoid__count', 'Number of items to be shown'); //required $links->add_validator( 'validate_required' )->add_validator( 'validate_regex', '%^[1-9][0-9]*$%', 'Number of items shown must be a number; 1 or more.' ); $tag_control = $ui->append('select', 'show', 'linkoid__show', 'Tag that will be shown via linkoid command'); $tags = DB::get_results( 'SELECT tag_slug, tag_text FROM {tags} ORDER BY tag_text ASC' ); $options = array(); foreach($tags as $tag) { $options[$tag->tag_slug] = $tag->tag_text; } $tag_control->options = $options; $ui->append( 'submit', 'save', _t('Save') ); $ui->out(); break; } } } /** * Respond to call to $theme->linkoid() in template * * @param string $return The return value to the template function (passed through other potential plugin calls) * @param Theme $theme The theme object * @param string $tag An optional tag to use instead of the one defined in the plugin options. * @return string The return value to the template function */ public function theme_linkoid( $theme, $tag = null ) { if(!isset($tag)) { $tag = Options::get( 'linkoid__show' ); } $linkoids = Posts::get(array('tag_slug'=>$tag, 'limit'=>Options::get( 'linkoid__count' ) ) ); $theme->linkoids = $linkoids; return $theme->fetch( 'linkoid' ); } /** * On plugin init, add the template included with this plugin to the availalbe templates in the theme */ public function action_init() { $this->add_template('linkoid', dirname(__FILE__) . '/linkoid.php'); } /** * Prevent posts with the selected tag from appearing anywhere but the tag listing and on single post requests * * @param array $where_filters An array of parameters being sent to Posts::get() * @return array The potentially altered parameter set. */ public function filter_template_where_filters( $where_filters ) { if( ! (isset($where_filters['tag']) || isset($where_filters['tag_slug']) || isset($where_filters['slug'])) ) { $where_filters['not:tag'] = Options::get('linkoid__show'); } return $where_filters; } } ?> <file_sep><?php class Discussit extends Plugin { static $regex_name= '/@([A-Za-z0-9]+)/'; static $regex_url= '/@\<a href="(.+)#comment-([0-9]+)"\>([A-Za-z0-9]+)\<\/a\>/'; /** * Add update beacon support **/ public function action_update_check() { Update::add( $this->info->name, '95d9b76a-ca6c-f5d4-9551-e8c0b020e097', $this->info->version ); } /** * Find referenced comments */ private static function get_parents($comment, $content, $comments) { $parents= array(); $params= array( 'post_id' => $comment->post->id, 'limit' => 1, 'orderby' => 'date DESC', 'where' => array('date < ' . $comment->date->sql) ); // Check for name preg_match_all(self::$regex_name, $content, $matches); $matches= $matches[1]; foreach($matches as $name) { $matched_comments= Comments::get(array_merge($params, array('criteria_fields' => array('name'), 'criteria' => $name))); if(count($matched_comments) > 0) { $parents[]= $matched_comments[0]; } } // Check for url $matches= array(); preg_match_all(self::$regex_url, $content, $matches); $ids= $matches[2]; foreach($ids as $id) { $matched_comments= Comments::get(array_merge($params, array('id' => $id))); if(count($matched_comments) > 0) { $parents[]= $matched_comments[0]; } } return $parents; } /** * Remove all relationships */ private function remove_relationships($comment, $parents) { foreach($parents as $parent) { if($parent->info->children) { $children= unserialize($parent->info->children); unset($children[$comment->id]); $parent->info->children= serialize($children); $parent->update(); } } } /** * Create relationships as needed */ private function create_relationships($comment, $parents, $update = true) { $parents_save= array(); foreach($parents as $parent) { if($parent->info->children) { $children= unserialize($parent->info->children); $children[$comment->id]= $comment->id; } else { $children= array($comment->id => $comment->id); } $parent->info->children= serialize($children); $parent->update(); $parents_save[$parent->id]= $parent->id; } $comment->info->parents= serialize($parents_save); if($update) { $comment->update(); } } /** * Test old comments for relationships * This will take a loooooong time */ public function action_plugin_activation( $plugin_file ) { $comments= Comments::get(array('nolimit' => true)); foreach($comments as $comment) { $parents= self::get_parents($comment, $comment->content, $comment->post->comments); $this->create_relationships($comment, $parents); } } /** * Remove all comment relationships */ public function action_plugin_deactivation( $plugin_file ) { DB::delete(DB::table('commentinfo'), array('name' => 'parents')); DB::delete(DB::table('commentinfo'), array('name' => 'children')); } /** * Catch new comments **/ public function action_comment_insert_after($comment) { $parents= self::get_parents($comment, $comment->content, $comment->post->comments); $this->create_relationships($comment, $parents); } /** * Clear and update relationships */ public function action_comment_update_content($comment, $old, $new) { if(is_object($new)) { $new= $new->value; } // Severe old ties $this->remove_relationships($comment, $comment->parents); // Create new ties $parents= self::get_parents($comment, $new, $comment->post->comments); $this->create_relationships($comment, $parents, false); } /** * Magically enable use of parents */ public function filter_comment_parents($value, $comment) { $parent_ids= unserialize($comment->info->parents); if(!is_array($parent_ids)) { return array(); } $parents= Comments::get(array('id' => $parent_ids, 'nolimit' => true, 'orderby' => 'date ASC')); return $parents; } /** * Magically enable use of children */ public function filter_comment_children($value, $comment) { $child_ids= unserialize($comment->info->children); if(!is_array($child_ids)) { return array(); } $children= Comments::get(array('id' => $child_ids, 'nolimit' => true, 'orderby' => 'date ASC')); return $children; } /** * Linkify parents and children */ public function filter_comment_content_out($content, $comment) { preg_match_all(self::$regex_name, $content, $matches); $matches= $matches[1]; foreach($matches as $name) { $params= array( 'post_id' => $comment->post->id, 'limit' => 1, 'orderby' => 'date DESC', 'where' => array('date < ' . $comment->date->sql), 'criteria_fields' => array('name'), 'criteria' => $name ); $matched_comments= Comments::get($params); if(count($matched_comments) > 0) { $parent= $matched_comments[0]; $content= str_replace('@' . $name, '@<a href="' . $comment->post->permalink . '#comment-' . $parent->id . '" title="This comment is in response to ' . $parent->name . '">' . $name . '</a>', $content); } } return $content; } /** * Show stuff in the comment form */ public function action_form_comment_edit($form, $comment) { $form->comment_controls->append('fieldset', 'discussion_tab', _t('Discussion')); $discussion = $form->discussion_tab->append('wrapper', 'discussion'); $discussion->class = 'container'; if(count($comment->parents) > 0) { $parents= array(); foreach($comment->parents as $parent) { $parents[]= '<a href="' . URL::get('admin', 'page=comment&id=' . $parent->id) . '">' . $parent->name . '</a>'; } $str= 'This comment is descended from comments by ' . Format::and_list($parents) . '.'; } else { $str= 'This comment has no parents.'; } $discussion->append('static', 'parents', '<div class="container"><p class="pct25">'._t('Parents').'</p><p>' . $str . '</p></div><hr />'); if(count($comment->children) > 0) { $children= array(); foreach($comment->children as $child) { $children[]= '<a href="' . URL::get('admin', 'page=comment&id=' . $child->id) . '">' . $child->name . '</a>'; } $str= 'There are children of this comment by ' . Format::and_list($children) . '.'; } else { $str= 'This comment has no children.'; } $discussion->append('static', 'children', '<div class="container"><p class="pct25">'._t('Children').'</p><p>' . $str . '</p></div><hr />'); } } ?><file_sep><?php // Apply Format::tag_and_list() to post tags... Format::apply( 'tag_and_list', 'post_tags_out' ); // Apply Format::nice_date() to post date... Format::apply( 'nice_date', 'post_pubdate_out', 'F j, Y g:ia' ); // Limit post length on the home page to 1 paragraph or 100 characters Format::apply( 'autop', 'post_content_excerpt' ); Format::apply_with_hook_params( 'more', 'post_content_excerpt', '', 100, 1 ); // Apply Format::nice_date() to post and comment date... Format::apply( 'nice_date', 'post_pubdate_out', 'F j, Y g:ia' ); Format::apply( 'nice_date', 'comment_Xdate_out', 'F j, Y g:ia' ); define( 'THEME_CLASS', 'wings' ); class wings extends Theme { public function add_template_vars() { if( !$this->template_engine->assigned( 'pages' ) ) { $this->assign('pages', Posts::get( array( 'content_type' => 'page', 'status' => Post::status('published'), 'nolimit' => 1 ) ) ); } } } ?> <file_sep><?php class MagicTags extends Plugin { /** * function info * Returns information about this plugin * @return array Plugin info array **/ function info() { return array ( 'name' => 'Magic Tags', 'url' => 'http://habariproject.org', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org', 'version' => '0.1', 'description' => 'Hides tags begining with "@" from display', 'license' => 'Apache License 2.0', ); } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'MagicTags', '1455ba80-3bcd-11dd-ae16-0800200c9a66', $this->info->version ); } /** * filters display of tags for posts to hide any that begin with "@" from display **/ public function filter_post_tags_out( $tags ) { $tags= array_filter($tags, create_function('$a', 'return $a{0} != "@";')); $tags= Format::tag_and_list($tags); return $tags; } /** * Displays a list of all tags used on the site except those begining with "@" as a comma seperated linked list. **/ public function magic_site_tags() { $tagcount= 0; foreach(DB::get_results('SELECT * FROM ' . DB::table('tags'). ' ORDER BY tag_text ASC') as $tag) { if (substr($tag->tag_text, 0, 1)== "@") {continue;} if ($tagcount!= 0) {echo ", ";} echo "<a href=\"" . URL::get('display_posts_by_tag', 'tag=' . $tag->tag_slug) . "\">{$tag->tag_text}</a>"; $tagcount++; } } } ?> <file_sep><?php /** * ThemeSwitcher - Allows visitors to change the theme of the site. * * Usage: http://domain.com/?theme_dir=themedir or * add <?php $theme->switcher(); ?> somewere. * * */ class ThemeSwitcher extends Plugin { // True if template was shown, false otherwise private $shown= false; /** * function info * Returns information about this plugin * @return array Plugin info array **/ function info() { return array ( 'name' => 'ThemeSwitcher', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'version' => '1.1', 'description' => 'Allows visitors to change the theme of the site.', 'license' => 'Apache License 2.0', 'copyright' => '2008' ); } function action_init() { if ( !empty($_GET['theme_dir'] ) || !empty( $_POST['theme_dir'] ) ) { $new_theme_dir= empty( $_GET['theme_dir'] ) ? $_POST['theme_dir'] : $_GET['theme_dir']; $all_themes= Themes::get_all(); if ( array_key_exists( $new_theme_dir, $all_themes ) ) { if ( !isset($_COOKIE['theme_dir'] ) || ( isset($_COOKIE['theme_dir'] ) && ( $_COOKIE['theme_dir'] != $new_theme_dir ) ) ) { $_COOKIE['theme_dir'] = $new_theme_dir; // Without this, the cookie isn't get in time to change the theme NOW. setcookie( 'theme_dir', $new_theme_dir ); } } } $this->add_template( 'switcher', dirname( __FILE__ ) . '/themeswitcher.php' ); } /** * Sets default to always show themeswitcher in footer if not using $theme->swithcer(); **/ public function action_plugin_activation( $file ) { if(Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__)) { if ( Options::get( 'themeswitcher__show' ) == null ) { Options::set( 'themeswitcher__show', 1 ); } } } /** * Call $theme->switcher() in your theme to display the template where you want. */ function theme_switcher( $theme ) { if (!$this->shown) { $this->shown= true; return $theme->fetch('switcher'); } } /** * Failsafe, if $theme->switcher() was not called, display the template in the footer. * If you enabled it. */ function theme_footer( $theme ) { if (!$this->shown && Options::get( 'themeswitcher__show')) { $this->shown= true; return $theme->fetch('switcher'); } } function filter_option_get_value($value, $name) { if (($name == 'theme_dir') && isset($_COOKIE['theme_dir'])) { return $_COOKIE['theme_dir']; } else { return $value; } } /** * Add our menu to the FormUI for plugins. * * @param array $actions Array of menu items for this plugin. * @param string $plugin_id A unique plugin ID, it needs to match ours. * @return array Original array with our added menu. */ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id ) { $actions[] = 'Configure'; } return $actions; } /** * Handle calls from FormUI actions. * Show the form to manage the plugin's options. * * @param string $plugin_id A unique plugin ID, it needs to match ours. * @param string $action The menu item the user clicked. */ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id ) { switch ( $action ) { case 'Configure': $themes = array_keys( Themes::get_all_data() ); $themes = array_combine( $themes, $themes ); $ui = new FormUI( 'themeswitcher' ); $ts_s = $ui->append( 'select', 'selected_themes', 'themeswitcher__selected_themes', 'Select themes to offer:' ); $ts_s->multiple= true; $ts_s->options =$themes; $ts_y = $ui->append( 'select', 'show', 'themeswitcher__show', _t('If not showing with $theme->switcher() always show in footer: ') ); $ts_y->options = array( '0' => _t('No'), '1' => _t('Yes') ); $ui->append( 'submit', 'save', 'Save' ); $ui->out(); break; } } } /** * Fail-safe method to force options to be saved in Habari's options table. * * @return bool Return true to force options to be saved in Habari's options table. */ public function save_options( $ui ) { return true; } } ?><file_sep><h3>Tag Cloud</h3> <ul><li><?php echo $content->cloud; ?></li></ul> <file_sep><?php class PostURL extends Plugin { public function action_form_publish($form, $post) { if($form->content_type->value == Post::type('entry') || $form->content_type->value == Post::type('page')) { $form->append('text', 'url', 'null:null', _t('URL'), 'admincontrol_text'); $form->url->tabindex = 2; $form->url->value = $post->info->url; $form->url->move_after($form->title); } } function action_publish_post($post, $form) { if($post->content_type == Post::type('entry') || $post->content_type == Post::type('page')) { $post->info->url = $form->url->value; } } public function filter_post_permalink($permalink,$post) { if(is_null($post->info->url) || $post->info->url=='') { return $permalink; } else { return $post->info->url; } } } ?> <file_sep><?php class AtomIcon extends Plugin { const PLUGIN_TOKEN = '<PASSWORD>'; /** * Do any wrapper-like things to the Atom feed proper. * @param SimpleXMLElement $xml the Atom feed document * @return SimpleXMLElement the modified Atom feed document */ public function action_atom_create_wrapper( $xml ) { if ($iconurl = Options::get('atomicon_iconurl')) { $xml->addChild('icon', $iconurl); } return $xml; } /* * Admin-type methods */ public function action_plugin_activation($file) { if ($file == str_replace('\\', '/', $this->get_file())) { ACL::create_token(self::PLUGIN_TOKEN, _t('Allow use of AtomIcon plugin'), 'Category', false); $group = UserGroup::get_by_name('admin'); $group->grant(self::PLUGIN_TOKEN); } } public function action_plugin_deactivation($file) { if ($file == str_replace('\\', '/', $this->get_file())) { ACL::destroy_token(self::PLUGIN_TOKEN); } } /* * Add a configuration panel for us. */ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()) { $actions[] = _t('Configure'); } return $actions; } /* * And here's the actual configuration panel itself. */ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id == $this->plugin_id()) { switch ($action) { case _t('Configure'): $ui = new FormUI(strtolower(get_class($this))); $ui->append('text', 'iconurl', 'option:atomicon_iconurl', _t('Feed icon URL:')); $ui->iconurl->size = 64; $ui->append('submit', 'save', 'Save'); $ui->out(); break; } } } } /* * Local Variables: * mode: C * c-file-style: "bsd" * tab-width: 4 * indent-tabs-mode: nil * End: */ ?> <file_sep> </div> <div class="right_content" id="sidebar"> <?php Plugins::act( 'theme_sidebar_top' ); ?> <div class="block" id="recent_comments"> <h3><span>Recent comments</span></h3> <ul> <?php foreach($recent_comments as $recent_comment): ?> <li><a href="<?php echo $recent_comment->post->permalink; ?>"><?php echo $recent_comment->name; ?></a></li> <?php endforeach; ?> </ul> </div> <div class="block" id="flickr"> <h3><a href="http://www.flickr.com/photos/theundersigned/">Flickr photostream</a></h3> <div class="images clearfix"> <script type="text/javascript" src="http://www.flickr.com/badge_code_v2.gne?count=9&amp;display=latest&amp;size=s&amp;layout=x&amp;source=user&amp;user=35634769@N00"></script> </div> </div> <?php $theme->switcher(); ?> <?php $theme->show_blogroll(); ?> <?php $theme->twitter(); ?> <div class="block" id="recent_posts"> <h3><span>Recent posts</span></h3> <ul> <?php foreach($recent_posts as $recent_post): ?> <li><a href="<?php echo $recent_post->permalink; ?>"><?php echo $recent_post->title; ?></a></li> <?php endforeach; ?> </ul> </div> <div class="block" id="login"> <h3><span>User</span></h3> <?php include 'loginform.php'; ?> </div> <?php Plugins::act( 'theme_sidebar_bottom' ); ?> </div> </div><file_sep><?php class Thickbox extends Plugin { /** * Required Plugin Informations */ public function info() { return array( 'name' => 'Thickbox', 'version' => '3.1', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Adds Thickbox functionality to your theme.', 'copyright' => '2009' ); } /** * Adds needed files to the theme stacks (javascript and stylesheet) */ public function action_init() { Stack::add( 'template_header_javascript', Site::get_url('scripts') . '/jquery.js', 'jquery' ); Stack::add( 'template_header_javascript', Site::get_url('user') . '/plugins/thickbox/thickbox-compressed.js', 'thickbox-js' ); Stack::add( 'template_stylesheet', array( Site::get_url('user') . '/plugins/thickbox/thickbox.css', 'screen,projector'), 'thickbox-css' ); } /** * Add help text to plugin configuration page **/ public function help() { $help = _t( 'There is no configuration for this plugin. Once this plugin is activated, add <code>class="thickbox"</code> to the link of an image file to open it in a hybrid modal box. More information and advanced instructions are available at the <a href="http://jquery.com/demo/thickbox/" title="ThickBox 3.1 Documentation and Examples">jQuery Demo page</a>.' ); return $help; } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Thickbox', '5e276e9e-c7ce-4010-a979-42580feefdd9', $this->info->version ); } } ?> <file_sep><?php /** * Lockdown plugin */ class LockdownPlugin extends Plugin { /** * Prevent users who are the demo user from being deleted * * @param boolean $allow true to allow the deletion of this user * @param User $user The user object requested to delete * @return boolea true to allow the deletion of this user, false to deny */ function filter_user_delete_allow( $allow, $user ) { if($user->username == 'demo') { Session::notice('To maintain the integrity of the demo, the demo user account can\'t be deleted.', 'lockdown_user_delete'); return false; } return $allow; } /** * Prevent users who are the demo user from being updated * * @param boolean $allow true to allow the update of this user * @param User $user The user object requested to update * @return boolea true to allow the update of this user, false to deny */ function filter_user_update_allow( $allow, $user ) { if($user->username == 'demo') { Session::notice('To maintain the integrity of the demo, the demo user account can\'t be updated.', 'lockdown_user_update'); return false; } return $allow; } /** * Permit only certain options to be updated. * * @param mixed $value The value of the option * @param string $name The name of the option * @param mixed $oldvalue The original value of the option * @return */ function filter_option_set_value( $value, $name, $oldvalue ) { // the only options allowed to be changed if ( in_array( $name, array( 'theme_dir', 'theme_name', 'cron_running', 'pluggable_versions' ) ) ) { return $value; } // only allow active_plugins to change if this class is the only thing being added if ( $name == 'active_plugins' && is_array( $value ) ) { $diff = array_diff_key( $value, $oldvalue ); if ( count( $diff ) == 1 && isset( $diff[ __CLASS__ ] ) ) { return $value; } } // otherwise, we throw our error and don't let the option change Session::notice('To maintain the integrity of the demo, option values can\'t be set.', 'lockdown_options'); Session::notice('Option to set: '.$name); return $oldvalue; } /** * Prevent plugins from being activated * * @param boolean $ok true if it's ok to activate this plugin * @param string $file The filename of the plugin * @return boolean false to prevent plugins from being activated */ function filter_activate_plugin( $ok, $file ) { // allow the lockdown plugin to be activated if ( $file == __FILE__ ) { return true; } Session::notice('To maintain the integrity of the demo, plugins can\'t be activated.', 'lockdown_plugin'); return false; } /** * Prevent plugins from being deactivated * * @param boolean $ok true if it's ok to deactivate this plugin * @param string $file The filename of the plugin * @return boolean false to prevent plugins from being deactivated */ function filter_deactivate_plugin( $ok, $file ) { Session::notice('To maintain the integrity of the demo, plugins can\'t be deactivated.', 'lockdown_plugin'); return false; } /** * Prevent certain published content from causing problems. **/ function filter_post_content( $content ) { $newcontent = InputFilter::filter($content); if($content != $newcontent) { Session::notice('Certain content is filtered from posts to maintain the integrity of the demo.', 'lockdown_plugin'); } return $newcontent; } /** * Filter title, slug, and tags fields for HTML content **/ function action_publish_post( $post, $form ) { $post->title = htmlentities($post->title); $post->slug = urlencode($post->slug); $post->tags = htmlentities($form->tags); } } ?><file_sep><?php class Chicklet extends Plugin { public function action_init() { // Handle backwards compatability if(!is_array(Options::get('chicklet__feedname'))) { Options::set('chicklet__feedname', array(Options::get('chicklet__feedname'))); } } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t('Configure'); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure') : $ui = new FormUI( strtolower( get_class( $this ) ) ); $customvalue = $ui->append( 'textmulti', 'feedname', 'chicklet__feedname', _t('Feed Addresses:') ); $customvalue = $ui->append( 'submit', 'submit', _t('Save') ); $ui->out(); break; } } } function action_add_template_vars( $theme ) { $count = $this->fetch(); $theme->subscribers = $count; } static public function fetch() { if(Cache::get('chickler_subscribercount') == NULL) { $count= 0; foreach(Options::get('chicklet__feedname') as $feed) { $url = "https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=" . $feed ; $remote = RemoteRequest::get_contents($url); @$xml = simplexml_load_string($remote); if($xml == false) { return 0; } else { $count = $count + intval($xml->feed->entry['circulation']); } } Cache::set('chickler_subscribercount', $count); } else { $count = Cache::get('chickler_subscribercount'); } return $count; } } ?> <file_sep>CREATE TABLE {rateit_log} ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, post_id INT NOT NULL, rating TINYINT NOT NULL, timestamp DATETIME NOT NULL, ip INT( 10 ) NOT NULL, INDEX ( post_id , ip ) ); <file_sep><?php /** * Rate It! * adding Star Rating to your posts. * * @package rateit * @version $Id$ * @author ayunyan <<EMAIL>> * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link http://ayu.commun.jp/habari-rateit */ require_once('rateitlog.php'); require_once('rateitlogs.php'); class RateIt extends Plugin { const DB_VERSION = 1; /** * plugin information * * @access public * @retrun void */ public function info() { return array( 'name' => 'Rate It!', 'version' => '0.02', 'url' => 'http://ayu.commun.jp/habari-rateit', 'author' => 'ayunyan', 'authorurl' => 'http://ayu.commun.jp/', 'license' => 'Apache License 2.0', 'description' => 'adding Star Rating to your posts.', 'guid' => '5ffe55ac-2773-11dd-b5d6-001b210f913f' ); } /** * action: plugin_activation * * @access public * @param string $file * @return void */ public function action_plugin_activation( $file ) { if ( Plugins::id_from_file( $file ) != Plugins::id_from_file( __FILE__ ) ) return; $db_version = Options::get( 'rateit__db_version' ); if ( empty( $db_version ) ) $db_version = Options::get( 'rateit:db_version' ); if ( empty( $db_version ) ) { if ( $this->install_db() ) { Options::set( 'rateit__db_version', self::DB_VERSION ); } else { Session::error( _t('Rate It!: can\'t create table.') ); } } elseif ( $db_version < self::DB_VERSION ) { // TODO: upgrade_db } Options::set('rateit__post_pos', 'bottom'); Modules::add(_t('Highest Rated Entries', 'rateit')); } /** * action: init * * @access public * @return void */ public function action_init() { $this->load_text_domain('rateit'); DB::register_table('rateit_log'); } /** * action: update_check * * @access public * @return void */ public function action_update_check() { Update::add('Rate It!', $this->info->guid, $this->info->version); } /** * action: plugin_ui * * @access public * @param string $plugin_id * @param string $action * @return void */ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id != $this->plugin_id() ) return; if ( $action == _t( 'Configure' ) ) { $form = new FormUI( strtolower( get_class( $this ) ) ); $form->append( 'radio', 'post_pos', 'rateit__post_pos', _t('Auto Insert: ', 'rateit'), array( 'none' => _t('None', 'rateit'), 'top' => _t('Top', 'rateit'), 'bottom' => _t('Bottom', 'rateit') ) ); $form->append( 'submit', 'save', _t( 'Save' ) ); $form->out(); } } /** * action: template_header * * @access public * @return void */ public function action_template_header() { Stack::add( 'template_header_javascript', Site::get_url( 'scripts' ) . '/jquery.js', 'jquery' ); Stack::add( 'template_header_javascript', $this->get_url() . '/js/rateit.js', 'rateit', array( 'jquery' ) ); Stack::add( 'template_stylesheet', array($this->get_url() . '/css/rateit.css', 'all') ); echo '<script type="text/javascript">var rateit_habari_url = \'' . Site::get_url( 'habari' ) . '\';var rateit_url = \'' . $this->get_url() . '\';</script>'; } /** * filter: plugin_config * * @access public * @return array */ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t( 'Configure' ); } return $actions; } /** * filter: dash_modules * * @access public * @param array $modules * @return array */ public function filter_dash_modules($modules) { $modules[] = _t('Highest Rated Entries', 'rateit'); $this->add_template('dash_highest_rated_entries', dirname(__FILE__) . '/dash_highest_rated_entries.php'); return $modules; } /** * filter: dash_module_highest_rated_entries * * @access public * @param array $module * @param string $module_id * @param object $theme * @return array */ public function filter_dash_module_highest_rated_entries($module, $module_id, $theme) { $module['title'] = _t('Highest Rated Entries', 'rateit'); $theme->highest_rated_posts = DB::get_results('SELECT * FROM {posts} LEFT JOIN {postinfo} ON {posts}.id = {postinfo}.post_id WHERE {postinfo}.name = \'rateit_rating\' ORDER BY {postinfo}.value DESC LIMIT 0,5;', array(), 'Post'); $module['content'] = $theme->fetch('dash_highest_rated_entries'); return $module; } /** * filter: rewrite_rules * * @access public * @param array $rules * @return array */ public function filter_rewrite_rules($rules) { // add rating rewrite rule $rules[]= new RewriteRule( array( 'name' => 'rateit', 'parse_regex' => '/^rateit\/rating$/i', 'build_str' => 'rateit/rating', 'handler' => 'RateIt', 'action' => 'rating', 'priority' => 2, 'rule_class' => RewriteRule::RULE_PLUGIN, 'is_active' => 1, 'description' => 'Rewrite for Rate It! rating action.' )); return $rules; } /** * filter: post_content_out * * @access public * @param string $content * @param object $post * @return string */ public function filter_post_content_out($content, $post) { $post_pos = Options::get('rateit__post_pos'); if ($post_pos == 'top') { $content = $this->create_rating($post) . $content; } elseif ($post_pos == 'bottom') { $content = $content . $this->create_rating($post); } return $content; } /** * theme: show_rateit * * @access public * @param object $theme * @param object $post * @return string */ public function theme_show_rateit($theme, $post) { return $this->create_rating($post); } private function create_rating( $post ) { if ( !isset( $post->info->rateit_total ) || !isset( $post->info->rateit_count ) ) { $total = 0; $count = 0; $rating = 0.00; } else { $total = $post->info->rateit_total; $count = $post->info->rateit_count; $rating = sprintf( "%.2f", $post->info->rateit_total / $post->info->rateit_count ); } $stars = round( $rating ); $stars_classes = array( 0 => 'nostar', 1 => 'onestar', 2 => 'twostar', 3 => 'threestar', 4 => 'fourstar', 5 => 'fivestar' ); if ( $this->check_rated( $post->id ) ) { $html = ' <div class="rateit" id="rateit-' . $post->id . '"> Rate It! (Average ' . $rating . ', ' . $count . ' votes) <div class="rateit-stars rateit-' . $stars_classes[$stars] . '"> <div class="rateit-readonly"></div> </div> </div>'; } else { $html = ' <div class="rateit" id="rateit-' . $post->id . '"> ' . sprintf(_t('Rate It! (Average %.2f, %d votes)', 'rateit'), $rating, $count) . ' <div class="rateit-stars rateit-' . $stars_classes[$stars] . '"> <ul id="rateit-list-' . $post->id . '"> <li class="rateit-one"><a href="#" title="Poor">1</a></li> <li class="rateit-two"><a href="#" title="Fair">2</a></li> <li class="rateit-three"><a href="#" title="Good">3</a></li> <li class="rateit-four"><a href="#" title="Great">4</a></li> <li class="rateit-five"><a href="#" title="Excellent">5</a></li> </ul> </div> <img src="' . $this->get_url() . '/img/loading.gif" class="rateit-loading" id="rateit-loading-' . $post->id . '" alt="" /> </div>'; } return $html; } /** * callback handler action * * @access public * @param string $action * @return void */ public function act( $action ) { switch ( $action ) { case 'rating': if ( !isset( $this->handler_vars['post_id'] ) || !ctype_digit( $this->handler_vars['post_id'] ) ) { echo json_encode( array( 'error' => 1, 'message' => _t('Missing parameter: ', 'rateit') . 'post_id' ) ); break; } if ( !isset( $this->handler_vars['rating'] ) || !ctype_digit( $this->handler_vars['rating'] ) ) { echo json_encode( array( 'error' => 1, 'message' => _t('Missing parameter: ', 'rateit') . 'rating' ) ); break; } if ( $this->check_rated( $this->handler_vars['post_id'] ) ) { echo json_encode( array( 'error' => 1, 'message' => _t('You have already rated this post', 'rateit') ) ); break; } if ( ( $post = $this->add_rating( $this->handler_vars['post_id'], $this->handler_vars['rating'] ) ) === false ) { echo json_encode( array( 'error' => 1, 'message' => _t('cannot rating this post', 'rateit') ) ); break; } echo json_encode( array( 'error' => 0, 'message' => _t('Thank you for Rating', 'rateit'), 'html' => $this->create_rating($post) ) ); break; default: break; } } private function add_rating( $post_id, $rating ) { $post = Posts::get( array( 'id' => $post_id, 'status' => Post::status( 'published' ), 'fetch_fn' => 'get_row' ) ); if ( !$post ) return false; $log = new RateItLog( array( 'post_id' => $post_id, 'rating' => $rating, 'ip' => $_SERVER['REMOTE_ADDR'] ) ); if ( !$log->insert() ) return false; $post->info->rateit_total += $rating; $post->info->rateit_count += 1; $post->info->rateit_rating = $post->info->rateit_total / $post->info->rateit_count; $post->info->commit(); return $post; } private function check_rated( $post_id, $ip = null ) { if ( !isset( $ip ) ) $ip = $_SERVER['REMOTE_ADDR']; $ip = sprintf( '%u', ip2long( $ip ) ); if ( $ip === false ) return true; $result = DB::get_row( 'SELECT COUNT(*) AS count FROM ' . DB::table( 'rateit_log' ) . ' WHERE post_id = :post_id AND ip = :ip', array( ':post_id' => $post_id, ':ip' => $ip ) ); if ( $result !== false && $result->count == 0 ) return false; return true; } /** * create table * * @access private * @return boolean */ private function install_db() { DB::register_table( 'rateit_log' ); return DB::dbdelta( $this->get_db_schema() ); } } ?> <file_sep><!-- This file can be copied and modified in a theme directory --> <li id="widget-twitterbox" class="widget widget_twitterbox"> <h3><a href="http://twitter.com/<?php echo urlencode( Options::get( 'twitter__username' )); ?>" title="follow me"><?php _e('Twitter'); ?></a></h3> <ul> <li class="tweet_text"><?php echo $tweet_text; ?></li> <li class="write"><a href="http://twitter.com/<?php echo urlencode( Options::get( 'twitter__username' )); ?>"><?php echo "at ".$tweet_time_since; ?></a></li> </ul> </li> <file_sep>var rpPel = null; var Commentarea = null; var commentformid = 'comment-public'; function $s(){ if(arguments.length == 1) return get$(arguments[0]); var elements = []; $c(arguments).each(function(el){elements.push(get$(el));}); return elements; } function get$(el){ if(typeof el == 'string') el = document.getElementById(el); return el; } function $c(array){ var nArray = []; for (i=0;el=array[i];i++) nArray.push(el); return nArray; } function commentarea(){ var fi = $s(commentformid).getElementsByName('textarea'); for(var i=0; i<fi.length; i++ ){ if(fi[i].name == 'comment_content'){ return fi[i]; } } return null; } function movecfm(event,Id,dp,author){ var cfm = $s(commentformid); if(cfm == null){ alert("ERROR:\nCan't find the '"+commentformid+"' div."); return false; } var reRootElement = $s("cancel_reply"); if(reRootElement == null){ alert("Error:\nNo anchor tag called 'cancel_reply'."); return false; } var replyId = document.getElementsByName("cf_commentparent"); if(replyId == null){ alert("Error:\nNo form field called 'cf_commentparent'."); return false; } else { replyId = replyId[0]; } var dpId = $s("comment_reply_dp"); if(Commentarea == null) Commentarea = $s('comment_content'); if(parseInt(Id)){ if(cfm.style.display == "none"){ alert("New Comment is submitting, please wait a moment"); return false; } if(event == null) event = window.event; rpPel = event.srcElement? event.srcElement : event.target; rpPel = rpPel.parentNode.parentNode; var OId = $s("comment-"+Id); if(OId == null){ //alert("Error:\nNo comment called 'comment-xxx'."); //return false; OId = rpPel; } replyId.value = Id; if(dpId) dpId.value = dp; reRootElement.style.display = "block"; if($s("cfmguid") == null){ var c = document.createElement("div"); c.id = "cfmguid"; c.style.display = "none"; cfm.parentNode.insertBefore(c,cfm); } cfm.parentNode.removeChild(cfm); OId.appendChild(cfm); if(Commentarea && Commentarea.display != "none"){ Commentarea.focus(); Commentarea.value = '@' + author + ', '; } cfm.style.display = "block"; }else{ replyId.value = "0"; if(dpId) dpId.value = "0"; reRootElement.style.display = "none"; var c = $s("cfmguid"); if(c){ cfm.parentNode.removeChild(cfm); c.parentNode.insertBefore(cfm,c); } if(parseInt(dp) && Commentarea && Commentarea.display != "none"){ Commentarea.focus(); Commentarea.value = ''; } } return true; } <file_sep><?php /** * User Profile Exposure Plugin Class * **/ class UPX extends Plugin { /** * function info * Returns information about this plugin * @return array Plugin info array **/ function info() { return array ( 'name' => 'UPX', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'version' => '1.0', 'description' => 'Exposes user profile information via xml entrypoint', 'license' => 'Apache License 2.0', ); } public function filter_rewrite_rules( $rules ) { $rules[] = new RewriteRule(array( 'name' => 'upx', 'parse_regex' => '/^upx\/(?P<username>[^\/]+)\/?$/i', 'build_str' => 'upx/{$username}', 'handler' => 'UPX', 'action' => 'display_user', 'priority' => 7, 'is_active' => 1, )); return $rules; } public function action_handler_display_user($params) { $users = Users::get(array('info' => array('ircnick'=>$params['username']))); //Utils::debug($user->info); switch(count($users)) { case 0: $xml = new SimpleXMLElement('<error>No user with that IRC nickname.</error>'); break; default: $xml = new SimpleXMLElement('<error>More than one user is registered under that nickname!</error>'); break; case 1: $user = reset($users); $xml = new SimpleXMLElement('<userinfo></userinfo>'); $xml['nickname'] = $params['username']; $xml->blog = $user->info->blog; $xml->name = $user->info->displayname; $xml->nickname = $user->info->ircnick; break; } header('Content-type: text/xml'); ob_clean(); // no idea why we get a blank line at the beginning, but it breaks XML parsing echo $xml->asXML(); } public function filter_adminhandler_post_user_fields ( $fields ) { $fields['ircnick'] = 'ircnick'; $fields['blog'] = 'blog'; return $fields; } public function action_form_user ( $form, $edit_user ) { $ircnick = ( isset( $user->info->ircnick ) ) ? $user->info->ircnick : ''; // insert the UPX block into the form above the page_controls section $upx = $form->insert('page_controls', 'wrapper', 'upx', _t('UPX')); $upx->class = 'container settings'; $upx->append( 'static', 'upx', '<h2>' . htmlentities( _t('UPX'), ENT_COMPAT, 'UTF-8' ) . '</h2>' ); $ircnick = $form->upx->append( 'text', 'ircnick', 'user:foo', _t( 'IRC Nick' ), 'optionscontrol_text' ); $ircnick->class = 'item clear'; $ircnick->value = $edit_user->info->ircnick; $blog = $form->upx->append( 'text', 'blog', 'null:null', _t( 'Blog URL' ), 'optionscontrol_text' ); $blog->class = 'item clear'; $blog->value = $edit_user->info->blog; } } ?><file_sep><div id="lastfm"> <?php echo $lastfm_tracks; ?> </div> <file_sep><?php class RateItLog extends QueryRecord { public static function default_fields() { return array( 'id' => 0, 'post_id' => 0, 'rating' => 0, 'ip' => 0, 'timestamp' => date( 'Y-m-d H:i:s' ), ); } /** * constructer * * @access public */ public function __construct( $paramarray = array() ) { if ( isset( $paramarray['ip'] ) ) { $paramarray['ip']= sprintf( '%u', ip2long( $paramarray['ip'] ) ); } // Defaults $this->fields = array_merge( self::default_fields(), $this->fields ); parent::__construct( $paramarray ); $this->exclude_fields( 'id' ); } /** * insert * * @access public * @return boolean */ public function insert() { $result = parent::insertRecord( DB::table( 'rateit_log' ) ); $this->newfields['id'] = DB::last_insert_id(); // Make sure the id is set in the comment object to match the row id $this->fields = array_merge($this->fields, $this->newfields); $this->newfields = array(); return $result; } public function __set( $name, $value ) { switch( $name ) { case 'ip': $this->ip = sprintf( '%u', ip2long( $value ) ); break; } return parent::__set( $name, $value ); } public function __get( $name ) { switch($name) { case 'ip': $out = long2ip( parent::__get( $name ) ); break; default: $out = parent::__get( $name ); break; } return $out; } } ?><file_sep><?php /** * Ohloh Badge Plugin: Display an ohloh badge, as image markup. **/ class OhlohBadge extends Plugin { private $config = array(); private $class_name = ''; public function help() { return _t( 'Configure, then use <code>&lt;?php $theme->ohloh_badge(); ?></code> in your theme to output the HTML image markup.' ); } public function info() { return array( 'url' => 'http://habariproject.org/', 'name' => 'Ohloh Badge', 'license' => 'Apache License 2.0', 'author' => '<NAME>', 'authorurl' => 'http://blog.roshambo.org/', 'version' => '0.1', 'description' => 'Displays an ohloh badge within your blog.', ); } private static function default_options() { return array ( 'type' => 'detailed', 'user_id' => '', 'alt_text' => '', ); } /** * Add update beacon support **/ public function action_update_check() { Update::add('Ohloh Badge', '42aaa113-4285-42ef-a811-3eb4281cee7c', $this->info->version); } /** * Add actions to the plugin page for this plugin * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id **/ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id === $this->plugin_id()) { $actions[] = _t('Configure', $this->class_name); } return $actions; } /** * Respond to the user selecting an action on the plugin page * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook **/ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id === $this->plugin_id()) { switch ($action) { case _t('Configure', $this->class_name): $ui = new FormUI($this->class_name); $type = $ui->append('select', 'type', 'option:' . $this->class_name . '__type', _t('Ohloh badge type', $this->class_name)); $type->options = array( 'detailed'=> _t('Detailed',$this->class_name), 'rank' => _t('Rank', $this->class_name), 'tiny' => _t('Tiny', $this->class_name), ); $type->add_validator('validate_required'); $user_id = $ui->append('text', 'user_id', 'option:' . $this->class_name . '__user_id', _t('Your numeric ohloh id', $this->class_name)); $user_id->add_validator('validate_ohloh_id'); $alt_text = $ui->append('text', 'alt_text', 'option:' . $this->class_name . '__alt_text', _t('Alt text for image', $this->class_name)); $alt_text->add_validator('validate_required'); $ui->append('submit', 'save', _t('Save', $this->class_name)); $ui->set_option('success_message', _t('Options saved', $this->class_name)); $ui->out(); break; } } } /** * Ensure it's a proper ohloh id * @param The configured params **/ public function validate_ohloh_id($id) { if (empty($id) || !is_numeric($id) || $id < 0 || (false !== strpos($id, '.'))) { return array(_t('A numeric ohloh id is required', $this->class_name)); } return array(); } /** * Ensure the configure options are set and with values * @param The configured params **/ private function plugin_configured($params = array()) { if (empty($params['type']) || empty($params['user_id']) || empty($params['alt_text'])) { return false; } return true; } /** * Create the image markup * @param The configured params **/ private function get_image_markup($params = array()) { $base_url = 'http://www.ohloh.net/accounts/' . $params['user_id']; $image_sizes = array( 'detailed' => ' width="191" height="35" ', 'tiny' => ' width="80" height="15" ', 'rank' => ' width="32" height="24" ', ); return '<a href="' . $base_url . '?ref=' . ucfirst($params['type']) . '">' . '<img src="' . $base_url . '/widgets/account_' . $params['type'] . '.gif"' . $image_sizes[$params['type']] . '"' . $params['alt_text'] . '" />' . '</a>'; } /** * Add Ohloh image to the available template vars * @param $theme The theme that will display the template **/ public function theme_ohloh_badge($theme, $params = array()) { $params = array_merge($this->config, $params); if ($this->plugin_configured($params)) { $theme->ohloh_badge = $this->get_image_markup($params); } else { $theme->ohloh_badge = _t('Ohloh badge plugin is not configured properly.', $this->class_name); } return $theme->fetch('ohloh_badge'); } /** * On plugin activation, set the default options */ public function action_plugin_activation($file) { if (realpath($file) === __FILE__) { $this->class_name = strtolower(get_class($this)); foreach (self::default_options() as $name => $value) { $current_value = Options::get($this->class_name . '__' . $name); if (is_null($current_value)) { Options::set($this->class_name . '__' . $name, $value); } } } } /** * On plugin init, add the template included with this plugin to the available templates in the theme */ public function action_init() { $this->class_name = strtolower(get_class($this)); foreach (self::default_options() as $name => $value) { $this->config[$name] = Options::get($this->class_name . '__' . $name); } $this->load_text_domain($this->class_name); $this->add_template('ohloh_badge', dirname(__FILE__) . '/ohloh_badge.php'); } } ?><file_sep><?php class autoclose extends Plugin { public function info() { return array( 'name' => 'Autoclose', 'version' => '0.3', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Automatically close comments on posts older than a given number of days', 'copyright' => '2008' ); } public function action_plugin_activation( $file ) { if ( realpath( $file ) == __FILE__ ) { CronTab::add_daily_cron( 'autoclose_check_posts', array( __CLASS__, 'check_posts' ), 'Check for posts to close comments on' ); } } public function action_plugin_deactivation( $file ) { if ( realpath( $file ) == __FILE__ ) { CronTab::delete_cronjob( 'autoclose_check_posts' ); } } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t( 'Configure', 'autoclose' ); $actions[] = _t( 'Re-open autoclosed', 'autoclose' ); } return $actions; } // debug/test: go to admin/autoclose or admin/autoclose?nolimit to force a run public function action_admin_theme_get_autoclose( $handler, $theme ) { self::check_posts( !is_null( $handler->handler_vars['nolimit'] ) ); Session::messages_out(); exit; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t( 'Configure', 'autoclose' ) : $ui = new FormUI( 'autoclose' ); $age_in_days = $ui->append( 'text', 'age_in_days', 'autoclose__age_in_days', _t('Post age (days) for autoclose', 'autoclose') ); $age_in_days->add_validator( 'validate_required' ); $ui->append( 'submit', 'save', _t( 'Save', 'autoclose' ) ); $ui->set_option( 'success_message', _t( 'Configuration saved', 'autoclose' ) ); $ui->on_success( array( $this, 'updated_config' ) ); $ui->out(); break; case _t( 'Re-Open', 'autoclose' ) : $this->reopen_autoclosed(); Utils::redirect( URL::get( 'admin', 'page=plugins' ) ); break; } } } public function updated_config( $ui ) { // is this needed? $ui->save(); // close comments on all old posts self::check_posts( true ); return false; } public static function check_posts( $nolimit = false ) { $autoclosed = array(); $age_in_days = Options::get( 'autoclose__age_in_days' ); if ( is_null( $age_in_days ) ) return; $age_in_days = abs( intval( $age_in_days ) ); $search= array( 'content_type' => 'entry', 'before' => HabariDateTime::date_create()->modify('-' . $age_in_days . ' days'), 'nolimit' => true, 'status' => 'published', ); if (!$nolimit) { $search['after'] = HabariDateTime::date_create()->modify('-' . ($age_in_days + 30). ' days'); } $posts = Posts::get( $search ); foreach ( $posts as $post ) { if ( !$post->info->comments_disabled && !$post->info->comments_autoclosed ) { $post->info->comments_disabled = true; $post->info->comments_autoclosed = true; $post->info->commit(); $autoclosed[] = sprintf( '<a href="%s">%s</a>', $post->permalink, htmlspecialchars( $post->title ) ); } } if ( count( $autoclosed ) ) { if ( count( $autoclosed ) > 5 ) { Session::notice( sprintf( _t( 'Comments autoclosed for: %s and %d other posts', 'autoclose' ), implode( ', ', array_slice( $autoclosed, 0, 5 ) ), count( $autoclosed ) - 5 ) ); } else { Session::notice( sprintf( _t( 'Comments autoclosed for: %s', 'autoclose' ), implode( ', ', $autoclosed ) ) ); } } else { Session::notice( sprintf( _t( 'Found no posts older than %d days with comments enabled.', 'autoclose' ), $age_in_days ) ); } return true; } public function reopen_autoclosed() { $reopened = array(); $posts = Posts::get( array( 'content_type' => 'entry', 'info' => array( 'comments_autoclosed' => true, ), 'nolimit' => true, ) ); foreach ( $posts as $post ) { $post->info->comments_disabled = false; $post->info->comments_autoclosed = false; $post->info->commit(); $reopened[] = sprintf( '<a href="%s">%s</a>', $post->permalink, htmlspecialchars( $post->title ) ); } Session::notice( sprintf( _t( 'Comments reopened on %d posts', 'autoclose' ), count( $reopened ) ) ); return true; } } ?> <file_sep><?php /** * DownloadPlugin Class * * This class provides functionality for downloading and installing * plugins directly from a url. * * @todo Document methods * @todo gzip,bzip,tar support * @todo better filename and filetype recognition (e.g. from url like http://host/filenamewithourextension) **/ class DownloadPlugin extends Plugin { private $downloadplugin_pluginsPath; function info() { return array ( 'name' => 'Download Plugin', 'url' => 'http://wiki.lulug.org/prog/habari/download-plugin', 'author' => '<NAME>', 'authorurl' => 'http://forkwait.net/blog', 'version' => '0.1.1', 'description' => 'Download and install plugins', 'license' => 'Apache License 2.0', ); } public function formui_submit( FormUI $form ) { $filename = basename($form->pluginurl); //local file path (e.g. habari_installation/system/plugins/plugin.zip) $filePath = $this->downloadplugin_pluginsPath . $filename; // check if the remote file is successfully opened if ($fp = fopen($form->pluginurl, 'r')) { $content = ''; // keep reading until there's nothing left while ($line = fread($fp, 1024)) { $content .= $line; } $fp = fopen($filePath, 'w'); fwrite($fp, $content); fclose($fp); } else { Session::notice( _t("Error during file download", 'plugin_locale') ); break; } $zip = new ZipArchive; $res = $zip->open( $filePath ); if ($res === TRUE) { $zip->extractTo( $this->downloadplugin_pluginsPath ); $zip->close(); //SET 775 Permission ? Session::notice( _t('Plugin installed', 'plugin_locale') ); } else { Session::notice( _t('Error during plugin installation', 'plugin_locale') ); $form->save(); unlink($filePath); break; } unlink($filePath); $form->pluginurl->value = ''; $form->save(); Utils::redirect( URL::get( 'admin', 'page=plugins' ) ); } public function action_plugin_ui( $plugin_id, $action ) { if ( $this->plugin_id() == $plugin_id ){ $this->downloadplugin_pluginsPath = HABARI_PATH . '/user/plugins/'; $ui = new FormUI( 'Download Plugin' ); if(is_writable($this->downloadplugin_pluginsPath)){ /* in 0.6 texts aren't resizable; search * "what are you trying to do with formui?" * in http://drunkenmonkey.org/irc/habari/2010-09-23 */ $url = $ui->append( 'textarea', 'pluginurl', 'null:null', _t('Plugin URL:', 'plugin_locale') ); $ui->append('submit', 'Download', _t('Download', 'plugin_locale')); $url->add_validator('url_validator', _t('The plugin_url field value must be a valid URL')); $ui->on_success( array($this, 'formui_submit') ); }else{ $ui->append('static','disclaimer', _t( '<p><em><small>Plugins directory is not writable, check permissions and reload this page</small></em></p>') ); } $ui->out(); } } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t('Install new plugin'); } return $actions; } function action_update_check() { Update::add( 'Download Plugin', '2641A2EE-C7D1-11DF-AB1B-7133DFD72085', $this->info->version ); } } ?> <file_sep><?php /********************************** * * Random Posts plugin for Habari 0.5+ * * to use, add <?php $theme->random_posts(); ?> to your theme where you want the list output. * *********************************/ class RandomPosts extends Plugin { const VERSION = '0.3'; private $config = array(); private $random_posts = ''; private $hard_limit = 5; // in case this is not configured, so that all posts are not returned public function info() { return array( 'name' => 'Random Posts', 'url' => 'http://mikelietz.org/code/habari/', 'author' =>'<NAME>', 'authorurl' => 'http://mikelietz.org', 'version' => self::VERSION, 'description' => 'Lists random posts, based on tags to include and/or exclude', 'license' => 'Apache License 2.0', ); } public function action_update_check() { Update::add( 'Random Posts', 'e3dc9780-4229-11dd-ae16-0800200c9a66', $this->info->version ); } public function action_init() { $class_name = strtolower( get_class( $this ) ); $this->config['num_posts'] = Options::get( $class_name . '__num_posts' ); $this->config['tags_exclude'] = Options::get( $class_name . '__tags_exclude' ); $this->config['tags_include'] = Options::get( $class_name . '__tags_include' ); $this->config['before_title'] = Options::get( $class_name . '__before_title' ); $this->config['after_title'] = Options::get( $class_name . '__after_title' ); } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t( 'Configure' ); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t( 'Configure' ): $class_name = strtolower( get_class( $this ) ); $ui = new FormUI( $class_name ); $num_posts = $ui->append( 'text', 'num_posts', 'randomposts__num_posts', _t( 'Default number of links to show' ) ); $tags_include = $ui->append( 'text','tags_include', 'randomposts__tags_include', _t( 'Comma-delimited list of tags to include' ) ); $tags_exclude = $ui->append( 'text','tags_exclude', 'randomposts__tags_exclude', _t( 'Comma-delimited list of tags to exclude' ) ); $before_title = $ui->append( 'text','before_title', 'randomposts__before_title', _t( 'HTML before title' ) ); $after_title = $ui->append( 'text','after_title', 'randomposts__after_title', _t( 'HTML after title' ) ); $ui->append( 'submit', 'save', 'save' ); $ui->out(); break; } } } public function theme_random_posts() { static $random_posts = null; if( $random_posts != null ) { return $random_posts; } $params = array( 'content_type' => Post::type( 'entry' ), 'status' => Post::status( 'published' ), ); $params[ 'limit' ] = ( empty( $this->config['num_posts']) ? $this->hard_limit : $this->config[ 'num_posts' ] ); if ($this->config[ 'tags_include' ] != '' ) { $params[ 'tag' ] = explode( ',', $this->config[ 'tags_include' ] ); } if ($this->config[ 'tags_exclude' ] != '' ) { $params[ 'not_tag' ] = explode( ',', $this->config[ 'tags_exclude' ] ); } $params[ 'orderby' ] = DB::get_driver_name() == 'mysql' ? 'RAND()' : 'Random()'; $posts = Posts::get( $params ); $prefix = ( empty( $this->config[ 'before_title' ] ) ? '' : $this->config[ 'before_title' ] ); $suffix = ( empty( $this->config[ 'after_title' ] ) ? '' : $this->config[ 'after_title' ] ); foreach ( $posts as $post ) { $the_link = "<a href='{$post->permalink}'>{$post->title}</a>"; $this->random_posts .= "$prefix$the_link$suffix\n"; } return $this->random_posts; } } ?> <file_sep><?php /* * Colophon Habari Plugin * This plugin allows the blog owner to include an about/colophon somewhere on the blog * without having to rely on a page or theme rewrite, since the about option got killed * * Example usage in PHP template: * * <?php if (Plugins::is_loaded('Colophon')) { ?> * <h2><?php echo $colophon_title; ?></h2> * <?php echo $colophon; ?> * <?php } ?> * */ class Colophon extends Plugin { const VERSION= '0.3'; /** * Required plugin information * @return array The array of information */ function info() { return array( 'name' => 'Colophon Plugin', 'version' => self::VERSION, 'url' => 'http://github.com/stan/habari-plugins/tree/master', 'author' => '<NAME>', 'authorurl' => 'http://stanbar.jp', 'licence' => 'Apache licence 2.0', 'description' => 'Adds an About / Colophon to your blog' ); } /** * Add actions to the plugin page for this plugin * @param array $actions An array of actions to apply to this plugin * @param string $plugin_id The string with the plugin id, generated by the system * @return array $actions Array of actions to atach to the specified $plugin_id */ public function filter_plugin_config($actions,$plugin_id) { if( $plugin_id == $this->plugin_id()) { $actions[] = _t('Configure'); } return $actions; } /** * Method that responds to the user selecting an action on the plugin page * @param string $plugin_id String containning the id of the plugin * @param string $action The action string suplied via the filter_plugin_config hook **/ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch( $action ) { case _t('Configure'): $ui = new FormUI ( strtolower( get_class( $this ) ) ); $ui->append('text','colophon_title','colophon_title',_t('Enter your Title:')); $ui->append('textarea','colophon_text','colophon_text',_t('Enter your Text:')); $ui->append( 'submit', 'save', _t( 'Save' ) ); $ui->out(); break; } } } /** * Assigns output code to the template variables * @param Theme $theme The theme that will display the template */ function action_add_template_vars( $theme ) { $theme->colophon = Format::autop(Options::get( 'colophon_text' )); $theme->colophon_title = Options::get( 'colophon_title' ); } } ?> <file_sep><?php /* * Woopra Plugin for Habari * * Lets you enable Woopra tracking in your Habari blog * your theme must include the $theme->footer call before the </body> tag in its footer.php * Refer to the readme.txt included with the plugin for the installation/configuration. * * Author: <NAME>. (http://www.awhitebox.com) * Licensed under the terms of Apache Software License 2.0 */ class Woopra extends Plugin { /** * Implement the update notification feature */ public function action_update_check() { Update::add( 'woopra', '9eee624f-8783-42d4-a87e-65d86baa2c1e', $this->info->version ); } public function action_plugin_activation($file) { if (Plugins::id_from_file($file) != Plugins::id_from_file(__FILE__)) return; Options::set('woopra__tag_registered', false); Options::set('woopra__display_avatar', 'no'); } /** * Adds a Configure action to the plugin * * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The id of a plugin * @return array The array of actions */ public function filter_plugin_config( $actions, $plugin_id ) { if ( $this->plugin_id() == $plugin_id ){ $actions[]= _t('Configure'); } return $actions; } /** * Creates a UI form to handle the plguin configurations * * @param string $plugin_id The id of a plugin * @param array $actions An array of actions that apply to this plugin */ public function action_plugin_ui( $plugin_id, $action ) { if ( $this->plugin_id() == $plugin_id && $action == _t('Configure')){ $form= new FormUI( strtolower(get_class( $this ) ) ); $form->append( 'fieldset','fieldset1', _t( 'Tag Registered Users', 'woopra' )); $tag_registered= $form->fieldset1->append( 'checkbox', 'tag_registered', 'option:woopra__tag_registered', _t( 'Enabled', 'woopra' )); $label2= $form->fieldset1->append( 'label','label2', _t( 'Display users avatars', 'woopra') ); $display_avatar= $form->fieldset1->append( 'radio', 'display_avatar', 'option:woopra__display_avatar', _t( 'Display users avatars', 'woopra'), array( 'no'=>'Disabled', 'userimage'=>'Local user image', 'gravatar'=>'Gravatar' )); $form->append( 'fieldset','fieldset2', _t( 'Exclude Users', 'woopra' ) ); $excluded_users= $form->fieldset2->append( 'textmulti', 'excluded_users', 'option:woopra__excluded_users', _t( 'Don\'t track visits from the following user names', 'woopra')); $form->append('submit', 'save', _t('Save')); $form->on_success( array( $this, 'save_config' ) ); $form->out(); } } /** * Invoked when the before the plugin configurations are saved * * @param FormUI $form The configuration form being saved * @return true */ public function save_config( $form ) { $form->save(); Session::notice('Woopra plugin configuration saved!'); return false; } public function theme_footer ($theme) { return $this->build_tracker_code(); } private function build_tracker_code() { //Load plugin options $class= strtolower( get_class( $this ) ); $tag_registered= Options::get( $class . '__tag_registered' ); $display_avatar= Options::get( $class . '__display_avatar' ); $excluded_users= Options::get( $class . '__excluded_users' ); $code=''; $current_user= User::identify(); $current_user_name= is_object($current_user) ? $current_user->username : ''; if ( !( is_object($current_user) && in_array( $current_user_name, $excluded_users) ) ){ $code= "<script type=\"text/javascript\">\n"; if ( is_object($current_user) && $tag_registered ){ $code.= "var woopra_visitor = new Array();\n"; $code.= "woopra_visitor['name'] =\"" . $current_user->displayname . "\";\n"; Switch ( $display_avatar ){ case "userimage": $code.= "woopra_visitor['avatar'] = \"" . $current_user->info->imageurl . "\";\n"; break; case "gravatar": $code.= "woopra_visitor['avatar'] = \"http://www.gravatar.com/avatar.php?gravatar_id=" . md5( strtolower( $current_user->email ) ) . "&size=60&default=http%3A%2F%2Fstatic.woopra.com%2Fimages%2Favatar.png\";\n"; break; } } $code.= "</script>\n<script src=\"http://static.woopra.com/js/woopra.js\" type=\"text/javascript\"></script>\n"; } return $code; } } ?><file_sep><!-- To customize this template, copy it to your currently active theme directory and edit it --> <div id="jaiku"> <ul> <?php if (is_array($presences)) { foreach ($presences as $presence) { printf('<li class="jaiku-message">%1$s <a href="%2$s"><abbr title="%3$s">%4$s</abbr></a> (<a href="%2$s#comments">%5$s</a>)</li>', $presence->message_out, $presence->url, $presence->created_at, $presence->created_at_relative, $presence->comments); } printf('<li class="jaiku-more"><a href="%s">' . _t('Read more…', $this->class_name) . '</a></li>', $presences[0]->user->url); } else { // Exceptions echo '<li class="jaiku-error">' . $presences . '</li>'; } ?> </ul> </div><file_sep><!-- This file can be copied and modified in a theme directory --> <ul id="tag-links"> <?php foreach( $theme->tag_links as $tag) { ?> <li><a href="<?php URL::out( 'display_entries_by_tag', array( 'tag'=> $tag->slug ), false ); ?>"><?php echo $tag->tag; ?></a></li> <? } ?> </ul> <file_sep> <li id="widget-relatedtags" class="widget"> <h3><?php _e('Related Tags') ?></h3> <?php echo $related_tags;; ?> </li> <file_sep>CREATE TABLE {plugin_versions} ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, post_id INTEGER UNSIGNED NOT NULL, url VARCHAR(255) NOT NULL, version VARCHAR(255) NOT NULL, md5 VARCHAR(255) NOT NULL, status VARCHAR(255) NOT NULL, habari_version VARCHAR(255) NOT NULL, requires VARCHAR(255) NOT NULL, provides VARCHAR(255) NOT NULL, recommends VARCHAR(255) NOT NULL, description TEXT, source_link VARCHAR(255) NOT NULL ); <file_sep><?php class CronTabManager extends Plugin { public function alias() { return array( 'action_admin_theme_get_cronjob' => 'action_admin_theme_post_cronjob' ); } public function action_plugin_activation( $file ) { if ( $file == str_replace( '\\','/', $this->get_file() ) ) { # create default access token ACL::create_token( 'manage_cronjobs', _t('Manage CronJobs', 'crontabmanager'), 'Crontab', false ); } } public function action_plugin_deactivation( $file ) { if ( $file == str_replace( '\\','/', $this->get_file() ) ) { # delete default access token ACL::destroy_token( 'manage_cronjobs' ); } } public function action_init() { $this->add_template('crontab', dirname($this->get_file()) . '/crontab.php'); $this->add_template('cronjob', dirname($this->get_file()) . '/cronjob.php'); } public function filter_admin_access_tokens( array $require_any, $page ) { switch ($page) { case 'crontab': case 'cronjob': $require_any = array('manage_cronjobs', true); break; } return $require_any; } public function action_admin_theme_post_crontab( AdminHandler $handler, Theme $theme ) { // saving is handled by FormUI $this->action_admin_theme_get_crontab($handler, $theme); $theme->display('crontab'); // stoopid. exit; } public function action_admin_theme_get_crontab( AdminHandler $handler, Theme $theme ) { if( isset($handler->handler_vars['action']) ) { switch($handler->handler_vars['action']) { case 'delete': $cron = CronTab::get_cronjob((int) $handler->handler_vars['cron_id']); if( $cron instanceof CronJob && $cron->delete() ) { Session::notice(_t( 'Deleted cron job "%s"', array($cron->name), 'crontabmanager' )); } else { Session::error(_t( 'Could not delete Cron Job with id "%s"', array($handler->handler_vars['cron_id']), 'crontabmanager' )); } break; case 'run': $cron = CronTab::get_cronjob((int) $handler->handler_vars['cron_id']); // it's possible that the cron has already run and been deleted if ( !$cron ) { Session::error( _t( 'Cron Job appears to have already run and no longer exists.', 'crontabmanager' ) ); } else { $cron->next_run = HabariDateTime::date_create('now'); $cron->update(); Options::set('next_cron', $cron->next_run->int ); Session::notice(_t( 'Executing Cron Job "%s"', array($cron->name), 'crontabmanager' )); } break; } } $form = new FormUI('crontab-new'); $form->set_option( 'form_action', URL::get('admin', 'page=crontab' ) ); $form->class[] = 'form comment'; $tabs = $form->append('tabs', 'publish_controls'); $new = $tabs->append('fieldset', 'settings', _t('Add Cronjob', 'crontabmanage')); $name = $new->append('text', 'cron_name', 'null:null', _t('Name', 'crontabmanager'), 'tabcontrol_text'); $callback = $new->append('text', 'callback', 'null:null', _t('Callback', 'crontabmanager'), 'tabcontrol_text'); $increment = $new->append('text', 'increment', 'null:null', _t('Interval', 'crontabmanager'), 'tabcontrol_text'); $start_time = $new->append('text', 'start_time', 'null:null', _t('Start Time', 'crontabmanager'), 'tabcontrol_text'); $end_time = $new->append('text', 'end_time', 'null:null', _t('End Time', 'crontabmanager'), 'tabcontrol_text'); $description = $new->append('text', 'description', 'null:null', _t('Description', 'crontabmanager'), 'tabcontrol_text'); $cron_classes = array( CronJob::CRON_SYSTEM => _t('System', 'crontabmanager'), CronJob::CRON_THEME => _t('Theme', 'crontabmanager'), CronJob::CRON_PLUGIN => _t('Plugin', 'crontabmanager'), CronJob::CRON_CUSTOM => _t('Custom', 'crontabmanager'), ); $cron_class = $new->append('select', 'cron_class', 'null:null', _t('Cron Class', 'crontabmanager'), $cron_classes, 'tabcontrol_select'); $cron_class->value = CronJob::CRON_CUSTOM; $new->append( 'submit', 'save', _t('Save', 'crontabmanager') ); $form->on_success( array($this, 'formui_submit') ); $theme->form = $form->get(); $crons = DB::get_results( 'SELECT * FROM {crontab}', array(), 'CronJob' ); $theme->crons = $crons; } public function action_admin_theme_get_cronjob( AdminHandler $handler, Theme $theme ) { $cron = CronTab::get_cronjob((int) $handler->handler_vars['cron_id']); $theme->cron = $cron; $form = new FormUI('cronjob'); $cron_id = $form->append( 'hidden', 'cron_id', 'null:null' ); $cron_id->value = (int) $handler->handler_vars['cron_id']; $name = $form->append( 'text', 'cron_name', 'null:null', _t('Name', 'crontabmanager'), 'optionscontrol_text' ); $name->class = 'item clear'; $name->value = $cron->name; $name->helptext = _t('A unique name for this cronjob.', 'crontabmanager'); $callback = $form->append( 'text', 'callback', 'null:null', _t('Callback', 'crontabmanager'), 'optionscontrol_text' ); $callback->class = 'item clear'; $callback->value = is_array($cron->callback) ? htmlspecialchars(serialize($cron->callback)) : $cron->callback; $callback->helptext = _t('A valid callback OR plugin filter name.', 'crontabmanager'); $increment = $form->append( 'text', 'increment', 'null:null', _t('Iterval', 'crontabmanager'), 'optionscontrol_text' ); $increment->class = 'item clear'; $increment->value = $cron->increment; $increment->helptext = _t('The interval, in seconds, between executions.', 'crontabmanager'); $next_run = $form->append( 'text', 'next_run', 'null:null', _t('Next Run', 'crontabmanager'), 'optionscontrol_text' ); $next_run->class = 'item clear'; $next_run->value = $cron->next_run->get(); $next_run->helptext = _t('A valid HabariDateTime formatted string.', 'crontabmanager'); $start_time = $form->append( 'text', 'start_time', 'null:null', _t('Start Time', 'crontabmanager'), 'optionscontrol_text' ); $start_time->class = 'item clear'; $start_time->value = $cron->start_time->get(); $start_time->helptext = _t('A valid HabariDateTime formatted string.', 'crontabmanager'); $end_time = $form->append( 'text', 'end_time', 'null:null', _t('End Time', 'crontabmanager'), 'optionscontrol_text' ); $end_time->class = 'item clear'; $end_time->value = $cron->end_time ? $cron->end_time->get() : $cron->end_time; $end_time->helptext = _t('A valid HabariDateTime formatted string OR empty for "never".', 'crontabmanager'); $description = $form->append( 'text', 'description', 'null:null', _t('Description', 'crontabmanager'), 'optionscontrol_text' ); $description->class = 'item clear'; $description->value = $cron->description; $description->helptext = _t('A string describing the Cron Job.', 'crontabmanager'); $cron_class = $form->append( 'select', 'cron_class', 'null:null', _t('Cron Class', 'crontabmanager'), 'optionscontrol_select' ); $cron_class->class = 'item clear'; $cron_class->value = $cron->cron_class; $cron_class->helptext = _t('The type of Cron Job.', 'crontabmanager'); $cron_class->options = array( CronJob::CRON_SYSTEM => _t('System', 'crontabmanager'), CronJob::CRON_THEME => _t('Theme', 'crontabmanager'), CronJob::CRON_PLUGIN => _t('Plugin', 'crontabmanager'), CronJob::CRON_CUSTOM => _t('Custom', 'crontabmanager'), ); $form->append( 'submit', 'save', _t('Save', 'crontabmanager') ); $form->on_success( array($this, 'formui_submit') ); $theme->form = $form->get(); } public function action_admin_theme_post_cronjob( AdminHandler $handler, Theme $theme ) { // saving is handled by FormUI $cron = CronTab::get_cronjob((int) $handler->handler_vars['cron_id']); $theme->display('cronjob'); // this is stoopid, but exit so adminhandler doesn't complain exit; } public function formui_submit( FormUI $form ) { if( isset($form->cron_id) ) { $cron = CronTab::get_cronjob((int) $form->cron_id->value); } else { $required = array('cron_name', 'callback', 'description'); foreach( $required as $req ) { if( !$form->{$req}->value ) { Session::error(_t('%s is a required feild.', array(ucwords($req)), 'crontabmanager')); return; } } $cron = new CronJob; //$cron->insert(); } $cron->name = $form->cron_name->value; $cron->callback = (strpos($form->callback->value, 'a:') === 0 || strpos($form->callback->value, 'O:') === 0) ? unserialize($form->callback->value) : $form->callback->value; $cron->increment = $form->increment->value ? $form->increment->value : 86400; $cron->next_run = HabariDateTime::date_create((isset($form->next_run) && $form->next_run->value) ? $form->next_run->value : HabariDateTime::date_create()); $cron->start_time = HabariDateTime::date_create($form->start_time->value ? $form->start_time->value : HabariDateTime::date_create()); $cron->end_time = $form->end_time->value ? HabariDateTime::date_create($form->end_time->value) : null; $cron->description = $form->description->value; $cron->cron_class = $form->cron_class->value; if ( intval( Options::get('next_cron') ) > $cron->next_run->int ){ Options::set( 'next_cron', $cron->next_run->int ); } if( $cron->update() ) { Session::notice( _t('Cron Job saved.', 'crontabmanager') ); } else { Session::error( _t('Could not save Cron Job.', 'crontabmanager') ); } } public function filter_adminhandler_post_loadplugins_main_menu( array $menu ) { $logout = $menu['logout']; unset($menu['logout']); $menu['crontab'] = array( 'url' => URL::get( 'admin', 'page=crontab'), 'title' => _t('Manage the crontab', 'crontabmanager'), 'text' => _t('Crontab' , 'crontabmanager'), 'hotkey' => 'J', 'selected' => false, 'access'=>array('manage_cronjobs', true)); // push logout link to bottom. $menu['logout'] = $logout; return $menu; } } ?> <file_sep><form id="tag_archive_form" action=""> <fieldset><legend><h3>Browse Archives</h3></legend> <ul><li><select name="archive_tags" onchange="window.location = (document.forms.tag_archive_form.archive_tags[document.forms.tag_archive_form.archive_tags.selectedIndex].value);"> <option value=''>by tag</option> <?php $tags = $content->tags; foreach( $tags as $tag ): ?> <option value="<?php echo $tag[ 'url' ]; ?>"><?php echo $tag[ 'tag' ] . $tag[ 'count' ]; ?></option> <?php endforeach; ?> </select></li></ul> </fieldset> </form><file_sep><?php include 'header.php'; ?> <!-- login --> <div id="primary" class="single-post"> <div class="inside"> <div class="primary"> <div id="loginform_div"> <?php if ( isset( $error ) ): ?> <p>That login is incorrect.</p> <?php endif; ?> <?php if ( !$user->loggedin ): ?> <?php Plugins::act( 'theme_loginform_before' ); ?> <form method="post" action="<?php URL::out( 'user', array( 'page' => 'login' ) ); ?>" id="loginform"> <label for="habari_username">Name:</label> <input type="text" size="25" name="habari_username" id="habari_username"><br /> <label for="<PASSWORD>password">Password:</label> <input type="<PASSWORD>" size="25" name="habari_password" id="<PASSWORD>"><br /> <?php Plugins::act( 'theme_loginform_controls' ); ?> <input type="submit" value="Sign in"> </form> <?php Plugins::act( 'theme_loginform_after' ); ?> <?php endif; ?> </div> <!-- /loginform --> <?php Plugins::act( 'theme_login' ); ?> </div> <!-- /primary --> <hr class="hide" /> <?php if ( $user->loggedin ) : ?> <div class="secondary"> <div> <b class="spiffy"> <b class="spiffy1"><b></b></b> <b class="spiffy2"><b></b></b> <b class="spiffy3"></b> <b class="spiffy4"></b> <b class="spiffy5"></b> </b> <div class="spiffy_content"> <div class="featured"> <dl> <dt>Logged in: </dt> <dd><br>You are logged in as <a href="<?php URL::out( 'admin', 'page=user&user=' . $user->username ) ?>" title="Edit Your Profile"> <?php echo $user->username; ?></a>.<br> Want to <a href="<?php Site::out_url( 'habari' ); ?>/user/logout">log out</a>? </dd> </dl> </div> </div> <b class="spiffy"> <b class="spiffy5"></b> <b class="spiffy4"></b> <b class="spiffy3"></b> <b class="spiffy2"><b></b></b> <b class="spiffy1"><b></b></b> </b> </div> </div> <?php endif; ?> <div class="clear"></div> </div> </div> <!-- /#primary --> <hr class="hide" /> <!-- /login --> <?php include 'sidebar.php'; ?> <?php include 'footer.php'; ?> <file_sep><?php class PageSubtitle extends Plugin { /** * Add the subtitle control to the publish page * * @param FormUI $form The publish page form * @param Post $post The post being edited **/ public function action_form_publish ( $form, $post ) { if ( $form->content_type->value == Post::type( 'page' ) ) { $subtitle = $form->settings->append( 'text', 'subtitle', 'null:null', _t( 'Subtitle: '), 'tabcontrol_text' ); $subtitle->value = $post->info->subtitle; $subtitle->move_before( $form->settings->status ); } } /** * Handle update of subtitle * @param Post $post The post being updated * @param FormUI $form. The form from the publish page **/ public function action_publish_post( $post, $form ) { if ( $post->content_type == Post::type( 'page' ) ) { $post->info->subtitle = $form->subtitle->value; } } } ?> <file_sep><?php class PingerUpdate extends Plugin { public function action_post_status_published($post) { if ( $post->status == Post::status( 'published' ) ) { CronTab::add_single_cron( 'ping update sites', 'ping_sites', time(), 'Ping update sites.' ); } } public function filter_ping_sites($result) { $ping = RemoteRequest::get_contents('http://www.pingoat.com/index.php?pingoat=go&blog_name=' . urlencode(Options::get('title')) . '&blog_url=' . urlencode(Site::get_url('habari')) . '&rss_url=' . urlencode(URL::get('collection', array('index'=>1))) . '&cat_0=1&id%5B%5D=0&id%5B%5D=1&id%5B%5D=2&id%5B%5D=3&id%5B%5D=4&id%5B%5D=5&id%5B%5D=6&id%5B%5D=7&id%5B%5D=8&id%5B%5D=9&id%5B%5D=10&id%5B%5D=11&id%5B%5D=12&id%5B%5D=13&id%5B%5D=14&id%5B%5D=15&id%5B%5D=16&id%5B%5D=17&id%5B%5D=18&id%5B%5D=19&id%5B%5D=20&id%5B%5D=21&id%5B%5D=22&id%5B%5D=23&id%5B%5D=24&id%5B%5D=25&cat_1=0&cat_2=0'); EventLog::log('Ping sent to Pingoat.', 'info', 'default', null, $ping ); return $result; } } ?> <file_sep><?php class HPM extends Plugin { const VERSION = '0.2'; const DB_VERSION = 001; public function action_init() { } public function action_update_check() { Update::add( 'hpm', '693E59D6-2B5F-11DD-A23A-9E6C56D89593', $this->info->version ); } /** * @todo fix this schema!!!! */ public function action_plugin_activation( $file ) { if ( $file == str_replace( '\\','/', $this->get_file() ) ) { DB::register_table('packages'); switch( DB::get_driver_name() ) { case 'sqlite': $schema = 'CREATE TABLE ' . DB::table('packages') . ' ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR(255) NOT NULL, guid VARCHAR(255) NOT NULL, version VARCHAR(255) NOT NULL, description TEXT , author VARCHAR(255) , author_url VARCHAR(255) , habari_version VARCHAR(255) , archive_md5 VARCHAR(255) , archive_url VARCHAR(255) , type VARCHAR(255) , status VARCHAR(255) , requires VARCHAR(255) , provides VARCHAR(255) , recomends VARCHAR(255) , tags TEXT , install_profile LONGTEXT );'; break; default: case 'mysql': $schema = 'CREATE TABLE ' . DB::table('packages') . ' ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, guid VARCHAR(255) NOT NULL, version VARCHAR(255) NOT NULL, description TEXT , author VARCHAR(255) , author_url VARCHAR(255) , habari_version VARCHAR(255) , archive_md5 VARCHAR(255) , archive_url VARCHAR(255) , type VARCHAR(255) , status VARCHAR(255) , requires VARCHAR(255) , provides VARCHAR(255) , recomends VARCHAR(255) , tags TEXT , install_profile LONGTEXT, PRIMARY KEY (id) ) CHARACTER SET ' . MYSQL_CHAR_SET . ' ;'; break; } if ( DB::dbdelta( $schema ) ) { Session::notice( 'Updated the HPM database tables.' ); } Options::set( 'hpm__last_update', 1 ); Options::set( 'hpm__repos', 'http://habariproject.org/en/packages' ); # create default access tokens for: 'system', 'plugin', 'theme', 'class' ACL::create_token( 'install_new_system', _t('Install System Updates', 'hpm'), 'hpm', false ); ACL::create_token( 'install_new_plugin', _t('Install New Plugins', 'hpm'), 'hpm', false ); ACL::create_token( 'install_new_theme', _t('Install New Themes', 'hpm'), 'hpm', false ); ACL::create_token( 'install_new_class', _t('Install New Classes', 'hpm'), 'hpm', false ); } } public function action_plugin_deactivation( $file ) { if ( $file == str_replace( '\\','/', $this->get_file() ) ) { DB::register_table('packages'); DB::register_table('package_repos'); DB::query( 'DROP TABLE IF EXISTS {packages} ' ); DB::query( 'DROP TABLE IF EXISTS {package_repos} ' ); # delete default access tokens for: 'system', 'plugin', 'theme', 'class' ACL::destroy_token( 'install_new_system' ); ACL::destroy_token( 'install_new_plugin' ); ACL::destroy_token( 'install_new_theme' ); ACL::destroy_token( 'install_new_class' ); } } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t('Add Sources', 'hpm'); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Add Sources', 'hpm') : $ui = new FormUI( 'hpm' ); $api_key = $ui->append( 'textarea', 'repos', 'option:hpm__repos', _t('HPM Repositories (comma seperated): ', 'hpm') ); $api_key->add_validator( 'validate_required' ); $ui->append( 'submit', 'save', _t( 'Save', 'hpm' ) ); $ui->set_option( 'success_message', _t( 'Configuration saved', 'hpm' ) ); $ui->out(); break; } } } public function filter_admin_access_tokens( array $require_any, $page ) { Plugins::act( 'hpm_init' ); switch ($page) { case 'hpm': $types = HabariPackages::list_package_types(); foreach ($types as $type) { $require_any['install_new_' . $type] = true; } break; } return $require_any; } public function filter_adminhandler_post_loadplugins_main_menu( $menus ) { $menus['plugins']['submenu']['plugs'] = array( 'url' => URL::get( 'admin', 'page=plugins'), 'title' => _t('Currently available plugins', 'hpm'), 'text' => _t('Available Plugins', 'hpm'), 'selected' => false, 'hotkey' => 1, 'access'=>array('install_new_plugins', true) ); $menus['plugins']['submenu']['hpm'] = array( 'url' => URL::get( 'admin', 'page=hpm&type=plugin'), 'title' => _t('Find new plugins', 'hpm'), 'text' => _t('Get New Plugins', 'hpm'), 'selected' => false, 'hotkey' => 2, 'access'=>array('install_new_plugins', true) ); $menus['themes']['submenu']['themeses'] = array( 'url' => URL::get( 'admin', 'page=themes'), 'title' => _t('Currently available themes', 'hpm'), 'text' => _t('Available Themes', 'hpm'), 'selected' => false, 'hotkey' => 1, 'access'=>array('install_new_themes', true) ); $menus['themes']['submenu']['hpm'] = array( 'url' => URL::get( 'admin', 'page=hpm&type=theme'), 'title' => _t('Find new themes', 'hpm'), 'text' => _t('Get New Themes', 'hpm'), 'selected' => false, 'hotkey' => 2, 'access'=>array('install_new_themes', true) ); return $menus; } public function action_admin_theme_get_hpm( $handler, $theme ) { $type = isset($handler->handler_vars['type']) ? $handler->handler_vars['type'] : null; $paged = isset($handler->handler_vars['paged']) ? $handler->handler_vars['paged'] : null; $limit = 20; if ( isset( $handler->handler_vars['action'] ) ) { $action = $handler->handler_vars['action']; if ( method_exists( $this, "act_$action" ) ) { $this->{"act_$action"}( $handler, $theme, $type ); } else { Plugins::act( "hpm_act_$action", $handler, $theme, $type ); } } if ( HabariPackages::require_updates() ) { Session::notice( "The packages list is out of date. " ); } if ( !is_writable( HabariPackages::tempdir() ) || !is_writable( HABARI_PATH . '/3rdparty' ) ) { $theme->notice = 'permissions'; $theme->display('hpm_notice'); exit; } $offset = $paged ? $limit * $paged : 0; if ( $type ) { $theme->packages = DB::get_results( "SELECT * FROM {packages} WHERE type = ? LIMIT $limit OFFSET $offset", array($type), 'HabariPackage' ); } else { $theme->packages = DB::get_results( "SELECT * FROM {packages} LIMIT $limit OFFSET $offset", array(), 'HabariPackage' ); } $theme->type = $type; $theme->display('hpm'); exit; } public function act_update( $handler, $theme ) { try { HabariPackages::update(); Session::notice( 'Package List is now up to date.' ); } catch (Exception $e) { Session::error( 'Could not update Package List' ); if ( DEBUG ) { Utils::debug($e); } } } public function act_upgrade( $handler, $theme ) { try { $package = HabariPackages::upgrade( $handler->handler_vars['guid'] ); Session::notice( "{$package->name} was upgraded to version {$package->version}." ); if ( $package->readme_doc ) { $theme->notice = 'readme'; $theme->package = $package; $theme->display('hpm_notice'); exit; } } catch (Exception $e) { Session::error( 'Could not complete upgrade: '. $e->getMessage() ); if ( DEBUG ) { Utils::debug($e); } } } public function act_install( $handler, $theme ) { try { $package = HabariPackages::install( $handler->handler_vars['guid'] ); Session::notice( "{$package->name} {$package->version} was installed." ); if ( $package->readme_doc ) { $theme->notice = 'readme'; $theme->package = $package; $theme->display('hpm_notice'); exit; } } catch (Exception $e) { Session::error( 'Could not complete install: '. $e->getMessage() ); if ( DEBUG ) { Utils::debug($e); } } } public function act_uninstall( $handler, $theme ) { try { $package = HabariPackages::remove( $handler->handler_vars['guid'] ); Session::notice( "{$package->name} {$package->version} was uninstalled." ); } catch (Exception $e) { Session::error( 'Could not complete uninstall: '. $e->getMessage() ); if ( DEBUG ) { Utils::debug($e); } } } public function action_auth_ajax_hpm_packages( $handler ) { Plugins::act('hpm_init'); $theme = Themes::create( 'admin', 'RawPHPEngine', dirname(__FILE__) .'/' ); $search = isset( $handler->handler_vars['search'] ) ? $handler->handler_vars['search'] : ''; $search = explode( ' ', $search ); $where = array(); $vals = array(); $limit = 20; $offset = (int) $handler->handler_vars['offset'] ? $handler->handler_vars['offset'] : 0; foreach ( $search as $term ) { $where[] = "(name LIKE CONCAT('%',?,'%') OR description LIKE CONCAT('%',?,'%') OR tags LIKE CONCAT('%',?,'%') OR type LIKE CONCAT('%',?,'%'))"; $vals = array_pad( $vals, count($vals) + 4, $term ); } $theme->packages = DB::get_results( 'SELECT * FROM {packages} WHERE ' . implode( ' AND ', $where ) . "LIMIT $limit OFFSET $offset", $vals, 'HabariPackage' ); echo json_encode( array( 'items' => $theme->fetch('hpm_packages') ) ); } public function action_hpm_init() { DB::register_table('packages'); include 'habaripackage.php'; include 'habaripackages.php'; include 'packagearchive.php'; include 'archivereader.php'; include 'tarreader.php'; include 'zipreader.php'; include 'txtreader.php'; PackageArchive::register_archive_reader( 'application/x-zip', 'ZipReader' ); PackageArchive::register_archive_reader( 'application/zip', 'ZipReader' ); PackageArchive::register_archive_reader( 'application/x-tar', 'TarReader' ); PackageArchive::register_archive_reader( 'application/tar', 'TarReader' ); PackageArchive::register_archive_reader( 'application/x-gzip', 'TarReader' ); PackageArchive::register_archive_reader( 'text/plain', 'TxtReader' ); PackageArchive::register_archive_reader( 'text/php', 'TxtReader' ); PackageArchive::register_archive_reader( 'application/php', 'TxtReader' ); $this->add_template( 'hpm', dirname(__FILE__) . '/templates/hpm.php' ); $this->add_template( 'hpm_packages', dirname(__FILE__) . '/templates/hpm_packages.php' ); $this->add_template( 'hpm_notice', dirname(__FILE__) . '/templates/hpm_notice.php' ); } } ?> <file_sep><?php class OpenSearch extends Plugin { /** * Required Plugin Informations */ public function info() { return array( 'name' => 'OpenSearch 1.1', 'version' => '0.2', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Add OpenSearch 1.1 support to Habari.', 'copyright' => '2007' ); } /** * Filter function called by the plugin hook `rewrite_rules` * Add a new rewrite rule to the database's rules * * Call `OpenSearch::act('osDescription')` when a request for `content-search.xml` is received * * @param array $db_rules Array of rewrite rules filtered so far */ public function filter_rewrite_rules( $db_rules ) { $db_rules[]= RewriteRule::create_url_rule( '"opensearch.xml"', 'OpenSearch', 'osDescription' ); $db_rules[]= new RewriteRule( array( 'name' => 'opensearch', 'parse_regex' => '%^search(?:/(?P<criteria>[^/]+))?(?:/page/(?P<page>\d+))?(?:/count/(?P<count>\d+))?/atom/?$%i', 'build_str' => 'search(/{$criteria})(/page/{$page})/atom', 'handler' => 'OpenSearch', 'action' => 'search', 'priority' => 8, 'is_active' => 1, 'rule_class' => RewriteRule::RULE_CUSTOM, 'description' => 'Searches posts' ) ); return $db_rules; } /** * Assign this plugin to the alternate rules for OpenSearch * * @param array $alternate_rules Rewrite rules assignments for alternate URL */ public function filter_atom_get_collection_alternate_rules( $alternate_rules ) { $alternate_rules['opensearch']= 'opensearch'; return $alternate_rules; } /** * Add OpenSearch namespace to the Atom feed * * @param array $xml_namespaces Namespaces currently assigned to this feed */ public function filter_atom_get_collection_namespaces( $xml_namespaces ) { $xml_namespaces['opensearch']= 'http://a9.com/-/spec/opensearch/1.1/'; return $xml_namespaces; } /** * Add various elements for the OpenSearch protocol to work * * @param string $xml XML generated so far by the AtomHandler::get_collection() method * @param array $params Parameters used to fetch results, will be used to find total results and where to start (index) * @return string XML OpenSearch results Atom feed */ public function filter_atom_get_collection( $xml, $params ) { $criteria = $params['criteria']; $totalResults = Posts::get( $params )->count_all(); $startIndex = isset( $params['page'] ) ? $params['page'] : 1; $itemsPerPage = isset( $this->handler_vars['count'] ) ? $this->handler_vars['count'] : Options::get( 'pagination' ); $xml->addChild( 'opensearch:totalResults', $totalResults); $xml->addChild( 'opensearch:startIndex', $startIndex ); $xml->addChild( 'opensearch:itemsPerPage', $itemsPerPage ); $xml_os_query = $xml->addChild( 'opensearch:Query' ); $xml_os_query->addAttribute( 'role', 'request' ); $xml_os_query->addAttribute( 'searchTerms', $criteria ); $xml_os_query->addAttribute( 'startPage', 1 ); return $xml; } /** * Act function called by the `Controller` class. * Dispatches the request to the proper action handling function. * * @param string $action Action requested, either Search or osDescription */ public function act( $action ) { self::$action(); } /** * Output the OpenSearch description file * * @return string XML OpenSearch description file */ public function osDescription() { $template_url = Site::get_url( 'habari' ) . '/search/{searchTerms}/page/{startPage}/count/{count}/atom'; $xml = '<?xml version="1.0" encoding="UTF-8"?><OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"></OpenSearchDescription>'; $xml = new SimpleXMLElement( $xml ); $xml_sn = $xml->addChild( 'ShortName', Options::get('title') ); $xml_description = $xml->addChild( 'Description', Options::get('tagline') ); $xml_tags = ''; $xml_contact = ''; $xml_url = $xml->addChild( 'Url' ); $xml_url->addAttribute( 'type', 'text/html'); $xml_url->addAttribute( 'template', $template_url ); $xml = $xml->asXML(); /* Clean the output buffer, so we can output from the header/scratch. */ ob_clean(); header( 'Content-Type: application/opensearchdescription+xml' ); print $xml; } /** * Searches content based on criteria * Creates a new Atom feed based on criteria and other parameters (pagination, limit, etc.) */ public function search() { $criteria = $this->handler_vars['criteria']; $page = isset( $this->handler_vars['page'] ) ? $this->handler_vars['page'] : 1; $limit = isset( $this->handler_vars['count'] ) ? $this->handler_vars['count'] : Options::get( 'pagination' ); preg_match_all( '/(?<=")(\\w[^"]*)(?=")|(\\w+)/', $criteria, $matches ); $words = $matches[0]; $where = 'status = ?'; $params = array( Post::status( 'published' ) ); foreach ( $words as $word ) { $where .= " AND (title LIKE CONCAT('%',?,'%') OR content LIKE CONCAT('%',?,'%'))"; $params[] = $word; $params[] = $word; // Not a typo } $user_filters = array( 'where' => $where, 'params' => $params, 'page' => $page, 'criteria' => $criteria, 'limit' => $limit ); $atomhandler = new AtomHandler(); $atomhandler->handler_vars['index']= $page; $atomhandler->get_collection( $user_filters ); } /** * Add the link and meta data to the header * * @param object $theme Theme object with all its properties and methods available */ public function theme_header( $theme ) { $search_url = Site::get_url('habari') . '/opensearch.xml'; $site_title = Options::get('title'); echo '<link rel="search" type="application/opensearchdescription+xml" href="' . $search_url . '" title="' . $site_title . '">'."\r\n"; if ( Controller::get_action() == 'search' ) { $totalResults = $theme->posts->count_all(); $startIndex = $theme->page; $itemsPerPage = isset( $this->handler_vars['count'] ) ? $this->handler_vars['count'] : Options::get( 'pagination' ); echo '<meta name="totalResults" content="' . $totalResults . '">'."\r\n"; echo '<meta name="startIndex" content="' . $startIndex . '">'."\r\n"; echo '<meta name="itemsPerPage" content="' . $itemsPerPage . '">'."\r\n"; } } } ?> <file_sep><?php /** * Credit Due plugin, allows output of theme and plugin information for Habari sites. */ class CreditDue extends Plugin { /** * Add help text to plugin configuration page **/ public function help() { $help = _t( '<p>To use, add <code>&lt;?php $theme->show_credits(); ?&gt;</code> in your theme.</p><p>To customize the output template, copy creditdue.php to your theme\'s directory</p>' ); return $help; } /** * function theme_show_credits * retrieves information about the active theme and returns it for display by a theme. * * Usage: This function is called using <?php $theme->show_credits(); ?> * This loads the template creditdue.php (which can be copied to the theme directory and customized) and shows the theme and plugins in unordered lists */ public function theme_show_credits( $theme ) { $theme_credits = Themes::get_active(); $plugin_credits = Plugins::get_active(); $theme->theme_credits = $theme_credits; $theme->plugin_credits = $plugin_credits; return $theme->fetch( 'creditdue' ); } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'CreditDue', 'fb0b8460-38f2-11dd-ae16-0800200c9a66', $this->info->version ); } /** * On plugin init, add the template included with this plugin to the available templates in the theme */ public function action_init() { $this->add_template('creditdue', dirname(__FILE__) . '/creditdue.php'); } } ?> <file_sep><?php class GoogleAds extends Plugin { function info() { return array( 'url' => 'http://iamgraham.net/plugins', 'name'=> 'GoogleAds', 'license' => 'Apache License 2.0', 'author'=> '<NAME>', 'authorurl' => 'http://iamgraham.net/', 'version' => '0.2' ); } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'GoogleAds', 'ad99b200-3ba0-11dd-ae16-0800200c9a66', $this->info->version ); } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t( 'Configure' ); } return $actions; } public function action_plugin_ui($plugin_id, $action) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t( 'Configure' ): $ui = new FormUI( strtolower( get_class( $this ) ) ); $clientcode = $ui->append( 'text', 'clientcode', 'googleads__clientcode', _t( 'Ad Client Code' ) ); $adslot = $ui->append( 'text', 'adslot', 'googleads__adslot', _t( 'Ad Slot ID' ) ); $adwidth = $ui->append( 'text', 'adwidth', 'googleads__adwidth', _t( 'Ad Width' ) ); $adheight = $ui->append( 'text', 'adheight', 'googleads__adheight', _t( 'Ad Height' ) ); $ui->append( 'submit', 'save', _t('Save') ); $ui->out(); break; } } } public function updated_config( $ui ) { return true; } private static function getvar( $var ) { return Options::get( 'googleads__' . $var ); } function action_theme_sidebar_bottom() { $code = <<<ENDAD <div class="sb-adsense"> <h2>Advertising</h2> <p><script type="text/javascript"><!-- google_ad_client = "CLIENTCODE"; google_ad_slot = "ADSLOT"; google_ad_width = ADWIDTH; google_ad_height = ADHEIGHT; //--></script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script></p> </div> ENDAD; $replace = array( 'CLIENTCODE' => self::getvar( 'clientcode' ), 'ADSLOT' => self::getvar( 'adslot' ), 'ADWIDTH' => self::getvar( 'adwidth' ), 'ADHEIGHT' => self::getvar( 'adheight' ) ); $code = str_replace( array_keys( $replace ), array_values( $replace ), $code ); echo $code; } } ?> <file_sep><?php // komode: le=unix language=php codepage=utf8 tab=4 tabs indent=4 class TextTransport extends Plugin { const ACTION_CONFIGURE = 'Configure'; const ACTION_EXPORT_ALL = 'Export all posts'; const ACTION_EXPORT_ONE = 'Export one post'; const FILENAME_HASH = '.hash'; const FILENAME_CONTENT = 'content.txt'; const FILENAME_PART_COMMENTPREFIX = 'comment'; const FILENAME_PART_COMMENTSEP = '.'; const FILENAME_PART_COMMENTSUFFIX = '.txt'; const OPTIONS_LOCALPATH = 'texttransport__localpath'; /** * Standard update checker */ public function action_update_check() { Update::add( 'Text Transport', 'c54b7fdc-5738-4ad8-a154-7e555878eaaa', $this->info->version ); } /** * Deactivation; removes the Options key */ public function action_plugin_deactivation( $file ) { Options::delete( self::OPTIONS_LOCALPATH ); } /** * Stndard plugin UI configuration */ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t( self::ACTION_CONFIGURE ); $actions[] = _t( self::ACTION_EXPORT_ALL ); } return $actions; } /** * UI for plugin button */ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t( self::ACTION_CONFIGURE ): $ui = new FormUI( strtolower( __CLASS__ ) ); $path = $ui->append( 'text', 'exportpath', self::OPTIONS_LOCALPATH, _t( 'Export Path:' ) ); $ui->exportpath->add_validator( array( __CLASS__, 'check_path' ) ); $ui->append( 'submit', 'save', _t( 'Save' ) ); $ui->set_option( 'success_message', _t( 'TextExport Settings Saved' ) ); $ui->out(); break; case _t( self::ACTION_EXPORT_ALL ): $this->export_all(); break; } } } /** * FormUI callback to check that the path is writable * * @param string $path path to check * @return array (empty on success, error message on fail) */ public static function check_path( $path ) { if ( is_writable( $path ) ) { // path is fine return array(); } return array( _t( 'Invalid path (not writable).' ) ); } /** * Exports all posts */ protected function export_all() { $posts = array(); foreach ( Posts::get() as $post ) { $hash = self::hash_from_post( $post ); if ($hash !== self::get_disk_post_hash( $post ) || $hash !== self::hash_from_disk_post( $post ) ) { // no match, need to export echo sprintf( _t( 'Exporting post: %s' ), $post->slug ) . "<br />\n"; if ( self::export_post( $post ) ) { Session::notice( sprintf( _t( 'Exported post: %s' ), $post->slug ) ) . "<br />\n"; } } else { echo sprintf( _t( "Post '%s' up to date." ), $post->slug ) . "<br />\n"; } } } /** * Export a specific post * * Also called by export_all * * @param Post $post the post to export */ protected static function export_post( Post $post ) { $postPath = self::get_post_export_path( $post ); self::recursive_file_delete( $postPath ); mkdir( $postPath ); file_put_contents( $postPath . self::FILENAME_HASH, self::hash_from_post( $post ) ); file_put_contents( $postPath . self::FILENAME_CONTENT, $post->content ); self::export_comments( $post ); } /** * Export comments for a given post * * @param Post $post export comments from this post */ protected static function export_comments( Post $post ) { foreach ($post->comments as $comment) { $commentFilename = self::FILENAME_PART_COMMENTPREFIX . self::FILENAME_PART_COMMENTSEP . $comment->id . self::FILENAME_PART_COMMENTSEP . Comment::status_name($comment->status) . self::FILENAME_PART_COMMENTSUFFIX; file_put_contents( $postPath . $commentFilename, $comment->content ); } return true; } /** * Get the export path for a specific post * * Rasises an error if the export path isn't writable * * @param Post $post the post for which we want the export path * @return string path */ protected static function get_post_export_path( Post $post ) { $exportPath = Options::get( self::OPTIONS_LOCALPATH ); if (!$exportPath || !is_readable( $exportPath ) || !is_writable( $exportPath ) ) { Error::raise( _t( 'Export path is not readable/writable. Be sure to configure this plugin.' ) ); } return $exportPath . DIRECTORY_SEPARATOR . $post->slug . DIRECTORY_SEPARATOR; } /** * Calculate the recursive post has from disk * * @param Post $post calculate a hash for this post, but do not use the post's data; get data from disk * @return string recursive hash from files on disk; false on failure */ public static function hash_from_disk_post( Post $post ) { $postPath = self::get_post_export_path( $post ); $contentFile = $postPath . self::FILENAME_CONTENT; if ( !is_readable( $contentFile ) ) { return false; } $content = file_get_contents( $contentFile ); $hash = md5( $post->slug . $content ); $prefixLen = strlen( self::FILENAME_PART_COMMENTPREFIX ); // gather filenames so they can be sorted $filenames = array(); foreach ( new DirectoryIterator( $postPath ) as $f ) { $commentFile = $f->getFileName(); if ( substr( $commentFile, 0, $prefixLen ) !== self::FILENAME_PART_COMMENTPREFIX ) { // not a comment file continue; } $filenames[] = $commentFile; } natsort( $filenames ); // now that they're sorted, actually process (hash) foreach ( $filenames as $commentFile ) { list( , $id, $status ) = explode( self::FILENAME_PART_COMMENTSEP, $postPath.$commentFile ); $hash = md5( $hash . self::hash_from_disk_comment( $postPath . $commentFile, $id, $status ) ); } return $hash; } /** * Calculate the hash for this comment, from disk * * REFACTOR to calculate the id, status internally * * @param string $commentFile the filename where this comment can be read (full path) * @param int $id the original comment ID for this comment (calculated from the filename) * @param string $status the status name of this comment * @return string hash of the comment */ protected static function hash_from_disk_comment( $commentFile, $id, $status ) { $content = file_get_contents( $commentFile ); $hash = md5( $id . $status . $content ); return $hash; } /** * Reads a hash from the pre-calculated value on the disk * * This method performs NO calculation; it's just an easy way to determine * if the contents have changed without hitting the database. This hash * is read from a file that is written to disk when the post is exported. * * @param Post $post the post from which to fetch the hash * @return string hash of this post */ public static function get_disk_post_hash( Post $post ) { $hashPath = self::get_post_export_path( $post ) . self::FILENAME_HASH; if ( !is_readable( $hashPath ) ) { // no hash return false; } return file_get_contents( $hashPath ); } /** * Calculates the recursive hash from a Post object * * @param Post $post the post object from which to calculate the hash * @return string hash */ public static function hash_from_post( Post $post ) { // these hashes are _NOT_ for security purposes // the point is to reduce an entire post + comment set into a hash // to efficiently check for changes $hash = md5( $post->slug . $post->content ); $comments = array(); foreach ( $post->comments as $comment ) { $comments[$comment->id] = $comment; } ksort($comments); foreach ($comments as $comment) { $hash = md5( $hash . self::hash_from_comment( $comment ) ); } return $hash; } /** * Calculates the hash from a Comment object * * @param Comment $comment the comment object from which to calculate the hash * @return string hash */ protected static function hash_from_comment( Comment $comment ) { $hash = md5( $comment->id . Comment::status_name( $comment->status ) . $comment->content ); return $hash; } /** * Recursive file and directory delete * * USE WITH CAUTION. This is roughly equivalent to `rm -rf $path`. * * @param string $path root path to delete * @return bool (success) */ protected static function recursive_file_delete( $path ) { if ( !is_writable( $path ) ) { return false; } $outerRdi = new RecursiveDirectoryIterator( $path ); $rdi = new RecursiveIteratorIterator( $outerRdi, RecursiveIteratorIterator::CHILD_FIRST ); foreach ($rdi as $name => $file) { if ( $file->isDir() ) { rmdir( $name ); } else { // file unlink( $name ); } } rmdir( $path ); return true; } } ?><file_sep><?php /** * FlickrFeed Plugin: Show the images from Flickr feed * Usage: <?php $theme->flickrfeed(); ?> */ class FlickrFeed extends Plugin { private $config = array(); private $class_name = ''; private static function default_options() { return array ( 'type' => 'user', 'user_id' => '', 'num_item' => '6', 'size' => 'square', 'tags' => '', 'cache_expiry' => '1800', ); } /** * Required plugin information * @return array The array of information **/ public function info() { return array( 'name' => 'FlickrFeed', 'version' => '0.5', 'url' => 'http://code.google.com/p/bcse/wiki/FlickrFeed', 'author' => '<NAME>', 'authorurl' => 'http://blog.bcse.info/', 'license' => 'Apache License 2.0', 'description' => _t('Display your latest photos on your blog.', $this->class_name) ); } /** * Add update beacon support **/ public function action_update_check() { Update::add('FlickrFeed', '165a2150-59ae-11dd-ae16-0800200c9a66', $this->info->version); } /** * Add actions to the plugin page for this plugin * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id **/ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id === $this->plugin_id()) { $actions[] = _t('Configure', $this->class_name); } return $actions; } /** * Respond to the user selecting an action on the plugin page * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook **/ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id === $this->plugin_id()) { switch ($action) { case _t('Configure', $this->class_name): $ui = new FormUI($this->class_name); $type = $ui->append('select', 'type', 'option:' . $this->class_name . '__type', _t('Photostream Type', $this->class_name)); $type->options = array( 'public' => _t('Public photos & video', $this->class_name), 'user' => _t('Public photos & video from you', $this->class_name), 'friends' => _t('Your friends’ photostream', $this->class_name), 'faves' => _t('Public favorites from you', $this->class_name), 'group' => _t('Group pool', $this->class_name) ); $type->add_validator('validate_required'); $user_id = $ui->append('text', 'user_id', 'option:' . $this->class_name . '__user_id', _t('Flickr ID (You can get it from <a href="http://idgettr.com">idGettr</a>)', $this->class_name)); $user_id->add_validator('validate_flickr_id'); $num_item = $ui->append('text', 'num_item', 'option:' . $this->class_name . '__num_item', _t('&#8470; of Photos', $this->class_name)); $num_item->add_validator('validate_uint'); $num_item->add_validator('validate_required'); $size = $ui->append('select', 'size', 'option:' . $this->class_name . '__size', _t('Photo Size', $this->class_name)); $size->options = array( 'square' => _t('Square', $this->class_name), 'thumbnail' => _t('Thumbnail', $this->class_name), 'small' => _t('Small', $this->class_name), 'medium' => _t('Medium', $this->class_name), 'large' => _t('Large', $this->class_name), 'original' => _t('Original', $this->class_name) ); $size->add_validator('validate_required'); $tags = $ui->append('text', 'tags', 'option:' . $this->class_name . '__tags', _t('Tags (comma separated, no space)', $this->class_name)); $cache_expiry = $ui->append('text', 'cache_expiry', 'option:' . $this->class_name . '__cache_expiry', _t('Cache Expiry (in seconds)', $this->class_name)); $cache_expiry->add_validator('validate_uint'); $cache_expiry->add_validator('validate_required'); // When the form is successfully completed, call $this->updated_config() $ui->append('submit', 'save', _t('Save', $this->class_name)); $ui->set_option('success_message', _t('Options saved', $this->class_name)); $ui->out(); break; } } } public function validate_uint($value) { if (!ctype_digit($value) || strstr($value, '.') || $value < 0) { return array(_t('This field must be positive integer.', $this->class_name)); } return array(); } public function validate_flickr_id($value) { if (empty($value) && in_array($this->config['type'], array('user', 'group'))) { return array(_t('A value for this field is required while type is not ‘Public’.', $this->class_name)); } return array(); } private function plugin_configured($params = array()) { if (empty($params['type']) || empty($params['user_id']) || empty($params['num_item']) || empty($params['size']) || empty($params['cache_expiry'])) { return false; } return true; } private function load_feeds($params = array()) { $cache_name = $this->class_name . '__' . md5(serialize($params)); if (Cache::has($cache_name)) { // Read from cache return Cache::get($cache_name); } else { switch ($params['type']) { case 'user': $url = 'http://api.flickr.com/services/feeds/photos_public.gne?id=' . $params['user_id'] . '&tags=' . $params['tags'] . '&format=php_serial'; break; case 'friends': $url = 'http://api.flickr.com/services/feeds/photos_friends.gne?user_id=' . $params['user_id'] . '&format=php_serial'; break; case 'faves': $url = 'http://api.flickr.com/services/feeds/photos_faves.gne?id=' . $params['user_id'] . '&format=php_serial'; break; case 'group': $url = 'http://api.flickr.com/services/feeds/groups_pool.gne?id=' . $params['user_id']. '&format=php_serial'; break; default: $url = 'http://api.flickr.com/services/feeds/photos_public.gne?tags=' . $params['tags'] . '&format=php_serial'; break; } try { // Get PHP serialized object from Flickr $call = new RemoteRequest($url); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { throw Error::raise(_t('Unable to contact Flickr.', $this->class_name)); } // Unserialize and manipulate the data $flickrfeed = unserialize($call->get_response_body()); $flickrfeed = array_slice($flickrfeed['items'], 0, $params['num_item']); // Photo size foreach ($flickrfeed as &$image) { switch ($params['size']) { case 'thumbnail': $image['image_url'] = str_replace('_m.jpg', '_t.jpg', $image['m_url']); break; case 'small': $image['image_url'] = $image['m_url']; break; case 'medium': $image['image_url'] = $image['l_url']; break; case 'large': $image['image_url'] = str_replace('_m.jpg', '_b.jpg', $image['m_url']); break; case 'original': $image['image_url'] = $image['photo_url']; break; default: $image['image_url'] = $image['t_url']; break; } } // Do cache Cache::set($cache_name, $flickrfeed, $params['cache_expiry']); return $flickrfeed; } catch (Exception $e) { return $e->getMessage(); } } } /** * Add Flickr images to the available template vars * @param Theme $theme The theme that will display the template **/ public function theme_flickrfeed($theme, $params = array()) { $params = array_merge($this->config, $params); if ($this->plugin_configured($params)) { $theme->flickrfeed = $this->load_feeds($params); } else { $theme->flickrfeed = _t('FlickrFeed Plugin is not configured properly.', $this->class_name); } return $theme->fetch('flickrfeed'); } /** * On plugin activation, set the default options */ public function action_plugin_activation($file) { if (realpath($file) === __FILE__) { $this->class_name = strtolower(get_class($this)); foreach (self::default_options() as $name => $value) { $current_value = Options::get($this->class_name . '__' . $name); if (is_null($current_value)) { Options::set($this->class_name . '__' . $name, $value); } } } } /** * On plugin init, add the template included with this plugin to the available templates in the theme */ public function action_init() { $this->class_name = strtolower(get_class($this)); foreach (self::default_options() as $name => $value) { $this->config[$name] = Options::get($this->class_name . '__' . $name); } $this->load_text_domain($this->class_name); $this->add_template('flickrfeed', dirname(__FILE__) . '/flickrfeed.php'); } } ?> <file_sep><!-- searchform --> <?php Plugins::act( 'theme_searchform_before' ); ?> <form method="get" action="<?php URL::out('display_search'); ?>"> <input type="text" name="criteria" value="To search, type and hit enter" onfocus="this.value = ''" onblur="this.value='To search, type and hit enter'"> </form> <?php Plugins::act( 'theme_searchform_after' ); ?> <!-- /searchform --> <file_sep><?php /** * HabminBar Plugin * * A plugin for Habari that displays and admin bar * on every page of your theme, for easy access to * the admin section. * * @package habminbar */ class HabminBar extends Plugin { const VERSION = '1.0'; /** * function info * * Returns information about this plugin * @return array Plugin info array */ public function info() { return array ( 'name' => 'Habmin Bar', 'url' => 'http://habariproject.org', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org', 'version' => self::VERSION, 'description' => 'An admin bar for Habari.', 'license' => 'Apache License 2.0', ); } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Habmin Bar', '1db4ce60-3ca2-11dd-ae16-0800200c9a66', $this->info->version ); } /** * Adds the admin bar stylesheet to the template_stylesheet Stack if the user is logged in. */ public function action_add_template_vars() { if ( User::identify()->loggedin ) { Stack::add( 'template_stylesheet', array($this->get_url() . '/habminbar.css', 'screen'), 'habminbar.css' ); } } /** * Filters the habminbar via Plugin API to add the edit menu item. * * @param array $menu The Habminbar array * @return array The modified Habminbar array */ public function filter_habminbar( $menu ) { if ( Controller::get_var('slug') ) { $post = Post::get('slug=' . Controller::get_var('slug')); $menu['write']= array( 'Edit', URL::get( 'admin', 'page=publish&id=' . $post->id ) ); } return $menu; } /** * Ouputs the default menu in the template footer, and runs the 'habmin_bar' plugin filter. * You can add menu items via the filter. See the 'filter_habminbar' method for * an example. */ public function action_template_footer() { if ( User::identify()->loggedin ) { $bar = '<div id="habminbar"><div>'; $bar.= '<div id="habminbar-name"><a href="' . Options::get('base_url') . '">' . Options::get('title') . '</a></div>'; $bar.= '<ul>'; $menu = array(); $menu['dashboard']= array( 'Dashboard', URL::get( 'admin', 'page=dashboard' ), "view the admin dashboard" ); $menu['write']= array( 'Write', URL::get( 'admin', 'page=publish' ), "create a new entry" ); $menu['option']= array( 'Options', URL::get( 'admin', 'page=options' ), "configure site options" ); $menu['comment']= array( 'Moderate', URL::get( 'admin', 'page=comments' ),"moderate comments" ); $menu['user']= array( 'Users', URL::get( 'admin', 'page=users' ), "administer users" ); $menu['plugin']= array( 'Plugins', URL::get( 'admin', 'page=plugins' ), "activate and configure plugins" ); $menu['theme']= array( 'Themes', URL::get( 'admin', 'page=themes' ), "select a theme" ); $menu = Plugins::filter( 'habminbar', $menu ); $menu['logout']= array( 'Logout', URL::get( 'user', 'page=logout' ), "logout" ); foreach ( $menu as $name => $item ) { list( $label, $url, $tooltip )= array_pad( $item, 3, "" ); $bar.= "\n\t<li><a href=\"$url\" class=\"$name\"" . ( ( $tooltip ) ? " title=\"$tooltip\"" : "" ) .">$label</a></li>"; } $bar.= '</ul><br style="clear:both;" /></div></div>'; echo $bar; } } } ?> <file_sep><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title><?php echo $theme->the_title(true); ?></title> <meta http-equiv="Content-Type" content="text/html"> <meta name="generator" content="Habari"> <link rel="alternate" type="application/atom+xml" title="Atom 1.0" href="<?php $theme->feed_alternate(); ?>"> <link rel="edit" type="application/atom+xml" title="Atom Publishing Protocol" href="<?php URL::out( 'atompub_servicedocument' ); ?>"> <link rel="EditURI" type="application/rsd+xml" title="RSD" href="<?php URL::out( 'rsd' ); ?>"> <link rel="stylesheet" type="text/css" media="screen" href="<?php Site::out_url( 'theme' ); ?>/style.css"> <?php $theme->header(); ?> </head> <body class="home"> <div id="header"> <h1><a href="<?php Site::out_url( 'habari' ); ?>"><?php Options::out( 'title' ); ?></a></h1> <h2><?php echo $theme->menu_title; ?></h2> <?php echo $theme->pages_menu(); ?> </div> <div id="container"> <div id="content"> <file_sep> <aside id="sidebar" role="complementary"> <ul class="xoxo"> <?php $theme->area( 'sidebar' ); ?> </ul> </aside> <file_sep><?php include 'header.php'; ?> <!-- home --> <div id="main" class="push-4 span-16"> <div id="content" class=""> <?php foreach ( $posts as $post ) { ?> <div id="post-<?php echo $post->id; ?>" class="<?php echo $post->statusname; ?>"> <h2 class="post-title"><a href="<?php echo $post->permalink; ?>" title="<?php echo $post->title; ?>"> <?php echo $post->title_out; ?></a></h2> <h4><?php echo $post->pubdate_out; ?><?php if ( $user ) { ?> <a href="<?php URL::out( 'admin', 'page=publish&slug=' . $post->slug); ?>" title="Edit post">(edit)</a><?php } ?></h4> <div> <?php echo $post->content_out; ?> </div> <div class="meta"> <p><?php if ( is_array( $post->tags ) ) { ?> Tags &brvbar; <?php echo $post->tags_out; ?> <?php } ?><br /><a href="<?php echo $post->permalink; ?>#comments" title="Comments to this post"> <?php echo $post->comments->approved->count; ?> <?php echo _n( 'Comment', 'Comments', $post->comments->approved->count ); ?></a></p> </div> </div> <?php } ?> </div> <div id="pagenav"> <span>Page:</span> <?php $theme->prev_page_link('&laquo; ' . _t('Newer Posts')); ?> <?php $theme->page_selector( null, array( 'leftSide' => 2, 'rightSide' => 2 ) ); ?> <?php $theme->next_page_link('&raquo; ' . _t('Older Posts')); ?> </div> </div> <?php include 'sidebar.php'; ?> <?php include 'footer.php'; ?> </div> </body> </html> <file_sep><!-- commentsform --> <?php // Do not delete these lines if ( ! defined('HABARI_PATH' ) ) { die( _t('Please do not load this page directly. Thanks!') ); } ?> <div id="respond"> <h3 class="reply"><?php _e('Leave a Reply'); ?></h3> <?php if ( Session::has_errors() ) { Session::messages_out(); } ?> <div class="formcontainer"> <?php $post->comment_form()->out(); ?> </div> </div> <file_sep><?php class MobileTheme extends Plugin { private function is_mobile() { // Detection script courtesy http://papermashup.com/lightweight-mobile-browser-detection/ $mobile_browser = 0; if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android)/i', strtolower($_SERVER['HTTP_USER_AGENT']))) { $mobile_browser++; } if((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml')>0) or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE'])))) { $mobile_browser++; } $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4)); $mobile_agents = array( 'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac', 'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno', 'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-', 'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-', 'newt','noki','oper','palm','pana','pant','phil','play','port','prox', 'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar', 'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-', 'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp', 'wapr','webc','winw','winw','xda','xda-' ); if(in_array($mobile_ua,$mobile_agents)) { $mobile_browser++; } if (strpos(strtolower($_SERVER['ALL_HTTP']),'OperaMini')>0) { $mobile_browser++; } if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'windows')>0) { $mobile_browser=0; } if($mobile_browser>0) { return true; } else { return false; } } function filter_get_theme_dir($theme_dir) { if(isset($_SESSION['mobile_theme'])) { if($_SESSION['mobile_theme']) { return Options::get('mobiletheme'); } else { return $theme_dir; } } if($this->is_mobile()) { return Options::get('mobiletheme'); } return $theme_dir; } function theme_is_mobile() { return $this->is_mobile(); } public function configure( ) { $theme_data = Themes::get_all_data(); $themes = array(); foreach($theme_data as $key => $theme) { $themes[$key] = (string)$theme['info']->name; } $ui = new FormUI( strtolower( get_class( $this ) ) ); $ui->append( 'select', 'mobiletheme', 'mobiletheme', _t('Select the theme to use for detected mobile browsers:') ); $ui->mobiletheme->options = $themes; $ui->append( 'submit', 'save', _t('Save') ); return $ui; } public function filter_block_list($block_list) { $block_list['mobiletoggle'] = _t('Mobile Toggle'); return $block_list; } public function action_block_content_mobiletoggle($block, $theme) { $block->mobile = $this->is_mobile(); $block->mobile_on = Url::get('mobile_on'); $block->mobile_off = Url::get('mobile_off'); } public function action_block_form_mobiletoggle($form, $block) { $form->append('static', 'There are no settings for this form.'); } public function action_init() { $this->add_rule('"mobile"/"on"', 'mobile_on'); $this->add_rule('"mobile"/"off"', 'mobile_off'); $this->add_template('block.mobiletoggle', dirname(__FILE__) . '/block.mobiletoggle.php'); } public function action_plugin_act_mobile_on() { $_SESSION['mobile_theme'] = true; Utils::redirect(Site::get_url('habari')); } public function action_plugin_act_mobile_off() { $_SESSION['mobile_theme'] = false; Utils::redirect(Site::get_url('habari')); } } ?> <file_sep><?php class LastRecent extends Plugin { private $api_key = '<KEY>'; private $cache_expiry = '7200'; private $user = null; private $limit = 3; private $images = 1; public function action_init() { $this->add_template( 'lastfm', dirname( __FILE__ ) . '/lastfm.php' ); $this->add_template( "block.lastfm_recent", dirname( __FILE__ ) . "/block.lastfm_recent.php" ); $this->user = Options::get( 'lastrecent__user' ); $this->limit = Options::get( 'lastrecent__limit' ); $size = Options::get( 'lastrecent__images' ); switch( $size ) { case 'none': $this->images = null; break; case 'small': $this->images = 0; break; case 'medium': $this->images = 1; break; case 'large': $this->images = 2; break; case 'extralarge': $this->images = 3; break; } } public function action_plugin_activation() { // a cronjob to fetch the data from last.fm CronTab::add_hourly_cron( 'lastrecent', 'lastrecent', _t( 'Fetch recent tracks from last.fm', 'lastrecent' ) ); } function action_plugin_deactivation( $file ) { CronTab::delete_cronjob( 'lastrecent' ); Cache::expire( array( 'lastrecent' ) ); } public function filter_plugin_config( $actions ) { $actions['configure']= _t( 'Configure' ); return $actions; } public function action_plugin_ui_configure() { $ui = new FormUI( strtolower( get_class( $this ) ) ); $ui->append( 'static', 'null:null', _t( 'These settings are only effective for themes using the legacy implementation method (See Help). If you plan to use blocks, you can must set these settings on a per-block basis.', 'lastrecent') ); $user= $ui->append( 'text', 'user', 'lastrecent__user', _t( 'Last.fm username: ', 'lastrecent' ) ); $limit= $ui->append( 'select', 'limit', 'lastrecent__limit', _t( 'Number of tracks to display: ', 'lastrecent' ) ); $options= array(); for ( $i= 1; $i<= 10; $i++ ) { $options[$i]= $i; } $limit->options= $options; $images= $ui->append( 'select', 'images', 'lastrecent__images', _t( 'Show images: ', 'lastrecent' ) ); $images->options= array( 'none' => _t( 'None', 'lastrecent' ), 'small' => _t( 'Small', 'lastrecent' ), 'medium' => _t( 'Medium', 'lastrecent' ), 'large' => _t( 'Large', 'lastrecent' ), 'extralarge' => _t( 'Extralarge', 'lastrecent' ) ); $ui->append( 'submit', 'save', _t( 'Save' ) ); $ui->on_success( array( $this, 'saveOptions' ) ); $ui->out(); } // Save the form and clear the cache public static function saveOptions ( $ui ) { $ui->save(); Cache::expire( 'lastrecent__legacy' ); } public function filter_block_list( $block_list ) { $block_list['lastfm_recent'] = _t( 'Last.fm Recent Tracks', 'lastrecent' ); return $block_list; } public function action_block_content_lastfm_recent( $block, $theme ) { $block->lastfm_recent = $this->get_lastrecent( $block ); } public function action_block_form_lastfm_recent( $form, $block ) { $form->append( 'text', 'user', $block, _t( 'Last.fm username: ', 'lastrecent' ) ); $form->append( 'text', 'user', $block, _t( 'Last.fm username: ', 'lastrecent' ) ); $form->append( 'select', 'limit', $block, _t( 'Number of tracks to display: ', 'lastrecent' ) ); $options = array(); for ( $i = 1; $i<= 10; $i++ ) { $options[$i] = $i; } $form->limit->options = $options; $form->append( 'select', 'size', $block, _t( 'Show images: ', 'lastrecent' ) ); $form->size->options= array( null => _t( 'None', 'lastrecent' ), 0 => _t( 'Small', 'lastrecent' ), 1 => _t( 'Medium', 'lastrecent' ), 2 => _t( 'Large', 'lastrecent' ), 3 => _t( 'Extralarge', 'lastrecent' ) ); } public function action_block_update_after( $block ) { if ( $block->type == 'lastfm_recent' ) { Cache::expire( 'lastrecent__' . $block->title ); } } public function theme_lastrecent( $theme ) { $theme->lastfm_tracks= $this->get_lastrecent(); return $theme->fetch( 'lastfm' ); } private function get_lastrecent( $block = null ) { $name = ( $block ) ? $block->title : 'legacy'; $user = ( $block ) ? $block->user : $this->user; $limit = ( $block ) ? $block->limit : $this->limit; $size = ( $block ) ? (int) $block->size : $this->images; if ( Cache::has( 'lastrecent__' . $name ) ) { $recent = Cache::get( 'lastrecent__' . $name ); } else { try { $last = new RemoteRequest( 'http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&api_key=' . $this->api_key . '&user=' . urlencode( $user ) . '&limit=' . $limit ); $last->set_timeout( 5 ); $result = $last->execute(); if ( Error::is_error( $result ) ) { throw $result; } $response = $last->get_response_body(); $xml = new SimpleXMLElement( $response ); $recent = array(); foreach ( $xml->recenttracks->track as $track ) { $recent[] = array( 'name' => (string) $track->name, 'url' => (string) $track->url, 'image' => (string) $track->image[$size], 'artist' => (string) $track->artist, 'album' => (string) $track->album, 'date' => (string) $track->date, ); } Cache::set( 'lastrecent__' . $name, $recent, $this->cache_expiry ); } catch( Exception $e ) { $recent['error'] = $e->getMessage(); } } return $recent; } } ?> <file_sep><!-- To customize this template, copy it to your currently active theme directory and edit it --> <?php if ($post->comments->tweetbacks->count > 0) { ?> <ul id="tweetbacks"> <?php foreach ($post->comments->tweetbacks as $tweet) { printf('<li class="tweetback vcard"><a href="%1$s" class="url fn" rel="external">%2$s</a>: %3$s <abbr class="published" title="%4$s">%5$s</abbr></li>', $tweet->profile_url, $tweet->name_out, $tweet->content_out, $tweet->date->format(HabariDateTime::ISO8601), $tweet->date->format('F j, Y – g:i a')); } ?> </ul> <?php } ?> <file_sep>var GoogleAnalytics = { trackClick: function (a) { var isInternal = new RegExp("^(https?):\/\/" + window.location.host, "i"); var isDownload = new RegExp("\\.(<?php echo $extensions ?>)$", "i"); var trackoutgoing = <?php echo (Options::get('googleanalytics__trackoutgoing')) ? 'true' : 'false' ?>; var trackmailto = <?php echo (Options::get('googleanalytics__trackmailto')) ? 'true' : 'false' ?>; var trackfiles = <?php echo (Options::get('googleanalytics__trackfiles')) ? 'true' : 'false' ?>; try { if (isInternal.test(a.href)) { if (trackfiles && isDownload.test(a.href)) { var extension = isDownload.exec(a.href); pageTracker._trackEvent("Downloads", extension[1].toUpperCase(), a.href.replace(isInternal, '')); } } else { if (trackmailto && a.protocol === "mailto:") { pageTracker._trackEvent("Mailtos", "Click", a.href.substring(7)); } else if (trackoutgoing) { pageTracker._trackEvent("Outgoing Links", "Click", a.href); } } } catch (e) {} }, attachListeners: function () { var hrefs = document.getElementsByTagName("a"); for (var i = 0; i < hrefs.length; i++) { GoogleAnalytics.addEvent(hrefs[i], "click", function () { GoogleAnalytics.trackClick(this); }); } }, addEvent: function (obj, type, fn) { if (obj.attachEvent) { obj['e' + type + fn] = fn; obj[type + fn] = function () { obj['e' + type + fn](window.event); }; obj.attachEvent('on' + type, obj[type + fn]); } else { obj.addEventListener(type, fn, false); } } }; GoogleAnalytics.attachListeners(); <file_sep>If you are reading this then I am already dead. Under your seat you will find a case. Do not open it! = Fun with Photos - Habari Photoblog theme = This is a really simply photoblog theme. == Licence == This is licensed under Apache Software License (http://www.apache.org/licenses/) == Posting photos == The theme splits all posts into two parts, the photo and the accompanying information. The photo is displayed first and the extra info, along with the comments, can be seen by clicking the link beneath the photo. There are two options for posting the photo and additional information: === Option 1 - No plugin === When you create your post you need to include the image HTML at the top. After that line add <!--details-->. Everything after <!--details--> will appear on the second screen. === Option 2 - With the plugin === In the theme folder there is another folder called "Fun with photos plugin". To use this copy it into the Habari plugins directory and activate it as normal. Once activated you will find that your post page has a new text box for the image URL. The Habari Silo will also have an extra option: Use Photo, that will insert the image URL into that box for you. If you use this method then everything in the normal post box will be extra text that is separated out onto the second page. == Changing the title graphic == Included with the theme is a folder called PSD. In it you will find a photoshop document with the blog title in it so you can change it. == Versions == = 1.0.1 = Added a single line of CSS to remove the outlines on the next and previous links. Enjoy Andrew http://www.habari-fun.co.uk <file_sep><?php require_once 'cpgdb.php'; require_once 'cpgoptions.php'; class Cpg extends Plugin { const VERSION = '0.1'; function info() { return array( 'name' => 'Copperleaf Photo Gallery Plugin', 'version' => self::VERSION, 'url' => 'http://wiki.habariproject.org/en/CPG', 'author' => '<NAME>', 'authorurl' => 'http://www.copperleaf.org/', 'license' => 'Apache License 2.0', 'description' => 'A plugin for managing and displaying photos.' ); } // *** Uncomment when ready for release *** //function action_update_check() //{ // Update::add('Copperleaf Photo Gallery Plugin', '397B7ABC-7E7A-11DD-A57A-408D55D89593', self::VERSION); //} public function action_plugin_activation($file) { if ($file == str_replace( '\\','/', $this->get_file())) { CpgDb::registerTables(); //Options::set( 'cpg__db_version', CpgDb::DB_VERSION ); CpgOptions::setDbVersion(CpgDb::DB_VERSION); if (CpgDb::install()) { Session::notice(_t( 'Created the CPG database tables.', 'cpg')); } else { Session::error(_t( 'Could not install CPG database tables.', 'cpg')); } } } public function action_init() { //$this->add_template('event.single', dirname(__FILE__) . '/event.single.php'); Post::add_new_type('imageset', false); Post::add_new_type('image', false); Post::add_new_type('gallery', false); CpgDb::registerTables(); //Utils::debug('tables registered!'); if (CpgDb::DB_VERSION > CpgOptions::getDbVersion()) { CpgDb::install(); EventLog::log( 'Updated CPG.' ); CpgOptions::setDbVersion(CpgDb::DB_VERSION); } } public function filter_adminhandler_post_loadplugins_main_menu($menus) { unset($menus['create_' . Post::type('imageset')]); unset($menus['manage_' . Post::type('imageset')]); unset($menus['create_' . Post::type('image')]); unset($menus['manage_' . Post::type('image')]); unset($menus['create_' . Post::type('gallery')]); return $menus; } public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()) { $actions[]= _t('Configure'); } return $actions; } public function action_plugin_ui($plugin_id, $action) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure') : $ui = new FormUI( strtolower( get_class( $this ) ) ); $customvalue= $ui->append( 'text', 'customvalue', 'cpg__customvalue', _t('Your custom value:') ); $ui->out(); break; } } } function action_plugins_loaded() { } } ?> <file_sep><?php if ($post->info->short_url): ?> <link rel="shorturl" href="<?php echo $post->info->short_url ?>" /> <link rel="shortlink" type="text/html" href="<?php echo $post->info->short_url ?>" /> <?php endif; ?> <file_sep><!-- Linkoid: To modify this template, copy it from the plugin directory to your current theme directory. --> <div class="sb-linkoid"> <h2>Linkoid</h2> <ul> <?php foreach($linkoids as $post): ?> <li><p><a href="<?php echo $post->permalink; ?>" style="font-weight: bold;"><?php echo $post->title; ?></a> - <?php echo $post->content; ?> </p></li> <?php endforeach; ?> </ul> </div> <file_sep><?php class dateNinja extends Plugin { /** * Add update beacon support **/ public function action_update_check() { Update::add( 'DateNinja', 'e64e02e0-38f8-11dd-ae16-0800200c9a66', $this->info->version ); } public function action_init() { // add some js to the admin header Stack::add( 'admin_header_javascript', $this->get_url() . '/date_ninja.js', 'dateninja' ); Stack::add( 'admin_header_javascript', $this->get_url() . '/date.js', 'datejs' ); } } ?> <file_sep><?php $theme->display('header'); ?> <link rel="stylesheet" type="text/css" media="screen" href="<?php echo $css; ?>"> <!--begin content--> <div id="content"> <div id='gallery-breadcrumbs'> <?php $links = array(array_pop($breadcrumbs)); $base = Site::get_url( 'habari' ); while ( !empty($breadcrumbs) ) { $link = $base . '/' . implode('/', $breadcrumbs); $breadcrumb = array_pop($breadcrumbs); $links[] = "<span class='gallery-breadcrumb'><a href='{$link}'>$breadcrumb</a></span>"; } echo implode(" &raquo; ", array_reverse($links)); ?> </div> <h2><?php echo $title; ?></h2> <?php foreach ( $dirs as $dir ): ?> <?php if ( $dir->thumbnail != null ): ?> <div class='gallery-img'> <a href='<?php echo $dir->url; ?>' title='<?php echo $dir->pretty_title; ?>'> <img src='<?php echo $dir->thumbnail->url; ?>'> </a> <h3><?php echo $dir->pretty_title; ?></h3> </div> <?php else: ?> <div class='gallery-dir'> Gallery: <a href='<?php echo $dir->url; ?>' title='<?php echo $dir->pretty_title; ?>'><?php echo $dir->pretty_title; ?></a> </div> <?php endif; ?> <?php endforeach; ?> <div class='clear'></div> <?php foreach ( $images as $image ): ?> <div class='gallery-img'> <a href='<?php echo $image->url; ?>' title='<?php echo $image->pretty_title; ?>'> <img src='<?php echo $image->thumbnail_url; ?>'> </a> <h3><?php echo $image->pretty_title; ?></h3> </div> <?php endforeach; ?> </div><!--end content--> <?php $theme->display('footer'); ?> <file_sep><?php /* * Notice: * 1. You have things below: * $site_name, site_link, * $post_title, $post_link, * $comment_id, $comment_author, $comment_content, * $reply_id, $reply_author, $reply_content, * $unsubscribe_link * 2. Do not change the order of the sections */ ?> ====== Subject ====== <?php echo "[$site_name] You have a new reply on $post_title"; ?> ====== End ====== ====== Text ====== <?php echo "Hi $comment_author, You have a new reply on $post_title from $reply_author. Your comment: $comment_content Reply $reply_content See your reply from $post_link ================================================ This mail is sent by system automatically, do not reply please. You can unsubscribe from $unsubscribe_link "; ?> ====== End ====== ====== HTML ====== <?php echo "<?xml version=\"1.0\" ?> <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"> <html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\"> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/> <title>[$site_name] You have a new reply on $post_title</title> </head> <body style=\"line-height: 150%; background-color: #eeeeee;\"> <div id=\"wrapper\" style=\"padding: 20px; border: 1px solid #dddddd; background-color: #ffffff;\"> Hi $comment_author, <br /> <br /> You have a new reply on <a href=\"$post_link\" title=\"$post_title\">$post_title</a> from $reply_author. <div style=\"padding: 10px; margin: 20px; border: 1px dashed #666666; background: #eeeeee;\"> Your comment: <blockquote><p>$comment_content</p></blockquote> </div> <div style=\"padding: 10px; margin: 20px; border: 1px dashed #666666; background: #eeeeee;\"> Reply: <blockquote><p>$reply_content</p></blockquote> </div> You can see your reply from <a href=\"$post_link#comment-$reply_id\" title=\"Reply\">$post_link#comment-$reply_id</a> <br/> <br /> ==============================================<br /> This mail is sent by system automatically, do not reply please. You can unsubscribe from <a href=\"$unsubscribe_link\" title=\"Unsubscribe\">here</a> </div> </body> </html>"; ?> ====== End ====== <file_sep><?php class Thickbox extends Plugin { /** * Required Plugin Informations */ public function info() { return array( 'name' => 'Thickbox', 'version' => '3.1', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Adds Thickbox functionality to your theme.', 'copyright' => '2008' ); } /** * Adds needed files to the theme stacks (javascript and stylesheet) */ public function action_init() { Stack::add( 'template_header_javascript', Site::get_url('scripts') . '/jquery.js', 'jquery' ); Stack::add( 'template_header_javascript', Site::get_url('user') . '/plugins/thickbox/thickbox-compressed.js', 'thickbox-js' ); Stack::add( 'template_stylesheet', array( Site::get_url('user') . '/plugins/thickbox/thickbox.css', 'screen,projector'), 'thickbox-css' ); } } ?> <file_sep><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en-US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title><?php if($request->display_entry && isset($post)) { echo "{$post->title} - "; } ?><?php Options::out( 'title' ) ?></title> <meta name="generator" content="Habari"> <link rel="alternate" type="application/atom+xml" title="Atom 1.0" href="<?php $theme->feed_alternate(); ?>"> <link rel="edit" type="application/atom+xml" title="Atom Publishing Protocol" href="<?php URL::out( 'atompub_servicedocument' ); ?>"> <link rel="EditURI" type="application/rsd+xml" title="RSD" href="<?php URL::out( 'rsd' ); ?>"> <link rel="stylesheet" type="text/css" media="screen" href="<?php Site::out_url( 'theme' ); ?>/css/screen.css"> <link rel="stylesheet" type="text/css" media="print" href="<?php Site::out_url( 'theme' ); ?>/css/print.css"> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script> <script type="text/javascript" src="http://localhost/habari-dev/user/themes/spark/js/loginbox.js"></script> <?php $theme->header(); ?> </head> <body> <div id="skiplinks"> <a href="#navigation">Jump to navigation</a> <a href="#content">Jump to main content</a> <a href="#searchform">Jump to search form</a> </div> <div id="container"> <?php if ( !$loggedin ) { ?> <div id="login-box"> <div class="login-button"><a href="#">Log in</a></div> <div class="clear"></div> <div class="login-form"> <?php Plugins::act( 'theme_loginform_before' ); ?> <form method="post" action="<?php URL::out( 'auth', array( 'page' => 'login' ) ); ?>" id="loginform"> <div><label for="habari_username"><?php _e('Name:'); ?></label></div> <div><input type="text" size="25" name="habari_username" id="habari_username"></div> <div><label for="habari_password"><?php _e('Password:'); ?></label></div> <div><input type="password" size="25" name="habari_password" id="<PASSWORD>password"></div> <?php Plugins::act( 'theme_loginform_controls' ); ?> <div><button><?php _e('Log in'); ?></button></div> </form> <?php Plugins::act( 'theme_loginform_after' ); ?> </div> </div> <?php } ?> <h1><a href="<?php Site::out_url( 'habari' ); ?>"><?php Options::out( 'title' ); ?></a></h1> <div id="main"> <file_sep><?php /* * PreApproved Class * * This class allows us to auto-approve comments * */ class AutoApprove extends Plugin { /* * function info * Returns information about this plugin * @return array Plugin info array */ function info() { return array ( 'name' => 'Auto-Approve', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'version' => '1.0.0', 'description' => 'Automatically approve comments that are not spam.', 'license' => 'Apache License 2.0', ); } /* * Register the PreApproved event type with the event log */ public function action_plugin_activation( $file ) { if ( realpath( $file ) == __FILE__ ) { EventLog::register_type( 'autoapprove', 'autoapprove' ); } } /* * Unregister the PreApproved event type on deactivation if it isn't being used */ public function action_plugin_deactivation( $file ) { if ( realpath( $file ) == __FILE__ ) { EventLog::unregister_type( 'autoapprove', 'autoapprove' ); } } /* * function act_comment_insert_before * This function is executed when the action "comment_insert_before" * is invoked from a Comment object. * The parent class, Plugin, handles registering the action * and hook name using the name of the function to determine * where it will be applied. * You can still register functions as hooks without using * this method, but boy, is it handy. * @param Comment The comment that will be processed before storing it in the database. * @return Comment The comment result to store. */ function action_comment_insert_before ( $comment ) { // This plugin ignores non-comments and comments already marked as spam if( $comment->type == Comment::COMMENT && $comment->status != Comment::STATUS_SPAM) { $comment->status = Comment::STATUS_APPROVED; EventLog::log( 'Comment by ' . $comment->name . ' automatically approved.', 'info', 'autoapprove', 'autoapprove' ); } return $comment; } function set_priorities() { return array( 'action_comment_insert_before' => 10 ); } /* * Add update beacon support */ function action_update_check() { Update::add( 'Auto-Approve', 'dbf559b2-62db-4364-b35d-74fc57ebc9b9', $this->info->version ); } } ?> <file_sep><?php /* * PreApproved Class * * This class allows us to auto-approve comments * */ class AutoApprove extends Plugin { /* * Register the PreApproved event type with the event log */ public function action_plugin_activation( $file ) { if ( realpath( $file ) == __FILE__ ) { EventLog::register_type( 'autoapprove', 'autoapprove' ); } } /* * Unregister the PreApproved event type on deactivation if it isn't being used */ public function action_plugin_deactivation( $file ) { if ( realpath( $file ) == __FILE__ ) { EventLog::unregister_type( 'autoapprove', 'autoapprove' ); } } /* * function act_comment_insert_before * This function is executed when the action "comment_insert_before" * is invoked from a Comment object. * The parent class, Plugin, handles registering the action * and hook name using the name of the function to determine * where it will be applied. * You can still register functions as hooks without using * this method, but boy, is it handy. * @param Comment The comment that will be processed before storing it in the database. * @return Comment The comment result to store. */ function action_comment_insert_before ( $comment ) { // This plugin ignores non-comments and comments already marked as spam if( $comment->type == Comment::COMMENT && $comment->status != Comment::STATUS_SPAM ) { $comment->status = Comment::STATUS_APPROVED; EventLog::log( 'Comment by ' . $comment->name . ' automatically approved.', 'info', 'autoapprove', 'autoapprove' ); } return $comment; } function set_priorities() { return array( 'action_comment_insert_before' => 10 ); } } ?> <file_sep><?php $theme->display ('header'); ?> <div id="container"> <div id="content"> <div class="hentry post error404"> <h2 class="entry-title"><?php _e('Error!'); ?></h2> <div class="entry-content"> <p><?php _e('The requested post was not found.'); ?></p> </div> </div><!-- .post --> </div><!-- #content --> </div><!-- #container --> <?php $theme->display ('sidebar'); ?> <?php $theme->display ('footer'); ?> <file_sep><?php /** * drop.io Silo * drop.io Silo * * @package dropiosilo * @version $Id$ * @author ayunyan <<EMAIL>> * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link http://ayu.commun.jp/habari-dropiosilo */ class DropioSilo extends Plugin implements MediaSilo { const SILO_NAME= 'drop.io'; /** * plugin information * * @access public * @retrun void */ public function info() { return array( 'name' => 'drop.io Silo', 'version' => '0.02-alpha', 'url' => 'http://ayu.commun.jp/habari-dropiosilo', 'author' => 'ayunyan', 'authorurl' => 'http://ayu.commun.jp/', 'license' => 'Apache License 2.0', 'description' => 'drop.io silo (http://drop.io/)', 'guid' => 'e9f30bd4-be96-11dd-aff6-001b210f913f' ); } /** * action: plugin_activation * * @access public * @param string $file * @return void */ public function action_plugin_activation($file) { if (Plugins::id_from_file($file) != Plugins::id_from_file(__FILE__)) return; Options::set('dropiosilo__api_key', ''); Options::set('dropiosilo__drop_name', ''); Options::set('dropiosilo__password', ''); } /** * action: init * * @access public * @return void */ public function action_init() { $this->load_text_domain('dropiosilo'); } /** * action: update_check * * @access public * @return void */ public function action_update_check() { Update::add($this->info->name, $this->info->guid, $this->info->version); } /** * action: plugin_ui * * @access public * @param string $plugin_id * @param string $action * @return void */ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id != $this->plugin_id()) return; if ($action == _t('Configure')) { $form = new FormUI(strtolower(get_class($this))); $form->append('text', 'api_key', 'dropiosilo__api_key', _t('API Key: ', 'dropiosilo')); $form->append('label', 'api_key_get_label', '<a href="http://api.drop.io/" target="_blank">doesn\'t have API Key?</a>'); $form->append('text', 'drop_name', 'dropiosilo__drop_name', _t('Drop Name: ', 'dropiosilo')); $form->append('password', '<PASSWORD>', '<PASSWORD>', _t('Guest Password (optional): ', '<PASSWORD>')); $form->append('submit', 'save', _t('Save')); $form->out(); } } /** * actuin: admin_footer * * @access public * @param string $theme * @return void */ public function action_admin_footer($theme) { if ($theme->page != 'publish') return; ?> <script type="text/javascript"> habari.media.output.dropiosilo = { display: function(fileindex, fileobj) { habari.editor.insertSelection('<a href="' + fileobj.url + '"><img src="' + fileobj.thumbnail_url + '" alt="' + fileobj.title + '" /></a>'); } } habari.media.preview.dropiosilo = function(fileindex, fileobj) { return '<div class="mediatitle"><a href="' + fileobj.dropiosilo_url + '" class="medialink">media</a>' + fileobj.title + '</div><img src="' + fileobj.thumbnail_url + '"><div class="mediastats"></div>'; } </script> <?php } /** * filter: plugin_config * * @access public * @return array */ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()) { $actions[] = _t('Configure'); } return $actions; } /** * filter: media_controls * * @access public * @param array $controls * @param object $silo * @param string $path * @param string $panelname * @return array */ public function filter_media_controls($controls, $silo, $path, $panelname) { $class = __CLASS__; if (!($silo instanceof $class)) return $controls; if(User::identify()->can('upload_media')) { $controls[] = '<a href="#" onclick="habari.media.showpanel(\'' . self::SILO_NAME . '/' . $path . '\', \'upload\');return false;">' . _t('Upload', 'dropiosilo') . '</a>'; } return $controls; } /** * filter: media_panels * * @access public */ public function filter_media_panels($panel, $silo, $path, $panelname) { $class = __CLASS__; if (!($silo instanceof $class)) return $panel; switch($panelname) { case 'upload': if (isset($_FILES['file'])) { if (!is_uploaded_file($_FILES['file']['tmp_name'])) { return _t('File Uploading Attack Detected!', 'dropiosilo'); } $dropio = new DropioAPI(Options::get('dropiosilo__api_key'), Options::get('dropiosilo__drop_name'), Options::get('dropiosilo__password')); try { $result = $dropio->upload($_FILES['file']['tmp_name'], $_FILES['file']['name']); } catch (Exception $e) { return sprintf(_t('File Upload Failed: %s', 'dropiosilo'), $e->getMessage()); } $panel .= '<p>' . _t('File upload successfully.', 'dropiosilo') . '</p>'; } else { ob_start(); ?> <div class="container transparent"> <form action="<?php URL::out('admin_ajax', array('context' => 'media_panel')); ?>" method="post" enctype="multipart/form-data" target="dropiosilo_upload_frame"> <input type="hidden" name="path" value="<?php echo self::SILO_NAME . '/' . $path; ?>"> <input type="hidden" name="panel" value="<?php echo $panelname; ?>" /> <?php _e('File:', 'dropiosilo'); ?> <input type="file" name="file" /> <input type="submit" value="<?php _e('Upload', 'dropiosilo'); ?>" /> </form> <iframe id="dropiosilo_upload_frame" name="dropiosilo_upload_frame" style="width: 1px; height: 1px;" onload="dropiosilo_uploaded();"></iframe> <script type="text/javascript"> var responsedata; function dropiosilo_uploaded() { if(!$('#dropiosilo_upload_frame')[0].contentWindow) return; var response = $($('#dropiosilo_upload_frame')[0].contentWindow.document.body).text(); if(response) { console.log(response); eval('responsedata = ' + response); window.setTimeout(dropiosilo_uploaded_complete, 500); } } function dropiosilo_uploaded_complete() { habari.media.jsonpanel(responsedata); } </script> </div> <?php $panel = ob_get_clean(); } break; } return $panel; } /** * silo info * * @access public * @return string */ public function silo_info() { $dropio = new DropioAPI(Options::get('dropiosilo__api_key'), Options::get('dropiosilo__drop_name'), Options::get('dropiosilo__password')); try { $dropio->check(); return array( 'name' => self::SILO_NAME, 'icon' => $this->get_url() . '/img/icon.png' ); } catch (Exception $e) { Session::error(sprintf(_t('drop.io Silo: %s', 'dropiosilo'), $e->getMessage())); return array(); } } /** * silo dir * * @access public * @return */ public function silo_dir($path) { $paths = explode('/', $path); $results = array(); $dropio = new DropioAPI(Options::get('dropiosilo__api_key'), Options::get('dropiosilo__drop_name'), Options::get('dropiosilo__password')); try { $assets = $dropio->get_assets(); } catch (Exception $e) { return array(); } for ($i = 0; $i < count($assets); $i++) { if ($assets[$i]->type != 'image') continue; $props = array(); $props['title'] = $assets[$i]->title; $props['url'] = $assets[$i]->converted; $props['thumbnail_url'] = $assets[$i]->thumbnail; $props['dropiosilo_url'] = 'http://drop.io/' . Options::get('dropiosilo__drop_name') . '/asset/' . $assets[$i]->name; $props['filetype'] = 'dropiosilo'; $results[] = new MediaAsset(self::SILO_NAME . '/' . Options::get('dropiosilo__drop_name') . '/' . $assets[$i]->name, false, $props); } return $results; } /** * silo get * * @access public */ public function silo_get($path, $qualities = null) { } /** * silo_put * * @access public */ public function silo_put($path, $filedata) { // TODO: built-in file uploading mechanism is not implemented? } /** * silo_url * * @access public * @param string $path * @param string $qualities */ public function silo_url($path, $qualities = null) { } /** * silo_delete * * @access public * @param string $path */ public function silo_delete($path) { } /** * silo highlights * * @access public */ public function silo_highlights() { } /** * silo permissions * * @access public * @param string $path */ public function silo_permissions($path) { } /** * silo contents * * @access public */ public function silo_contents() { } } class DropioAPI { private $api_key; private $drop_name; private $token; private $base_url = 'http://api.drop.io/drops/'; private $upload_url = 'http://assets.drop.io/upload'; /** * constructer * * @access public * @param string $api_key * @param string $drop_name */ public function __construct($api_key, $drop_name, $token = '') { $this->api_key = $api_key; $this->drop_name = $drop_name; $this->token = $token; } /** * api_key and drop_name check * * @access public */ public function check() { $request = new RemoteRequest($this->base_url . $this->drop_name . '?api_key=' . $this->api_key . '&token=' . $this->token . '&version=1.0&format=json', 'GET'); $result = $request->execute(); if ($result !== true) throw new Exception('Invalid API Key, Drop Name or Password.'); $respose = json_decode($request->get_response_body()); if (isset($response->result) && $response->result == 'Failure') { throw new Exception($response->message); } return true; } /** * get assets list * * @access public */ public function get_assets() { $request = new RemoteRequest($this->base_url . $this->drop_name . '/assets?api_key=' . $this->api_key . '&token=' . $this->token . '&version=1.0&format=json', 'GET'); $result = $request->execute(); if ($result !== true) throw new Exception('Invalid API Key, Drop Name or Password.'); $response = json_decode($request->get_response_body()); if (isset($response->result) && $response->result == 'Failure') { throw new Exception($response->message); } return $response; } /** * upload * * @access public */ public function upload($filename, $override_filename = null) { $request = new MyRemoteRequest($this->upload_url, 'POST'); $request->set_postdata('version', '1.0'); $request->set_postdata('api_key', $this->api_key); $request->set_postdata('token', $this->token); $request->set_postdata('drop_name', $this->drop_name); $request->set_file('file', $filename, null, $override_filename); $result = $request->execute(); if ($result !== true) throw new Exception('Invalid API Key, Drop Name or Password.'); $response = json_decode($request->get_response_body()); if (isset($response->result) && $response->result == 'Failure') { throw new Exception($response->message); } return $response; } } class MyRemoteRequest { private $method = 'GET'; private $url; private $params = array(); private $headers = array(); private $postdata = array(); private $files = array(); private $body = ''; private $timeout = 180; private $processor = NULL; private $executed = FALSE; private $response_body = ''; private $response_headers = ''; private $user_agent = 'Habari'; /** * @param string $url URL to request * @param string $method Request method to use (default 'GET') * @param int $timeuot Timeout in seconds (default 180) */ public function __construct( $url, $method = 'GET', $timeout = 180 ) { $this->method = strtoupper( $method ); $this->url = $url; $this->set_timeout( $timeout ); $this->user_agent .= '/' . Version::HABARI_VERSION; $this->add_header( array( 'User-Agent' => $this->user_agent ) ); // can't use curl's followlocation in safe_mode with open_basedir, so // fallback to srp for now if ( function_exists( 'curl_init' ) && ! ( ini_get( 'safe_mode' ) && ini_get( 'open_basedir' ) ) ) { $this->processor = new MyCURLRequestProcessor; } else { $this->processor = new SocketRequestProcessor; } } /** * DO NOT USE THIS FUNCTION. * This function is only to be used by the test case for RemoteRequest! */ public function __set_processor( $processor ) { $this->processor = $processor; } /** * Add a request header. * @param mixed $header The header to add, either as a string 'Name: Value' or an associative array 'name'=>'value' */ public function add_header( $header ) { if ( is_array( $header ) ) { $this->headers = array_merge( $this->headers, $header ); } else { list( $k, $v )= explode( ': ', $header ); $this->headers[$k]= $v; } } /** * Add a list of headers. * @param array $headers List of headers to add. */ public function add_headers( $headers ) { foreach ( $headers as $header ) { $this->add_header( $header ); } } /** * Set the request body. * Only used with POST requests, will raise a warning if used with GET. * @param string $body The request body. */ public function set_body( $body ) { if ( $this->method !== 'POST' ) return Error::raise( _t('Trying to add a request body to a non-POST request'), E_USER_WARNING ); $this->body = $body; } /** * Set the request query parameters (i.e., the URI's query string). * Will be merged with existing query info from the URL. * @param array $params */ public function set_params( $params ) { if ( ! is_array( $params ) ) $params = parse_str( $params ); $this->params = $params; } /** * Set the timeout. * @param int $timeout Timeout in seconds */ public function set_timeout( $timeout ) { $this->timeout = $timeout; return $this->timeout; } /** * set postdata * * @access public * @param mixed $name * @param string $value */ public function set_postdata($name, $value = null) { if (is_array($name)) { $this->postdata = array_merge($this->postdata, $name); } else { $this->postdata[$name] = $value; } } /** * set file * * @access public * @param string $name * @param string $filename * @param string $content_type */ public function set_file($name, $filename, $content_type = null, $override_filename = null) { if (!file_exists($filename)) { return Error::raise(sprintf(_t('File %s not found.'), $filename), E_USER_WARNING); } if (empty($content_type)) $content_type = 'application/octet-stream'; $this->files[$name] = array('filename' => $filename, 'content_type' => $content_type, 'override_filename' => $override_filename); $this->headers['Content-Type'] = 'multipart/form-data'; } /** * A little housekeeping. */ private function prepare() { // remove anchors (#foo) from the URL $this->url = $this->strip_anchors( $this->url ); // merge query params from the URL with params given $this->url = $this->merge_query_params( $this->url, $this->params ); if ( $this->method === 'POST' ) { if ( ! isset( $this->headers['Content-Type'] ) || $this->headers['Content-Type'] == 'application/x-www-form-urlencoded') { // TODO should raise a warning $this->add_header( array( 'Content-Type' => 'application/x-www-form-urlencoded' ) ); $this->body = http_build_query($this->postdata, '', '&'); } elseif ($this->headers['Content-Type'] == 'multipart/form-data') { $boundary = md5(Utils::nonce()); $this->headers['Content-Type'] .= '; boundary=' . $boundary; $parts = array(); @reset($this->postdata); while (list($name, $value) = @each($this->postdata)) { $parts[] = "Content-Disposition: form-data; name=\"{$name}\"\r\n\r\n{$value}\r\n"; } @reset($this->files); while (list($name, $fileinfo) = @each($this->files)) { $filename = basename($fileinfo['filename']); if (!empty($fileinfo['override_filename'])) $filename = $fileinfo['override_filename']; $part = "Content-Disposition: form-data; name=\"{$name}\"; filename=\"{$filename}\"\r\n"; $part .= "Content-Type: {$fileinfo['content_type']}\r\n\r\n"; $part .= file_get_contents($fileinfo['filename']) . "\r\n"; $parts[] = $part; } $this->body = "--{$boundary}\r\n" . join("--{$boundary}\r\n", $parts) . "--{$boundary}--\r\n"; } $this->add_header( array( 'Content-Length' => strlen( $this->body ) ) ); } } /** * Actually execute the request. * On success, returns TRUE and populates the response_body and response_headers fields. * On failure, throws error. */ public function execute() { $this->prepare(); $result = $this->processor->execute( $this->method, $this->url, $this->headers, $this->body, $this->timeout ); if ( $result && ! Error::is_error( $result ) ) { // XXX exceptions? $this->response_headers = $this->processor->get_response_headers(); $this->response_body = $this->processor->get_response_body(); $this->executed = TRUE; return TRUE; } else { // actually, processor->execute should throw an Error which would bubble up // we need a new Error class and error handler for that, though $this->executed = FALSE; return $result; } } public function executed() { return $this->executed; } /** * Return the response headers. Raises a warning and returns '' if the request wasn't executed yet. */ public function get_response_headers() { if ( !$this->executed ) return Error::raise( _t('Trying to fetch response headers for a pending request.'), E_USER_WARNING ); return $this->response_headers; } /** * Return the response body. Raises a warning and returns '' if the request wasn't executed yet. */ public function get_response_body() { if ( !$this->executed ) return Error::raise( _t('Trying to fetch response body for a pending request.'), E_USER_WARNING ); return $this->response_body; } /** * Remove anchors (#foo) from given URL. */ private function strip_anchors( $url ) { return preg_replace( '/(#.*?)?$/', '', $url ); } /** * Call the filter hook. */ private function __filter( $data, $url ) { return Plugins::filter( 'remoterequest', $data, $url ); } /** * Merge query params from the URL with given params. * @param string $url The URL * @param string $params An associative array of parameters. */ private function merge_query_params( $url, $params ) { $urlparts = InputFilter::parse_url( $url ); if ( ! isset( $urlparts['query'] ) ) { $urlparts['query']= ''; } if ( ! is_array( $params ) ) { parse_str( $params, $params ); } $urlparts['query']= http_build_query( array_merge( Utils::get_params( $urlparts['query'] ), $params ), '', '&' ); return InputFilter::glue_url( $urlparts ); } /** * Static helper function to quickly fetch an URL, with semantics similar to * PHP's file_get_contents. Does not support * * Returns the content on success or FALSE if an error occurred. * * @param string $url The URL to fetch * @param bool $use_include_path whether to search the PHP include path first (unsupported) * @param resource $context a stream context to use (unsupported) * @param int $offset how many bytes to skip from the beginning of the result * @param int $maxlen how many bytes to return * @return string description */ public static function get_contents( $url, $use_include_path = FALSE, $context = NULL, $offset =0, $maxlen = -1 ) { $rr = new RemoteRequest( $url ); if ( $rr->execute() === TRUE) { return ( $maxlen != -1 ? substr( $rr->get_response_body(), $offset, $maxlen ) : substr( $rr->get_response_body(), $offset ) ); } else { return FALSE; } } } interface MyRequestProcessor { public function execute( $method, $url, $headers, $body, $timeout ); public function get_response_body(); public function get_response_headers(); } class MyCURLRequestProcessor implements MyRequestProcessor { private $response_body = ''; private $response_headers = ''; private $executed = false; private $can_followlocation = true; /** * Maximum number of redirects to follow. */ private $max_redirs = 5; /** * Temporary buffer for headers. */ private $_headers = ''; public function __construct() { if ( ini_get( 'safe_mode' ) || ini_get( 'open_basedir' ) ) { $this->can_followlocation = false; } } public function execute( $method, $url, $headers, $body, $timeout ) { $merged_headers = array(); foreach ( $headers as $k => $v ) { $merged_headers[]= $k . ': ' . $v; } $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, $url ); // The URL. curl_setopt( $ch, CURLOPT_HEADERFUNCTION, array(&$this, '_headerfunction' ) ); // The header of the response. curl_setopt( $ch, CURLOPT_MAXREDIRS, $this->max_redirs ); // Maximum number of redirections to follow. if ( $this->can_followlocation ) { curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true ); // Follow 302's and the like. } curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); // Return the data from the stream. curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout ); curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout ); curl_setopt( $ch, CURLOPT_HTTPHEADER, $merged_headers ); // headers to send if ( $method === 'POST' ) { curl_setopt( $ch, CURLOPT_POST, true ); // POST mode. curl_setopt( $ch, CURLOPT_POSTFIELDS, $body ); } else { curl_setopt( $ch, CURLOPT_CRLF, true ); // Convert UNIX newlines to \r\n. } $body = curl_exec( $ch ); if ( curl_errno( $ch ) !== 0 ) { return Error::raise( sprintf( _t('%s: CURL Error %d: %s'), __CLASS__, curl_errno( $ch ), curl_error( $ch ) ), E_USER_WARNING ); } if ( curl_getinfo( $ch, CURLINFO_HTTP_CODE ) !== 200 ) { return Error::raise( sprintf( _t('Bad return code (%1$d) for: %2$s'), curl_getinfo( $ch, CURLINFO_HTTP_CODE ), $url ), E_USER_WARNING ); } curl_close( $ch ); // this fixes an E_NOTICE in the array_pop $tmp_headers = explode("\r\n\r\n", substr( $this->_headers, 0, -4 ) ); $this->response_headers = array_pop( $tmp_headers ); $this->response_body = $body; $this->executed = true; return true; } public function _headerfunction( $ch, $str ) { $this->_headers.= $str; return strlen( $str ); } public function get_response_body() { if ( ! $this->executed ) { return Error::raise( _t('Request did not yet execute.') ); } return $this->response_body; } public function get_response_headers() { if ( ! $this->executed ) { return Error::raise( _t('Request did not yet execute.') ); } return $this->response_headers; } } ?><file_sep><?php /** * Create a block with arbitrary content. * */ class PrettyPhoto extends Plugin { public function action_template_header($theme) { Plugins::act('add_prettyphoto_template'); } public function action_add_prettyphoto_template() { Stack::add('template_stylesheet', array($this->get_url() . '/css/prettyPhoto.css', 'screen')); Stack::add('template_header_javascript', $this->get_url() . '/js/jquery.prettyPhoto.js', 'prettyphoto', 'jquery'); } public function action_add_prettyphoto_admin() { Stack::add('admin_stylesheet', array($this->get_url() . '/css/prettyPhoto.css', 'screen')); Stack::add('admin_header_javascript', $this->get_url() . '/js/jquery.prettyPhoto.js', 'prettyphoto', 'jquery'); } } ?> <file_sep><?php class RateItLogs extends ArrayObject { } ?><file_sep><?php class LimitAccessPlugin extends Plugin { private $fetch_real = false; /** * function info * Returns information about this plugin * @return array Plugin info array **/ function info() { return array ( 'name' => 'Limit Access', 'url' => 'http://habariproject.org/', 'author' => '<NAME>', 'authorurl' => 'http://asymptomatic.net/', 'version' => '1.0', 'description' => 'Limits certain users to specific features - to eventually be replaced by the full core ACL implementation', 'license' => 'Apache License 2.0', ); } function action_theme_admin_user($user) { $configure = $user->info->limitaccess == 0 ? ' selected="selected" ' : ''; $full = $user->info->limitaccess == 1 ? ' selected="selected" ' : ''; $limited = $user->info->limitaccess == 2 ? ' selected="selected" ' : ''; if($user->id == User::identify()->id) { return; } $editor = User::identify(); if(isset($editor->info->limitaccess) && $editor->info->limitaccess > 0) { return; } echo <<< LIMIT_USER_UI <div class="container settings regionalsettings" id="regionalsettings"> <h2>Limit Access</h2> <div class="item clear" id="limit_access"> <span class="pct20"> <label for="timezone">Limit Access</label> </span> <span class="pct80"> <select id="limitaccess" name="limitaccess"> <option value="0" $configure>Full Access and Configure Limits</option> <option value="1" $full>Full Access</option> <option value="2" $limited>Limit Access</option> </select> </span> </div> </div> LIMIT_USER_UI; } function filter_adminhandler_post_user_fields($fields) { $user = User::identify(); if(isset($user->info->limitaccess) && $user->info->limitaccess == 0) { $fields['limitaccess'] = 'limitaccess'; } return $fields; } function filter_adminhandler_post_loadplugins_main_menu($menus) { $user = User::identify(); if($this->fetch_real || $user->info->limitaccess <= 1) { return $menus; } $t_limited_menus = $this->get_menu(); $limited_menus = array(); foreach($t_limited_menus as $mk => $m2) { if(Options::get('limitaccess__' . $mk)) { $limited_menus[$mk] = $m2; } } $menus = array_intersect_key($menus, $limited_menus); return $menus; } public function filter_plugin_config($actions, $plugin_id) { $user = User::identify(); if(isset($user->info->limitaccess) && $user->info->limitaccess > 0) { return $actions; } if ($plugin_id == $this->plugin_id()) { $actions[] = _t('Configure'); } return $actions; } public function action_plugin_ui($plugin_id, $action) { if ($plugin_id == $this->plugin_id()) { switch ($action) { case _t('Configure'): $ui = new FormUI('limitaccess'); $menus = $this->get_menu(); $ui->append('fieldset', 'accessmenus', 'Available Menus'); $ui->accessmenus->append('static', 'accessdescription', 'Please select the menu options that will be available to users with limited access.'); foreach($menus as $menu_key => $menu) { $ui->accessmenus->append('checkbox', $menu_key, 'limitaccess__' . $menu_key, $menu['text']); } $ui->append('submit', 'save', 'save'); $ui->out(); break; } } } protected function get_menu() { $createmenu = array(); $managemenu = array(); foreach( Post::list_active_post_types() as $type => $typeint ) { if ( $typeint == 0 ) { continue; } $createmenu['create_' . $typeint]= array( 'url' => 'page=publish&content_type=' . $type, 'text' => sprintf( _t( 'Create %s' ), ucwords( $type ) ) ); $managemenu['manage_' . $typeint]= array( 'url' => 'page=posts&type=' . $typeint, 'text' => sprintf( _t( 'Manage %s' ), ucwords( $type ) ) ); } $adminmenu = array( 'comments' => array( 'url' => 'page=comments' , 'text' => _t( 'Comments' ), ), 'tags' => array( 'url' => 'page=tags' , 'text' => _t( 'Tags' ), ), 'dashboard' => array( 'url' => 'page=' , 'text' => _t( 'Dashboard' ), ), 'options' => array( 'url' => 'page=options' , 'text' => _t( 'Options' ), ), 'themes' => array( 'url' => 'page=themes' , 'text' => _t( 'Themes' ), ), 'plugins' => array( 'url' => 'page=plugins' , 'text' => _t( 'Plugins' ), ), 'import' => array( 'url' => 'page=import' , 'text' => _t( 'Import' ), ), 'users' => array( 'url' => 'page=users' , 'text' => _t( 'Users' ), ), 'logs' => array( 'url' => 'page=logs', 'text' => _t( 'Logs' ), ) , 'logout' => array( 'url' => 'page=logout' , 'text' => _t( 'Logout' ), ), 'user' => array( 'url' => 'page=user&userid=' . User::identify()->id , 'text' => _t( 'User\'s own profile page' ), ), 'otheruser' => array( 'url' => 'page=user' , 'text' => _t( 'Other user\'s profile page' ), ), ); $mainmenus = array_merge( $createmenu, $managemenu, $adminmenu ); return $mainmenus; } public function action_before_act_admin() { $user = User::identify(); if(isset($user->info->limitaccess) && $user->info->limitaccess == 0) { return; } Plugins::register(array($this, 'kill_admin_user'), 'action', 'admin_theme_get_user'); Plugins::register(array($this, 'kill_admin_user'), 'action', 'admin_theme_post_user'); $menus = $this->get_menu(); foreach($menus as $mk => $m2) { if(!Options::get('limitaccess__' . $mk)) { $params = Utils::get_params($m2['url']); $page = $params['page']; unset($params['page']); $kill = true; foreach($params as $k => $v) { if(Controller::get_var($k) != $v) { $kill = false; } } if($page == 'user') { $kill = false; } if ($kill) { Plugins::register(array($this, 'kill_admin'), 'action', 'admin_theme_post_' . $page); Plugins::register(array($this, 'kill_admin'), 'action', 'admin_theme_get_' . $page); } } } } public function kill_admin_user($admin) { // Special cases if(!Options::get('limitaccess__otheruser') && isset($admin->handler_vars['user'])) { die('This menu option is not available to you.'); } if(!Options::get('limitaccess__user') && !isset($admin->handler_vars['user'])) { die('This menu option is not available to you.'); } } protected function kill_admin() { die('This menu option is not available to you.'); } } ?><file_sep><?php /** * Fresh Comments * * For those who really miss Brian’s Latest Comments. :) * Usage: <?php $theme->freshcomments(); ?> **/ class FreshComments extends Plugin { private $config = array(); private $class_name = ''; private $cache_name = ''; private static function default_options() { return array ( 'num_posts' => 5, 'num_comments' => 6, 'show_trackbacks' => FALSE, 'show_pingbacks' => FALSE, 'fade_old' => TRUE, 'range_in_days' => 10, 'newest_color' => '#444444', 'oldest_color' => '#cccccc' ); } /** * Required plugin information * @return array The array of information **/ public function info() { return array( 'name' => 'Fresh Comments', 'version' => '0.3', 'url' => 'http://code.google.com/p/bcse/wiki/FreshComments', 'author' => '<NAME>', 'authorurl' => 'http://blog.bcse.info/', 'license' => 'Apache License 2.0', 'description' => _t('Allow you display recent comments just like Brian’s latest Comment.', $this->class_name) ); } /** * Add update beacon support **/ public function action_update_check() { Update::add('Fresh Comments', '5f5f68a0-fc19-47c2-969f-25dcc9959f7d', $this->info->version); } /** * Add actions to the plugin page for this plugin * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id **/ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()) { $actions[] = _t('Configure', $this->class_name); } return $actions; } /** * Respond to the user selecting an action on the plugin page * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook **/ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id == $this->plugin_id()) { switch ($action) { case _t('Configure', $this->class_name) : $ui = new FormUI(strtolower(get_class($this))); $ui->append('fieldset', 'general', _t('General', $this->class_name)); $ui->general->append('text', 'num_posts', 'option:' . $this->class_name . '__num_posts', _t('&#8470; of Posts', $this->class_name)); $ui->general->num_posts->add_validator(array($this, 'validate_uint')); $ui->general->num_posts->add_validator('validate_required'); $ui->general->append('text', 'num_comments', 'option:' . $this->class_name . '__num_comments', _t('&#8470; of Comments', $this->class_name)); $ui->general->num_comments->add_validator(array($this, 'validate_uint')); $ui->general->num_comments->add_validator('validate_required'); $ui->general->append('checkbox', 'show_trackbacks', 'option:' . $this->class_name . '__show_trackbacks', _t('Show Trackbacks', $this->class_name)); $ui->general->append('checkbox', 'show_pingbacks', 'option:' . $this->class_name . '__show_pingbacks', _t('Show Pingbacks', $this->class_name)); $ui->append('fieldset', 'fade', _t('Fade-out', $this->class_name)); $ui->fade->append('checkbox', 'fade_old', 'option:' . $this->class_name . '__fade_old', _t('Fade-out Older Comment', $this->class_name)); $ui->fade->append('text', 'range_in_days', 'option:' . $this->class_name . '__range_in_days', _t('Fading Speed (bigger is slower)', $this->class_name)); $ui->fade->range_in_days->add_validator(array($this, 'validate_uint')); $ui->fade->range_in_days->add_validator('validate_required'); $ui->fade->append('text', 'newest_color', 'option:' . $this->class_name . '__newest_color', _t('Newest Color', $this->class_name)); $ui->fade->newest_color->add_validator(array($this, 'validate_color')); $ui->fade->newest_color->add_validator('validate_required'); $ui->fade->append('text', 'oldest_color', 'option:' . $this->class_name . '__oldest_color', _t('Oldest Color', $this->class_name)); $ui->fade->oldest_color->add_validator(array($this, 'validate_color')); $ui->fade->oldest_color->add_validator('validate_required'); $ui->append('submit', 'save', _t('Save', $this->class_name)); $ui->set_option('success_message', _t('Options saved', $this->class_name)); $ui->out(); break; } } } public function validate_uint($value) { if (!ctype_digit($value) || strstr($value, '.') || $value < 0) { return array(_t('This field must be positive integer.', $this->class_name)); } return array(); } public function validate_color($value) { if (!preg_match('/^#[0-9a-z]{6}$/i', $value)) { return array(_t('This field must be an HTML color hex code.', $this->class_name)); } return array(); } /** * Returns true if plugin config form values defined in action_plugin_ui should be stored in options by Habari * @return bool True if options should be stored **/ public function updated_config($ui) { return true; } /** * Return the HTML of Fresh Comments * @param Theme $theme The theme that will display the template **/ public function theme_freshcomments($theme) { if (Cache::has($this->cache_name)) { return Cache::get($this->cache_name); } else { $comment_types = array(Comment::COMMENT); if ($this->config['show_trackbacks']) $comment_types[] = Comment::TRACKBACK; if ($this->config['show_pingbacks']) $comment_types[] = Comment::PINGBACK; $query = 'SELECT {posts}.* FROM {posts} INNER JOIN {comments} ON ({posts}.id = {comments}.post_id) WHERE {posts}.status = ? AND {comments}.status = ? AND ({comments}.type = ?' . str_repeat(' OR {comments}.type = ?', count($comment_types) - 1) . ') GROUP BY {posts}.id ORDER BY {comments}.date DESC, {posts}.id DESC LIMIT ' . $this->config['num_posts']; $query_args = array_merge(array(Post::status('published'), Comment::STATUS_APPROVED), $comment_types); $commented_posts = DB::get_results($query, $query_args, 'Post'); $freshcomments = array(); foreach ($commented_posts as $i => $post) { $query = 'SELECT * FROM {comments} WHERE post_id = ? AND status = ? AND (type = ?' . str_repeat(' OR type = ?', count($comment_types) - 1) . ') ORDER BY date DESC LIMIT ' . $this->config['num_comments']; $query_args = array_merge(array($post->id, Comment::STATUS_APPROVED), $comment_types); $comments = DB::get_results($query, $query_args, 'Comment'); $freshcomments[$i]['post'] = $post; foreach ($comments as $j => $comment) { $freshcomments[$i]['comments'][$j]['comment'] = $comment; $freshcomments[$i]['comments'][$j]['color'] = $this->get_color($comment->date); } } $theme->freshcomments = $freshcomments; $html = $theme->fetch('freshcomments'); Cache::set($this->cache_name, $html, 3600); return $html; } } protected static function sanitize_color($new_color) { return round(max(0, min(255, $new_color))); } protected function get_color($comment_date) { if ($this->config['fade_old']) { $time_span = ($_SERVER['REQUEST_TIME'] - $comment_date->int) / $this->config['range_in_seconds']; $time_span = min($time_span, 1); $color = array( 'r' => self::sanitize_color($this->config['newest_color']['r'] + $this->config['color_range']['r'] * $time_span), 'g' => self::sanitize_color($this->config['newest_color']['g'] + $this->config['color_range']['g'] * $time_span), 'b' => self::sanitize_color($this->config['newest_color']['b'] + $this->config['color_range']['b'] * $time_span) ); return '#' . ColorUtils::rgb_hex($color); } else { return $this->config['newest_color']; } } /** * On plugin activation, set the default options */ public function action_plugin_activation($file) { if (realpath($file) == __FILE__) { $this->class_name = strtolower(get_class($this)); $this->cache_name = Site::get_url('host') . $this->class_name; foreach (self::default_options() as $name => $value) { $current_value = Options::get($this->class_name . '__' . $name); if (is_null($current_value)) { Options::set($this->class_name . '__' . $name, $value); } } } } /** * On plugin deactivation, expire the cache */ public function action_plugin_deactivation($file) { if (realpath($file) == __FILE__) { Cache::expire($this->cache_name); } } /** * After a new and approved comment is inserted, expire the cache */ public function action_comment_insert_after($comment) { if ($comment->status === COMMENT::STATUS_APPROVED) { Cache::expire($this->cache_name); } } /** * After an approved comment is updated, expire the cache */ public function action_comment_update_after($comment) { if ($comment->status === COMMENT::STATUS_APPROVED) { Cache::expire($this->cache_name); } } /** * After an approved comment is deleted, expire the cache */ public function action_comment_delete_after($comment) { if ($comment->status === COMMENT::STATUS_APPROVED) { Cache::expire($this->cache_name); } } /** * On plugin init, add the template included with this plugin to the available templates in the theme */ public function action_init() { $this->class_name = strtolower(get_class($this)); $this->cache_name = Site::get_url('host') . $this->class_name; foreach (self::default_options() as $name => $value) { $this->config[$name] = Options::get($this->class_name . '__' . $name); } // Calculate colors if ($this->config['fade_old']) { $this->config['range_in_seconds'] = $this->config['range_in_days'] * 24 * 60 * 60 ; $this->config['newest_color'] = ColorUtils::hex_rgb($this->config['newest_color']); $this->config['oldest_color'] = ColorUtils::hex_rgb($this->config['oldest_color']); $this->config['color_range'] = array( 'r' => $this->config['oldest_color']['r'] - $this->config['newest_color']['r'], 'g' => $this->config['oldest_color']['g'] - $this->config['newest_color']['g'], 'b' => $this->config['oldest_color']['b'] - $this->config['newest_color']['b'] ); } $this->load_text_domain($this->class_name); $this->add_template('freshcomments', dirname(__FILE__) . '/freshcomments.php'); } } ?> <file_sep><?php class InstantSearch extends Plugin { /** * Register the template. **/ function action_init() { $this->add_template( "block.instant_search", dirname( __FILE__ ) . "/block.instant_search.php" ); } /** * Add block to the list of selectable blocks **/ public function filter_block_list( $block_list ) { $block_list[ 'instant_search' ] = _t( 'Instant Search', 'instant_search' ); return $block_list; } /** * Add required Javascript */ public function theme_header($theme) { // Add the jQuery library Stack::add( 'template_header_javascript', Site::get_url('scripts') . '/jquery.js', 'jquery' ); Stack::add( 'template_header_javascript', $this->get_url() . '/instant_search.js', 'instant_search', array( 'jquery' ) ); // Add the callback URL. $url = "InstantSearch.url = '" . URL::get( 'ajax', array( 'context' => 'instant_search') ) . "';"; Stack::add('template_header_javascript', $url, 'instant_search_url', 'instant_search'); } /** * Respond to Javascript callbacks * The name of this method is action_ajax_ followed by what you passed to the context parameter above. */ public function action_ajax_instant_search( $handler ) { // Get the data that was sent $response = $handler->handler_vars[ 'q' ]; // Wipe anything else that's in the buffer ob_end_clean(); $new_response = Posts::get( array( "criteria"=>$response ) ); $final_response = array(); foreach ( $new_response as $post ) { $final_response[] = array( 'title' => $post->title, 'content' => $post->content, 'pubdate' => $post->pubdate->format(), 'updated' => $post->updated->format(), 'modified' => $post->modified->format(), 'url' => $post->permalink, ); } // Send the response echo json_encode( $final_response ); } } ?> <file_sep> <div id="sidebar"> <div class="block"> <form method="get" id="search" action="<?php URL::out( 'display_search' ); ?>"> <p><input type="text" id="searchfield" name="criteria" value="<?php if ( isset( $criteria ) ) { echo htmlentities($criteria, ENT_COMPAT, 'UTF-8'); } ?>"> <input type="submit" id="searchsubmit" value="<?php _e( 'Search' ); ?>"></p> </form> </div> <div class="block"> <h2><?php _e( 'Tags' ); ?></h2> <?php $theme->tag_cloud(5); ?> <a href="<?php Site::out_url( 'habari' ); ?>/tag"><?php _e( 'more' ); ?>...</a> </div> <br> <div class="block"> <h2><?php _e('Archive'); ?></h2> <?php $theme->monthly_archives(0, 'N'); ?> </div> <?php $theme->area( 'sidebar' ); ?> </div> <div id="footer"> <p><?php printf( _t( '%1$s is powered by %2$s' ), Options::get( 'title' ),' <a href="http://www.habariproject.org/" title="Habari">Habari ' . Version::HABARI_VERSION . '</a>' ); ?> - <a href="<?php URL::out( 'atom_feed', array( 'index' => '1' ) ); ?>"><?php _e( 'Atom Entries' ); ?></a><?php _e( ' and ' ); ?> <a href="<?php URL::out( 'atom_feed_comments' ); ?>"><?php _e( 'Atom Comments' ); ?></a></p> </div> <?php $theme->footer(); ?> </body> </html> <file_sep><?php $theme->display('header'); ?> <!-- page.single --> <div id="content" class="hfeed"> <div id="page-<?php echo $post->slug; ?>" class="hentry page <?php echo $post->statusname , ' ' , $post->tags_class; ?>"> <div class="entry-head"> <h1 class="entry-title"><a href="<?php echo $post->permalink; ?>" title="<?php echo strip_tags($post->title); ?>" rel="bookmark"><?php echo $post->title_out; ?></a></h1> <br class="clear" /> <span class="comments-link"><a href="<?php echo $post->permalink; ?>#comments" title="Comments to this post"> <?php echo $post->comments->approved->count; ?> <?php _ne('Comment', 'Comments', $post->comments->approved->count, 'demorgan'); ?></a></span> <?php if ($loggedin) { ?> <span class="entry-edit"><a href="<?php echo $post->editlink; ?>" title="Edit post">Edit</a></span> <?php } ?> </div> <div class="entry-content"> <?php echo $post->content_out; ?> </div> </div> <?php $theme->display('comments'); ?> </div> <hr /> <!-- /page.single --> <?php $theme->display('sidebar'); ?> <?php $theme->display('footer'); ?> <file_sep><?php /* * Simple PHP interface for the Simplenote API (no pun intended) * Created by <NAME> * http://github.com/abrahamvegh/simplenote-php/ * * USE AT YOUR OWN RISK */ class simplenoteapi { private $email; private $token; /* ***** Internal methods ***** */ /* * Makes all requests to the API * * This method should only be called by the api_* wrapper methods */ private function curl_request($url_append, $curl_options = array()) { $curl_options[CURLOPT_URL] = 'https://simple-note.appspot.com/api/' . $url_append; $curl_options[CURLOPT_HEADER] = true; $curl_options[CURLOPT_RETURNTRANSFER] = true; $ch = curl_init(); curl_setopt_array($ch, $curl_options); $result = curl_exec($ch); $stats = curl_getinfo($ch); $result = explode("\n", $result); $headers = array(); $break = false; unset($result[0]); foreach ($result as $index => $value) { if (!$break) { if (trim($value) == '') { unset($result[$index]); $break = true; } else { $line = explode(':', $value, 2); $headers[$line[0]] = $line[1]; unset($result[$index]); } } } $result = implode("\n", $result); curl_close($ch); $result = array( 'stats' => $stats, 'headers' => $headers, 'body' => $result ); return $result; } /* * Calls the API using a GET */ private function api_get($method, $parameters = '') { if (is_array($parameters)) { foreach ($parameters as $key => $value) { unset($parameters[$key]); $parameters[] = urlencode($key) . '=' . urlencode($value); } $parameters = implode('&', $parameters); } !empty($parameters) ? $parameters = '?' . $parameters : false ; return $this->curl_request($method . $parameters); } /* * Calls the API using a POST */ private function api_post($method, $body, $parameters = '') { $curl_options = array( CURLOPT_POST => true, CURLOPT_POSTFIELDS => $body ); if (is_array($parameters)) { foreach ($parameters as $key => $value) { unset($parameters[$key]); $parameters[] = urlencode($key) . '=' . urlencode($value); } $parameters = implode('&', $parameters); } !empty($parameters) ? $parameters = '?' . $parameters : false ; return $this->curl_request($method . $parameters, $curl_options); } /* ***** Public methods ***** */ /* * Attempts to authenticate and receive an access token * * Saves the token and returns true if successful * Returns false if it fails for any reason */ public function login($email, $password) { $body = base64_encode('email=' . urlencode($email) . '&password=' . urlencode($password)); $response = $this->api_post('login', $body); if ($response['stats']['http_code'] == 200) { $this->email = $email; $this->token = $response['body']; return true; } else { return false; } } /* * Retrieves the index list * * Returns the data in objects, using the json_decode function * Returns false if it fails for any reason */ public function index() { $response = $this->api_get( 'index', array( 'auth' => $this->token, 'email' => $this->email ) ); if ($response['stats']['http_code'] == 200) { $response = json_decode($response['body']); return $response; } else { return false; } } /* * Retrieves a note * * Returns an associative array of the data if successful * Returns false if it fails for any reason */ public function get_note($note_key) { $response = $this->api_get( 'note', array( 'key' => $note_key, 'auth' => $this->token, 'email' => $this->email, 'encode' => 'base64' ) ); if ($response['stats']['http_code'] == 200) { $note = array( 'key' => $response['headers']['note-key'], 'createdate' => $response['headers']['note-createdate'], 'modifydate' => $response['headers']['note-modifydate'], 'deleted' => (strtolower($response['headers']['note-deleted']) == 'true') ? true : false , 'content' => base64_decode($response['body']) ); return $note; } else { return false; } } /* * Updates or creates a note * * Returns the note key if successful * Returns false if it fails for any reason */ public function save_note($content, $note_key = '') { $parameters = array( 'auth' => $this->token, 'email' => $this->email ); if (isset($note_key)) $parameters['key'] = $note_key; $response = $this->api_post( 'note', base64_encode($content), $parameters ); if ($response['stats']['http_code'] == 200) { return $response['body']; } else { // Utils::debug( $response ); return false; } } /* * Deletes a note * * Returns true if successful * Returns false is it fails for any reason */ public function delete_note($note_key) { $response = $this->api_get( 'delete', array( 'key' => $note_key, 'auth' => $this->token, 'email' => $this->email ) ); if ($response['stats']['http_code'] == 200) { return true; } else { return false; } } /* * API-powered search * * Returns data even for zero results * Returns false if it fails for any reason */ public function search($search_term, $max_results = 10, $offset_index = 0) { $response = $this->api_get( 'search', array( 'query' => urlencode($search_term), 'results' => $max_results, 'offset' => $offset_index, 'auth' => $this->token, 'email' => $this->email ) ); if ($response['stats']['http_code'] == 200) { if( json_decode($response['body']) == '' ) { Utils::debug( $response ); } $response = json_decode($response['body']); $return = array( 'count' => $response->Response->totalRecords, 'results' => array() ); if ($return['count'] > 0) { foreach ($response->Response->Results as $result) { if (!empty($result->key)) $return['results'][$result->key] = $result->content; } } return $return; } else { return false; } } } $api = new simplenoteapi; $api->login('<EMAIL>', '<PASSWORD>'); print_r($api->index()); ?><file_sep> <li id="widget-flickrrss" class="widget"> <h3><?php _e('Flickr', 'binadamu'); ?></h3> <ul class="flickr-images"> <?php $theme->flickr_images(); ?> </ul> </li> <file_sep><?php /** * RelatedPosts Plugin - Show the related posts of the provided post. * Copy relatedposts.php to your themedir and style it. * * * Usage: * <code>$theme->related_posts($post);</code> * */ class recent_posts extends Plugin { private $config= array(); private $default_options= array ( 'num_post' => '5', ); /** * Required plugin info() implementation provides info to Habari about this plugin. */ public function info() { return array( 'name' => 'Related Posts', 'url' => '', 'author' =>'eighty4', 'authorurl' => 'http://eighty4.se', 'version' => '0.1', 'description' => 'Show the related posts based on interception of tags Inspired by R<NAME> (a.k.a. tinyau) RN Related Posts', 'license' => 'Apache License 2.0', ); } public function action_update_check() { Update::add( 'RelatedPosts', '5E5B630C-1276-11DE-AFD8-77AF55D89593', $this->info->version ); } /** * Plugin init action, executed when plugins are initialized. */ public function action_init() { $this->class_name= strtolower( get_class( $this ) ); foreach ( $this->default_options as $name => $unused ) { $this->config[$name]= Options::get( $this->class_name . '__' . $name ); } $this->add_template('related_posts', dirname(__FILE__) . '/relatedposts.php'); } /** * Add actions to the plugin page for this plugin * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id **/ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = 'Configure'; } return $actions; } /** * Sets the new 'hide_replies' option to '0' to mimic current, non-reply-hiding * functionality. **/ public function action_plugin_activation( $file ) { if(Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__)) { if ( Options::get( 'related_posts__count' ) == null ) { Options::set( 'related_posts__count', 5 ); } } } /** * Respond to the user selecting an action on the plugin page * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook **/ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case 'Configure' : $ui = new FormUI( strtolower( get_class( $this ) ) ); $ui->append( 'text', 'count', 'related_posts__count', _t( 'No. of Post to be shown' ) ); $ui->append( 'submit', 'save', _t('Save') ); $ui->out(); break; } } } public function theme_related_posts( $theme, $post = null ) { // If $post is an array of posts let's hope we want the first one. // There's probably a better way of doing this but I'm not positive // that [0] won't be called something else in the future. // Go ahead and change this if there's a better solution :) //if( $post instanceOf Posts ) $post = current( $post ); // If we don't give it a post use $theme's if( $post === null ) $post = $theme->posts; $theme->related_entry = array(); if( $post instanceOf Post ) { $post_type = Post::type( 'entry' ); $post_status = Post::status( 'published' ); if( is_array( $post->tags ) && $post->tags ) { $tags = array_keys( $post->tags ); $theme->related_entry = Posts::get( array( 'content_type' => Post::type( 'entry' ), 'status' => Post::status( 'published' ), 'limit' => Options::get( 'related_posts__count' ), 'all:tag' => $tags, // what's the exact difference between all:tag and tag_slug? 'not:id' => $post->id ) ); } } return $theme->fetch( 'related_posts' ); } } ?> <file_sep><?php $theme->display ('header'); ?> <div id="container"> <div id="content"> <div id="post-<?php echo $post->id; ?>" class="hentry page <?php echo $post->statusname , ' ' , $post->tags_class; ?>"> <h2 class="entry-title"><?php echo $post->title_out; ?></h2> <div class="entry-content"> <?php echo $post->content_out; ?> <?php $theme->show_tags(); ?> </div> <?php if ( $post->get_access()->edit ) { ?> <div class="entry-meta"><a href="<?php URL::out( 'admin', 'page=publish&slug=' . $post->slug); ?>" title="<?php _e('Edit post'); ?>"><?php _e('Edit'); ?></a></div> <?php } ?> </div> <?php $theme->display ('comments'); ?> </div><!-- #content --> </div><!-- #container --> <?php $theme->display ('sidebar'); ?> <?php $theme->display ('footer'); ?> <file_sep><?php /** * GoogleMaps * easily/quickly insert Google Maps into your posts. * * @package googlemaps * @version $Id$ * @author ayunyan <<EMAIL>> * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link http://ayu.commun.jp/habari-googlemaps */ class GoogleMaps extends Plugin { /** * action: plugin_activation * * @access public * @param string $file * @return void */ public function action_plugin_activation($file) { if (Plugins::id_from_file($file) != Plugins::id_from_file(__FILE__)) return; Options::set('googlemaps__api_key', ''); Options::set('googlemaps__map_width', 500); Options::set('googlemaps__map_height', 300); Options::set('googlemaps__streetview_width', 500); Options::set('googlemaps__streetview_height', 200); } /** * action: init * * @access public * @return void */ public function action_init() { $this->load_text_domain('googlemaps'); $api_key = Options::get('googlemaps__api_key'); if (empty($api_key)) return; Stack::add('template_header_javascript', 'http://www.google.com/jsapi?key=' . $api_key); Stack::add('template_header_javascript', Site::get_url('scripts') . '/jquery.js', 'jquery'); Stack::add('template_header_javascript', $this->get_url() . '/js/googlemaps.js'); } /** * action: update_check * * @access public * @return void */ public function action_update_check() { Update::add('Google Maps', $this->info->guid, $this->info->version); } /** * action: plugin_ui * * @access public * @param string $plugin_id * @param string $action * @return void */ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id != $this->plugin_id()) return; if ($action == _t('Configure')) { $form = new FormUI( strtolower(get_class($this))); $form->append('text', 'api_key', 'googlemaps__api_key', _t('API Key: ', 'googlemaps')); $map_width = $form->append('text', 'map_width', 'googlemaps__map_width', _t('Map Width: ', 'googlemaps')); $map_width->add_validator('validate_regex', '/^[0-9]+$/'); $map_height = $form->append('text', 'map_height', 'googlemaps__map_height', _t('Map Height: ', 'googlemaps')); $map_height->add_validator('validate_regex', '/^[0-9]+$/'); $streetview_width = $form->append('text', 'streetview_width', 'googlemaps__streetview_width', _t('Streetview Width: ', 'googlemaps')); $streetview_width->add_validator('validate_regex', '/^[0-9]+$/'); $streetview_height = $form->append('text', 'streetview_height', 'googlemaps__streetview_height', _t('Streetview Height: ', 'googlemaps')); $streetview_height->add_validator('validate_regex', '/^[0-9]+$/'); $form->append('submit', 'save', _t('Save')); $form->out(); } } /** * action: admin_header * * @access public * @param object $theme * @return void */ public function action_admin_header( $theme ) { if ($theme->page != 'publish') return; $api_key = Options::get('googlemaps__api_key'); if (empty($api_key)) return; Stack::add('admin_header_javascript', 'http://www.google.com/jsapi?key=' . $api_key); Stack::add('admin_header_javascript', $this->get_url() . '/js/googlemaps_admin.js'); } /** * action: template_header * * @access public * @param object $theme * @return void */ public function action_template_header($theme) { ?> <script type="text/javascript"> var habari_googlemaps = { map_width: <?php Options::out('googlemaps__map_width'); ?>, map_height: <?php Options::out('googlemaps__map_height'); ?>, streetview_width: <?php Options::out('googlemaps__streetview_width'); ?>, streetview_height: <?php Options::out('googlemaps__streetview_height'); ?> }; </script> <?php } /** * action: form_publish * * @access public * @param object $form * @return void */ public function action_form_publish($form) { $container = $form->publish_controls->append('fieldset', 'googlemaps', _t('Google Maps')); ob_start(); ?> <div id="googlemaps" class="container" style="width: 600px;"> <p> <input type="text" id="googlemaps_address" name="googlemaps_address" /> <input type="button" id="googlemaps_search" value="<?php echo _t('Search'); ?>" /> <input type="button" id="googlemaps_streetview_toggle" value="<?php echo _t('Street View', 'googlemaps'); ?>" /> <input type="button" id="googlemaps_insert" value="<?php echo _t('Insert Map', 'googlemaps'); ?>" /> </p> <div id="googlemaps_canvas"></div> <div id="googlemaps_streetview_canvas" style="width: 600px; height: 300px;"></div> </div> <?php $container->append('static', 'static1', ob_get_contents()); ob_end_clean(); } /** * filter: plugin_config * * @access public * @param array $actions * @param integer $plugin_id * @return array */ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()) { $actions[] = _t('Configure'); } return $actions; } } ?><file_sep><?php include_once dirname(__FILE__) . "/pluginsearchinterface.php"; include_once "Zend/Search/Lucene.php"; /** * A wrapper plugin for the Zend Framework implementation of Lucene. * * @todo Add support for the highlighting functionality in the search snippet * * @link http://framework.zend.com/manual/en/zend.search.lucene.html */ class ZendSearchLucene implements PluginSearchInterface { /** * The default limit for retrieving items */ const DEFAULT_LIMIT = 50; /** * The Lucene index object. * * @var Zend_Search_Lucene_Interface */ private $_index; /** * The path to the index file */ private $_index_path; /** * The path to the index file directory */ private $_root_path; /** * Create the object, requires the index location. * * @param string $path */ public function __construct( $path ) { $this->_root_path = $path; $this->_index_path = $this->_root_path . (substr($this->_root_path, -1) == '/' ? '' : '/') . 'zsl.db'; } /** * Null the index so ZSL can clean up. */ public function __destruct() { $this->_index = null; } /** * Check whether the preconditions for the plugin are installed * * @return boolean */ public function check_conditions() { $ok = true; if( !is_writable( $this->_root_path ) ) { Session::error( 'Init failed, Search index directory is not writeable. Please update configuration with a writeable directiory.', 'Multi Search' ); $ok = false; } if( !class_exists("Zend_Search_Lucene") ) { Session::error( 'Init failed, Zend Framework or Zend Search Lucene not installed.', 'Multi Search' ); $ok = false; } return $ok; } /** * Initialise a writable database for updating the index * * @param int flag allow setting the DB to be initialised with PluginSearchInterface::INIT_DB */ public function open_writable_database( $flag = 0 ) { Zend_Search_Lucene::setResultSetLimit( 50 ); Zend_Search_Lucene_Analysis_Analyzer::setDefault( new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8() ); if( PluginSearchInterface::INIT_DB == $flag ) { $this->_index = Zend_Search_Lucene::create($this->_index_path); } else { $this->_index = Zend_Search_Lucene::open($this->_index_path); } } /** * Prepare the database for reading */ public function open_readable_database() { return $this->open_writable_database(); } /** * Return a list of IDs for the given search criteria * * @param string $criteria * @param int $limit * @param int $offset * @return array * * @todo Add caching for pagination rather than current method */ public function get_by_criteria( $criteria, $limit, $offset ) { $hits = $this->_index->find( strtolower( $criteria ) ); $ids = array(); $counter = 1; foreach( $hits as $hit ) { if( $offset < $counter ) { $ids[] = $hit->postid; } $counter++; if( $counter > ($limit+$offset) ) { break; } } return $ids; } /** * Add a post to the index. * * @param Post $post the post being inserted */ public function index_post( $post ) { $doc = new Zend_Search_Lucene_Document(); $doc->addField( Zend_Search_Lucene_Field::Text( 'url', $post->permalink ) ); $title = Zend_Search_Lucene_Field::Text( 'title', strtolower( $post->title ), 'utf-8' ); $title->boost = 50; $doc->addField( $title ); $doc->addField( Zend_Search_Lucene_Field::UnStored( 'contents', strtolower( $post->content ), 'utf-8' ) ); // Add tags $tags = $post->tags; $tagstring = ''; foreach($tags as $tag) { $tagstring .= $tag . ' '; } $dtag = Zend_Search_Lucene_Field::UnStored( 'tags', strtolower( $tagstring ), 'utf-8' ); $dtag->boost = 10; $doc->addField( $dtag ); // Add ID $doc->addField( Zend_Search_Lucene_Field::keyword( 'postid', $post->id ) ); $this->_index->addDocument($doc); } /** * Updates a post. * * @param Post $post */ public function update_post( $post ) { $this->delete_post( $post ); return $this->index_post( $post ); } /** * Remove a post from the index * * @param Post $post the post being deleted */ public function delete_post( $post ) { $term = new Zend_Search_Lucene_Index_Term( $post->id, 'postid' ); $docIds = $this->_index->termDocs( $term ); foreach ( $docIds as $id ) { $this->_index->delete( $id ); } } /** * Return a list of posts that are similar to the current post. * This is not a very good implementation, so do not expect * amazing results - the term vector is not available for a doc * in ZSL, which limits how far you can go! * * @return array ids */ public function get_similar_posts( $post, $max_recommended = 5 ) { Zend_Search_Lucene::setResultSetLimit( $max_recommended + 1 ); $title = $post->title; $tags = $post->tags; $tagstring = ''; foreach($tags as $tag) { $tagstring .= $tag . ' '; } $analyser = Zend_Search_Lucene_Analysis_Analyzer::getDefault(); $tokens = $analyser->tokenize( strtolower( $tagstring ) . ' ' . strtolower( $title ) ); $query = new Zend_Search_Lucene_Search_Query_MultiTerm(); foreach( $tokens as $token ) { $query->addTerm( new Zend_Search_Lucene_Index_Term( $token->getTermText() ) ); } $hits = $this->_index->find( $query ); $ids = array(); $counter = 0; foreach( $hits as $hit ) { if( $hit->postid != $post->id ) { $ids[] = $hit->postid; $counter++; } if( $counter == $max_recommended ) { break; } } return $ids; } /** * Return the spelling correction. Not implemented by * this backend. * * @return string */ public function get_corrected_query_string() { return ''; } }<file_sep><?php $theme->display ('header'); ?> <div id="container"> <div id="content"> <div id="post-<?php echo $post->id; ?>" class="hentry entry <?php echo $post->statusname , ' ' , $post->tags_class; ?>"> <h2 class="entry-title"> <?php $date1 = strtotime( $post->pubdate ); $date2 = $post->pubdate; $date = Utils::getdate( strtotime( $post->pubdate ) ); ?> <span class="entry-date"><span class="entry-ym"><?php if ( $date1 == "" ) { echo $post->pubdate->out("m.y"); } else { echo $date['mon0'].".".substr($date['year'], -2, 2); } ?></span><span class="entry-day"><?php if ( $date1 == "" ) { echo $post->pubdate->out("d"); } else { echo $date['mday0']; } ?></span></span><a href="<?php echo $post->permalink; ?>" title="<?php echo $post->title; ?>"><?php echo $post->title_out; ?></a> </h2> <div class="entry-meta"> <?php if ( $show_author ) { ?><span class="author"><?php _e('by'); ?> <?php echo $post->author->displayname; ?></span><span class="meta-sep">|</span><?php } ?> <?php if ( $post->get_access()->edit ) { ?> <span class="edit-link"><a href="<?php URL::out( 'admin', 'page=publish&slug=' . $post->slug); ?>" title="<?php _e('Edit post'); ?>"><?php _e('Edit'); ?></a></span> <span class="meta-sep">|</span> <?php } ?> <?php if ( count( $post->tags ) ) { ?> <span class="tag-links"><?php _e('Tagged:'); ?> <?php echo $post->tags_out; ?></span> <span class="meta-sep">|</span> <?php } ?> <span class="comments-link"><a href="<?php echo $post->permalink; ?>#comments" title="<?php _e('Comments to this post'); ?>"><?php echo $post->comments->approved->count; ?> <?php echo _n( 'Comment', 'Comments', $post->comments->approved->count ); ?></a></span> </div> <div class="entry-content"> <?php echo $post->content_out; ?> </div> <?php if ( Plugins::is_loaded('RelatedPosts') || Plugins::is_loaded('RelatedTags') ) { ?> <div class="entry-related"> <?php if ( Plugins::is_loaded('RelatedPosts') ) { ?> <div id="related-post" class="related-box"> <h3>Related Posts</h3> <?php echo $related_posts; ?> </div> <?php } if ( Plugins::is_loaded('RelatedTags') ) { ?> <div id="related-tags" class="related-box"> <h3>Related Tags</h3> <?php echo $related_tags; ?> </div> <?php } ?> </div> <?php } ?> <div id="nav-below" class="navigation"> <?php if ( $previous = $post->descend() ): ?> <div class="nav-previous"> <span class="meta-nav">&laquo;</span> <a href="<?php echo $previous->permalink ?>" title="<?php echo $previous->slug ?>"><?php echo $previous->title ?></a></div> <?php endif; ?> <?php if ( $next = $post->ascend() ): ?> <div class="nav-next"><a href="<?php echo $next->permalink ?>" title="<?php echo $next->slug ?>"><?php echo $next->title ?></a> <span class="meta-nav">&raquo;</span></div> <?php endif; ?> </div> </div> <?php $theme->display ('comments'); ?> </div><!-- #content --> </div><!-- #container --> <?php $theme->display ('sidebar'); ?> <?php $theme->display ('footer'); ?> <file_sep><?php class unButtonAdmin extends Plugin { public function info() { return array ( 'name' => 'Un-button Admin', 'version' => '0.1', 'author' => 'Habari Community', 'license' => 'Apache License 2.0', 'description' => 'Reverts the ugly admin buttons to the default OS widgets', ); } public function action_admin_header( $theme ) { // This is such a hack it's not even funny // But I am laughing inside. Laughing in a bad way. Stack::remove('admin_stylesheet', 'admin'); $css = file_get_contents(Site::get_dir('admin_theme') . '/css/admin.css'); $css = preg_replace( '@#page input\[type=button\], #page input\[type=submit\], #page button {([^}]+)}@', '', $css, 1 ); $css = preg_replace( '@#page input\[type=button\]:hover, #page input\[type=submit\]:hover, #page button:hover {([^}]+)}@', '', $css, 1 ); Stack::add( 'admin_stylesheet', array( preg_replace('@../images/@', Site::get_url('admin_theme') . '/images/', $css), 'screen' ), 'admin', 'jquery' ); } } ?><file_sep><?php class GoogleAnalytics extends Plugin { public function action_init() { $this->add_rule('"gaextra.js"', 'serve_gaextra'); } /** * Add the tracking code to the template_header_javascript Stack. * * @todo determine if there is a better action to use * @return null */ public function action_init_theme_any( $theme ) { $code = $this->tracking_code(); if ( $code != null ) { Stack::add('template_header_javascript', $code, 'googleanalytics'); } } public function action_plugin_act_serve_gaextra() { ob_clean(); header('Content-Type: application/javascript'); // format extensions for regex match $extensions = explode(',', Options::get('googleanalytics__trackfiles_extensions')); $extensions = array_map('trim', $extensions); $extensions = implode('|', $extensions); include 'googleanalytics.js.php'; } public function configure() { $form = new FormUI(strtolower(get_class($this))); $form->append('text', 'clientcode', 'googleanalytics__clientcode', _t('Analytics Client Code')); $form->append('checkbox', 'loggedintoo', 'googleanalytics__loggedintoo', _t('Track logged-in users too')); $form->append('checkbox', 'skip_gaextra', 'googleanalytics__skip_gaextra', _t('Skip inclusion of gaextra.js')); if(!Options::get('googleanalytics__skip_gaextra')) { $form->append('checkbox', 'trackoutgoing', 'googleanalytics__trackoutgoing', _t('Track outgoing links')); $form->append('checkbox', 'trackmailto', 'googleanalytics__trackmailto', _t('Track mailto links')); $form->append('checkbox', 'trackfiles', 'googleanalytics__trackfiles', _t('Track download links')); $form->append('textarea', 'track_extensions', 'googleanalytics__trackfiles_extensions', _t('File extensions to track (comma separated)')); } $form->append('submit', 'save', 'Save'); return $form; } private function tracking_code() { if ( URL::get_matched_rule()->entire_match == 'user/login' ) { // Login page; don't display return; } $clientcode = Options::get('googleanalytics__clientcode'); if ( empty($clientcode) ) { return; } // only actually track the page if we're not logged in, or we're told to always track $do_tracking = !User::identify()->loggedin || Options::get('googleanalytics__loggedintoo'); $track_pageview = ($do_tracking) ? "_gaq.push(['_trackPageview']);" : ''; $habari_url = Site::get_url('habari'); if(Options::get('googleanalytics__skip_gaextra')) { $extra = ''; } else { $extra = <<<EXTRA var ex = document.createElement('script'); ex.type = 'text/javascript'; ex.async = true; ex.src = '{$habari_url}/gaextra.js'; s.parentNode.insertBefore(ex, s); EXTRA; } return <<<ANALYTICS var _gaq = _gaq || []; _gaq.push(['_setAccount', '{$clientcode}']); {$track_pageview} (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); {$extra}})(); ANALYTICS; } } ?> <file_sep> <li id="widget-relatedposts" class="widget"> <h3><?php _e('Related Posts', 'demorgan') ?></h3> <?php echo $related_posts; ?> </li> <file_sep><?php /** * Provides community plugin / theme directory as well as beacon update services. * * cross reference between compatible themes/plugins - morydd * 'People who downloaded this also downloaded X' - randyw * if 2 plugins have 4 or more tags in common, say something like "This plugin not what you want? Try foo, bar, or baz" - randyw */ require 'beaconhandler.php'; require 'pluginrepo.php'; class PluginServer extends Plugin { private $info_fields = array( 'guid' ); private $plugin_fields = array( 'post_id', 'version', 'md5', 'habari_version', 'description', 'author', 'author_url', 'license', 'screenshot', 'instructions', 'url', 'status', 'requires', 'provides', 'recommends', 'source_link' ); private $theme_fields = array( 'post_id', 'version', 'md5', 'habari_version', 'description', 'author', 'author_url', 'license', 'screenshot', 'instructions', 'url', 'status', 'requires', 'provides', 'recommends', 'source_link' ); private $license_fields = array( 'simpletext', 'shortname', 'link' ); const VERSION = '0.2alpha3'; public function filter_default_rewrite_rules( $rules ) { // put together our rule $rule['name'] = 'beacon_server'; $rule['parse_regex'] = '%^beacon$%i'; $rule['build_str'] = 'beacon'; $rule['handler'] = 'BeaconHandler'; $rule['action'] = 'request'; $rule['description'] = 'Incoming Beacon Update Requests'; // add our rule to the stack $rules[] = $rule; // put together our rule $rule['name'] = 'repo_server'; $rule['parse_regex'] = '%^packages[/]?$%i'; $rule['build_str'] = 'packages'; $rule['handler'] = 'PluginRepo'; $rule['action'] = 'packages'; $rule['description'] = 'Plugin Repo Server'; // add our rule to the stack $rules[] = $rule; // put together our rule $rule['name'] = 'display_plugin'; $rule['parse_regex'] = '%^explore/plugins/(?P<slug>.+)/?$%'; $rule['build_str'] = 'explore/plugins/{$slug}'; $rule['handler'] = 'UserThemeHandler'; $rule['action'] = 'display_plugin'; $rule['priority'] = 3; $rule['description'] = 'Plugin Repo Server Browser'; // add our rule to the stack $rules[] = $rule; // put together our rule $rule['name'] = 'display_plugins'; $rule['parse_regex'] = '%^explore/plugins(?:/page/(?P<page>\d+))?/?$%'; $rule['build_str'] = 'explore/plugins(/page/{$page})'; $rule['handler'] = 'UserThemeHandler'; $rule['action'] = 'display_plugins'; $rule['priority'] = 2; $rule['description'] = 'Plugin Repo Server Browser'; // add our rule to the stack $rules[] = $rule; $rule['name'] = 'display_theme'; $rule['parse_regex'] = '%^explore/themes/(?P<slug>.+)/?$%'; $rule['build_str'] = 'explore/themes/{$slug}'; $rule['handler'] = 'UserThemeHandler'; $rule['action'] = 'display_theme'; $rule['priority'] = 3; $rule['description'] = 'Plugin Repo Server Browser'; $rules[] = $rule; $rule['name'] = 'display_themes'; $rule['parse_regex'] = '%^explore/themes(?:/page/(?P<page>\d+))?/?$%'; $rule['build_str'] = 'explore/themes(/page/{$page})'; $rule['handler'] = 'UserThemeHandler'; $rule['action'] = 'display_themes'; $rule['priority'] = 2; $rule['description'] = 'Plugin Repo Server Browser'; $rules[] = $rule; $rule['name'] = 'display_license'; $rule['parse_regex'] = '%^explore/other/license/(?P<slug>.+)/?$%'; $rule['build_str'] = 'explore/other/license/{$slug}'; $rule['handler'] = 'UserThemeHandler'; $rule['action'] = 'display_license'; $rule['priority'] = 2; $rule['description'] = 'Plugin Repo Server Browser'; $rules[] = $rule; // and pass it along return $rules; } /** * @ todo make uoe own template for these */ public function filter_theme_act_display_plugins( $handled, $theme ) { $paramarray['fallback']= array( 'plugin.multiple', 'multiple', ); // Makes sure home displays only entries $default_filters = array( 'content_type' => Post::type( 'plugin' ), ); $paramarray['user_filters']= $default_filters; $theme->act_display( $paramarray ); return true; } public function filter_theme_act_display_plugin( $handled, $theme ) { $default_filters = array( 'content_type' => Post::type( 'plugin' ), ); $theme->act_display_post( $default_filters ); return true; } public function filter_theme_act_display_themes( $handled, $theme ) { $paramarray['fallback']= array( 'theme.multiple', 'multiple', ); // Makes sure home displays only entries $default_filters = array( 'content_type' => Post::type( 'theme' ), ); $paramarray['user_filters']= $default_filters; $theme->act_display( $paramarray ); return true; } public function filter_theme_act_display_theme( $handled, $theme ) { $default_filters = array( 'content_type' => Post::type( 'theme' ), ); $theme->act_display_post( $default_filters ); return true; } public function filter_theme_act_display_licenses( $handled, $theme ) { $paramarray['fallback']= array( 'license.multiple', 'multiple', ); // Makes sure home displays only entries $default_filters = array( 'content_type' => Post::type( 'license' ), ); $paramarray['user_filters']= $default_filters; $theme->act_display( $paramarray ); return true; } public function filter_theme_act_display_license( $handled, $theme ) { $default_filters = array( 'content_type' => Post::type( 'license' ), ); $theme->act_display_post( $default_filters ); return true; } public function action_plugin_activation ( $file ='' ) { if ( Plugins::id_from_file( $file ) == Plugins::id_from_file( __FILE__ ) ) { // add or activate our custom post type Post::add_new_type( 'plugin' ); Post::add_new_type( 'license' ); Post::add_new_type( 'theme' ); DB::register_table( 'dir_plugin_versions' ); DB::register_table( 'dir_theme_versions' ); // Create the database table, or upgrade it DB::dbdelta( $this->get_db_schema() ); Session::notice( _t( 'updated plugin_versions table', 'plugin_directory' ) ); } } public function action_plugin_deactivation( $file ='' ) { if ( Plugins::id_from_file( $file ) == Plugins::id_from_file( __FILE__ ) ) { // @todo it has yet been decided whether or not this is a good idea - MellerTime /* // get all the posts of our update type, so we can delete them $posts = Posts::get( array( 'content_type' => 'plugin', 'nolimit' => true ) ); foreach ( $posts as $post ) { $post->delete(); } */ // deactivate our custom post type Post::deactivate_post_type( 'plugin' ); } } public function action_auth_ajax_generate_guid( $handler ) { echo UUID::get(); } /** *Manipulate the controls on the publish page * *@param FormUI $form The form that is used on the publish page *@param Post $post The post being edited **/ public function action_form_publish($form, $post) { if ( $form->content_type->value == Post::type('plugin') ) { // remove silos we don't need them, do we? $form->remove($form->silos); // add guid after title $guid = $form->append('text', 'plugin_details_guid', 'null:null', 'GUID'); $guid->value = $post->info->guid; $guid->template = ($post->slug) ? 'admincontrol_text' : 'guidcontrol'; $form->move_after($form->plugin_details_guid, $form->title); // add instructions after content $instructions = $form->append('textarea','plugin_details_instructions', 'null:null', 'Instructions'); $instructions->value = $post->info->instructions; $instructions->class[] = 'resizable'; $instructions->template = 'admincontrol_textarea'; $form->move_after($form->plugin_details_instructions, $form->content); // todo Fix all the tabindexes - there are two #2s right now and GUID has none. // todo Remove the settings tab, as it's not needed $plugin_details = array( 'url' => $post->info->url, 'screenshot' => $post->info->screenshot, 'author' => $post->info->author, 'author_url' => $post->info->author_url, 'license' => $post->info->license ); $plugin_form_fields = $form->publish_controls->append('fieldset', 'plugin_details', 'Plugin Details'); foreach ( $plugin_details as $field => $value ) { $plugin_field = $plugin_form_fields->append('text', 'plugin_details_' . $field, 'null:null', ucfirst(str_replace('_', ' ', $field))); $plugin_field->value = $value; $plugin_field->template = 'tabcontrol_text'; } $plugin_versions = $form->publish_controls->append('fieldset', 'plugin_versions', 'Plugin Versions'); if ( $post->slug != '' ) { $form->plugin_versions->append('static', 'current_versions', 'Current Versions'); foreach ( (array) $post->versions as $version ) { $version_info = $version->status . ": " . $post->title . " " . $version->version . " -- " . $version->description; $plugin_versions->append('static', 'version_info', $version_info); } } $form->plugin_versions->append('static', 'new_version', 'Add New Version'); $version = $plugin_versions->append('text', 'plugin_version_version', 'null:null', _t( 'Version Number' )); $version->template = 'tabcontrol_text'; $description = $plugin_versions->append('text', 'plugin_version_description', 'null:null', _t( 'Version Description' )); $description->template = 'tabcontrol_text'; $url = $plugin_versions->append('text', 'plugin_version_url', 'null:null', _t( 'Archive URL' )); $url->template = 'tabcontrol_text'; $habari_version = $plugin_versions->append('text', 'plugin_version_habari_version', 'null:null', _t( 'Compatible Habari Version <br> ("x" is a wildcard, eg. 0.5.x)' )); $habari_version->template = 'tabcontrol_text'; $status = $plugin_versions->append( 'select', 'plugin_version_status', 'null:null', 'Status'); $status->template = 'tabcontrol_select'; $status->options = array( 'release' => 'Release', 'critical' => 'Critical', 'bugfix' => 'Bugfix', 'feature' => 'Feature', ); $requires = $plugin_versions->append('text', 'plugin_version_requires', 'null:null', _t( 'Requires' )); $requires->template = 'tabcontrol_text'; $provides = $plugin_versions->append('text', 'plugin_version_provides', 'null:null', _t( 'Provides' )); $provides->template = 'tabcontrol_text'; $recommends = $plugin_versions->append('text', 'plugin_version_recommends', 'null:null', _t( 'Recommends' )); $recommends->template = 'tabcontrol_text'; $sourcelink = $plugin_versions->append('text', 'plugin_version_source_link', 'null:null', _t( 'Link to Source' )); $sourcelink->template = 'tabcontrol_text'; /* @todo validate sourcelink */ } else if ( $form->content_type->value == Post::type( 'license' ) ) { // clean up the form a little... $form->remove( $form->silos ); $form->remove( $form->content ); $form->remove( $form->tags ); $settings = $form->publish_controls->settings; $settings->minor_edit->remove(); $settings->comments_enabled->remove(); $settings->pubdate->remove(); // add shortname after title $shortname = $form->append('text', 'license_shortname', 'null:null', _t('Short Name') ); $shortname->value = $post->info->shortname; $shortname->template = 'admincontrol_text'; $form->move_after($form->license_shortname, $form->title); // add simpletext after shortname $simpletext = $form->append('textarea','license_simpletext', 'null:null', _t('Simplified Text') ); $simpletext->value = $post->info->simpletext; $simpletext->class[] = 'resizable'; $simpletext->template = 'admincontrol_textarea'; $form->move_after($form->license_simpletext, $form->license_shortname); // add link after simpletext $link = $form->append('text', 'license_link', 'null:null', _t('Link') ); $link->value = $post->info->link; $link->template = 'admincontrol_text'; $form->move_after($form->license_link, $form->license_simpletext); } } public function action_publish_post( $post, $form ) { if ( $post->content_type == Post::type('plugin') ) { foreach ( $this->info_fields as $info_field ) { if ( $form->{"plugin_details_$info_field"}->value ) { $post->info->{$info_field} = $form->{"plugin_details_$info_field"}->value; } } $this->save_versions( $post, $form ); } /* NEED THEME STUFF HERE */ else if ( $post->content_type == Post::type('license') ) { foreach ( $this->license_fields as $field ) { if ( $form->{"license_$field"}->value ) { $post->info->{$field} = $form->{"license_$field"}->value; } } } } /** * @todo check for required inputs */ public function save_versions( $post, $form ) { if ( $form->plugin_version_version->value ) { $version_vals = array(); foreach ( $this->plugin_fields as $version_field ) { if ( $form->{"plugin_version_$version_field"} ) { $version_vals[$version_field] = $form->{"plugin_version_$version_field"}->value; } else { $version_vals[$version_field] = ''; } } $version_vals['post_id'] = $post->id; $version_vals['md5'] = $this->get_version_md5( $version_vals['url'] ); DB::update( DB::table( 'dir_plugin_versions' ), $version_vals, array( 'version' => $version_vals['version'], 'post_id' => $post->id ) ); Session::notice( 'Added version number ' . $version_vals['version'] ); } /* NEED THEME STUFF HERE */ } public function get_version_md5( $url ) { $file = RemoteRequest::get_contents( $url ); return md5( $file ); } public function filter_post_versions( $versions, $post ) { $table='{dir_' . $post->typename . '_versions}'; return DB::get_results( 'SELECT * FROM ' . $table . ' WHERE post_id = ?', array( $post->id ) ); } public static function licenses() { // @todo make this configurable through the plugin options - MellerTime $licenses['apache_20']= 'Apache License 2.0'; $licenses['gpl']= 'GPL'; $licenses['lgpl']= 'LGPL'; $licenses['public']= 'Public Domain'; return $licenses; } public function action_init() { DB::register_table( 'dir_plugin_versions' ); DB::register_table( 'dir_theme_versions' ); $this->add_template( 'plugin.multiple', dirname(__FILE__) . '/templates/plugin.multiple.php' ); $this->add_template( 'plugin.single', dirname(__FILE__) . '/templates/plugin.single.php' ); $this->add_template( 'guidcontrol', dirname(__FILE__) . '/templates/guidcontrol.php' ); } } ?> <file_sep><?php class RenderTypeFormat extends Format { public function render_type( $content, $font_file, $font_size = 28, $font_color = '#000000FF', $background_color = '#00000000', $output_format = 'png', $width = NULL ) { return Plugins::filter( 'render_type', $content, $font_file, $font_size, $font_color, $background_color, $output_format, $width ); } } ?><file_sep><div class="spoiler"> <a href="#" class="spoiler-message"><?php echo $message; ?></a> <span class="spoiler-text"><?php echo $spoiler; ?></span> </div> <file_sep><?php /** * A plugin to hide spoilers until a conscious action on the part of the user. * **/ class UpdatePosts extends Plugin { /** * Do nothing yet on activation * **/ public function action_plugin_activation($file) { } // Add configuration here /** * Do nothing yet on init **/ public function action_init() { } /** * Publish post when old post is updated. This is invoked by a change in * the 'updated' date, which is only changed when 'minor edit' is not set. **/ public function action_post_update_updated($post) { if($post->status == "published" && $post->pubdate != $post->modified) { $test = new Post(); $test->title = $post->title." modified by ".$post->author->displayname; $test->user_id = $post->author->id; $test->content = "The following post has been modified significantly: <a href='".$post->permalink."'>".$post->title."</a>"; $test->insert(); $test->publish(); } } // Add Beacon support here } ?> <file_sep><div class="block" id="twitter"> <h3>Twitter</h3> <ul> <li><em><?php echo htmlspecialchars( $tweet_text ); ?></em></li> <li>Via <a href="http://twitter.com/<?php echo urlencode( Options::get( 'twitter:username' )); ?>">Twitter</a></li> </ul> </div><file_sep>#!/usr/bin/php <?php // read from php://stdin $email = file_get_contents('php://stdin'); class Email { const MULTIPART = 0; const SINGLE = 1; private $email_raw; public $body_raw; public $headers; public $content_type; public $body; public $body_parts; public $type; public $boundary; public function __construct($email) { $this->email_raw = $email; $this->parse_email($email); } public function parse_email($email) { list($headers, $body) = explode("\n\n", $email, 2); $this->headers = new EmailHeaders(trim($headers)); $this->parse_body($body); } public function parse_body($body) { $this->body_raw = $body; if (preg_match('#^multipart/.*boundary=(\'|")(.*)(\1)#i', $this->headers->get('content-type'), $m)) { $this->type = self::MULTIPART; $this->boundary = $m[2]; $body = substr($body, strlen($this->boundary)+2); $bodies = explode("--$this->boundary", $body, -1); foreach ($bodies as $bod) { $this->body_parts[] = new EmailBodyPart($bod); } } else { $this->type = self::SINGLE; $this->body = $body; } } } include "emailheaders.php"; include "emailbodypart.php"; $e = new Email($email); ?> <file_sep><?php class Dateyurl extends Plugin { /** * Required plugin info() implementation provides info to Habari about this plugin. */ public function info() { return array ( 'name' => 'DateYURL', 'url' => 'http://habariproject.org', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org', 'version' => 0.2, 'description' => 'Makes entry urls in the form /{year}/{month}/{day}/{slug} or /{year}/{month}/{slug}. <strong>Ensure the Route 301 plugin is not also attempting to rewrite your choice!</strong>', 'license' => 'Apache License 2.0', ); } public function action_init() { $rule = RewriteRules::by_name('display_entry'); $rule = $rule[0]; $format = Options::get( 'dateyurl__format' ); // for backwards compatibility. the first time, set the option if ( $format == null ) { Options::set( 'dateyurl__format', 'date' ); $format = 'date'; } if ( $format == 'date' ) { // /{year}/{month}/{day}/{slug} $rule->parse_regex= '%(?P<year>\d{4})/(?P<mon0>\d{2})/(?P<mday0>\d{2})/(?P<slug>[^/]+)(?:/page/(?P<page>\d+))?/?$%i'; $rule->build_str= '{$year}/{$mon0}/{$mday0}/{$slug}(/page/{$page})'; } if ( $format == 'month' ) { // /{year}/{month}/{slug} $rule->parse_regex= '%(?P<year>\d{4})/(?P<mon0>\d{2})/(?P<slug>[^/]+)(?:/page/(?P<page>\d+))?/?$%i'; $rule->build_str= '{$year}/{$mon0}/{$slug}(/page/{$page})'; } } public function action_update_check() { Update::add( 'DateYURL', '376A1864-98A1-11DD-A1CC-365A55D89593', $this->info->version ); } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t( 'Configure' ); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { if ( $action == _t( 'Configure' ) ) { $class_name = strtolower( get_class( $this ) ); $form = new FormUI( $class_name ); $form->append( 'select', 'format', 'dateyurl__format', _t( 'URL Format' ), array( 'date' => '/{year}/{month}/{day}/{slug}', 'month' => '/{year}/{month}/{slug}' ) ); $form->append( 'submit', 'save', _t( 'Save' ) ); $form->on_success( array( $this, 'updated_config' ) ); $form->out(); } } } public function updated_config( $form ) { $form->save(); } public function action_plugin_activation( $file ) { if ( Plugins::id_from_file( $file ) == Plugins::id_from_file( __FILE__ ) ) { if ( Options::get( 'dateyurl__format' ) == null ) { Options::set( 'dateyurl__format', 'date' ); } } } } ?><file_sep><?php include 'header.php'; ?> <?php include 'sidebar.php'; ?> <div class="post" id="post-<?php echo $post->id; ?>"> <h2 class="post_title"><a href="<?php echo $post->permalink; ?>" title="<?php echo $post->title; ?>"><?php echo $post->title_out; ?></a></h2> <div class="post_content"> <?php $content = preg_replace('%^\s*<p>%i', '<p class="first_paragraph">', $post->content_out, 1); echo $content; ?> </div> </div> <?php include 'footer.php'; ?><file_sep> <div class="container"> <p class="column span-5"><?php _e( 'Feed URL', 'blogroll' ); ?></p> <p class="column span-14 last"><input type="text" id="feed" name="feed" size="100%" value="<?php echo isset($feed)?$feed:''; ?>" class="styledformelement"></p> </div> <hr> <div class="container"> <p class="column span-5"><?php _e( 'Owner Name', 'blogroll' ); ?></p> <p class="column span-14 last"><input type="text" id="owner" name="owner" size="100%" value="<?php echo isset($owner)?$owner:''; ?>" class="styledformelement"></p> </div> <hr> <div class="container"> <p class="column span-5"><?php _e( 'Relationship', 'blogroll' ); ?></p> <p class="column span-14 last"> <label><?php echo Utils::html_select( 'rel', $relationships, $rel, array( 'class'=>'longselect') ); ?></label> </p> </div> <file_sep> <li id="widget-entries" class="widget"> <h3><?php _e('Recently', 'demorgan'); ?></h3> <ul> <?php if ($recent_entries) { foreach ($recent_entries as $entry) { ?> <li><a href="<?php echo $entry->permalink; ?>" title="<?php echo strip_tags($entry->title); ?>" rel="bookmark"><?php echo $entry->title_out; ?></a></li> <?php } } else { ?> <li><?php _e('There are currently no posts in this blog.', 'demorgan'); ?></li> <?php } ?> </ul> </li> <file_sep><?php /** * StatusNet Twitter-Compat API Plugin * * Show your latest StatusNet notices in your theme and/or * post your latest blog post to your StatusNet service. * * Usage: <?php $theme->statusnet(); ?> to show your latest notices. * Copy the statusnet.tpl.php template to your active theme to customize * output display. * **/ class StatusNet extends Plugin { /** * Update beacon support. UID is real, but not reg'd with project. **/ public function action_update_check() { Update::add( 'StatusNet', '8676A858-E4B1-11DD-9968-131C56D89593', $this->info->version ); } public function help() { $help = _t('<p>For the <strong>&micro;blog service</strong> setting, enter the portion of your &micro;blog service home page URL between the slash at the end of <tt>http://</tt> and the slash before your user name: <tt>http://</tt><strong>statusnet.service</strong><tt>/</tt><em>yourname</em>.</p> <p>To use identi.ca, for example, since your URL is something like <tt>http://identi.ca/yourname</tt>, you would enter <tt>identi.ca</tt>.</p> <p>To display your latest notices, call <code>$theme->statusnet();</code> at the appropriate place in your theme.</p>'); return $help; } /** * Add actions to the plugin page for this plugin * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id **/ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = 'Configure'; } return $actions; } /** * Set defaults. **/ public function action_plugin_activation( $file ) { if(Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__)) { if ( Options::get( 'statusnet__hide_replies' ) !== 0 ) { Options::set( 'statusnet__hide_replies', 1 ); } if ( Options::get( 'statusnet__linkify_urls' ) !== 0 ) { Options::set( 'statusnet__linkify_urls', 1 ); } if ( !Options::get( 'statusnet__svc' ) ) { Options::set( 'statusnet__svc', 'identi.ca' ); } if ( Options::get( 'statusnet__show' ) !== 0 ) { Options::set( 'statusnet__show', 1 ); } if ( !Options::get( 'statusnet__limit' ) ) { Options::set( 'statusnet__limit', 1 ); } } } /** * Respond to the user selecting an action on the plugin page * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook **/ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { if ( $action == _t( 'Configure' ) ) { $ui = new FormUI( strtolower( get_class( $this ) ) ); $ui->append('fieldset', 'svcinfo', _t('Service', 'statusnet')); $statusnet_svc = $ui->append( 'text', 'svc', 'statusnet__svc', _t('&micro;blog service:') ); $ui->svc->move_into($ui->svcinfo); $statusnet_username = $ui->append( 'text', 'username', 'statusnet__username', _t('Service username:') ); $ui->username->move_into($ui->svcinfo); $statusnet_password = $ui->append( 'password', '<PASSWORD>', '<PASSWORD>', _t('Service password:') ); $ui->password->move_into($ui->svcinfo); $ui->append('fieldset', 'publishinfo', _t('Publish', 'statusnet')); $statusnet_post = $ui->append( 'checkbox', 'post_status', 'statusnet__post_status', _t('Announce new blog posts on µblog') ); $statusnet_post->options = array( '0' => _t('Disabled'), '1' => _t('Enabled') ); $ui->post_status->move_into($ui->publishinfo); $statusnet_post = $ui->append( 'text', 'prefix', 'statusnet__prefix', _t('Announcement prefix (e.g., "New post: "):') ); $ui->prefix->move_into($ui->publishinfo); $ui->append('fieldset', 'subscribeinfo', _t('Subscribe', 'statusnet')); $statusnet_show = $ui->append( 'checkbox', 'show', 'statusnet__show', _t('Retrieve µblog notices for blog display') ); $ui->show->move_into($ui->subscribeinfo); $statusnet_limit = $ui->append( 'select', 'limit', 'statusnet__limit', _t('Number of notices to display:') ); $statusnet_limit->options = array_combine(range(1, 20), range(1, 20)); $ui->limit->move_into($ui->subscribeinfo); $statusnet_show = $ui->append( 'checkbox', 'hide_replies', 'statusnet__hide_replies', _t('Hide @replies') ); $ui->hide_replies->move_into($ui->subscribeinfo); $statusnet_show = $ui->append( 'checkbox', 'linkify_urls', 'statusnet__linkify_urls', _t('Linkify URLs') ); $ui->linkify_urls->move_into($ui->subscribeinfo); $statusnet_cache_time = $ui->append( 'text', 'cache', 'statusnet__cache', _t('Cache expiry in seconds:') ); $ui->cache->move_into($ui->subscribeinfo); $ui->on_success( array( $this, 'updated_config' ) ); $ui->append( 'submit', 'save', _t('Save') ); $ui->out(); } } } /** * Returns true if plugin config form values defined in action_plugin_ui should be stored in options by Habari * @return bool True if options should be stored **/ public function updated_config( FormUI $ui ) { Session::notice( _t( 'StatusNet options saved.', 'statusnet' ) ); $ui->save(); } /** * Add the StatusNet user options to the list of valid field names. * This causes adminhandler to recognize the statusnet fields and * to set the userinfo record appropriately **/ public function filter_adminhandler_post_user_fields( $fields ) { $fields['statusnet_name'] = 'statusnet_name'; $fields['statusnet_pass'] = '<PASSWORD>'; return $fields; } /** * Post a status to service * @param string $svcurl Catenation of user server, API endpoints * @param string $notice The new status to post **/ public function post_status( $svcurl, $notice, $name, $pw ) { $request = new RemoteRequest( $svcurl, 'POST' ); $request->add_header( array( 'Authorization' => 'Basic ' . base64_encode( "{$name}:{$pw}" ) ) ); $request->set_body( 'source=habari&status=' . urlencode( $notice ) ); $request->execute(); } /** * React to the update of a post status to 'published' * @param Post $post The post object with the status change * @param int $oldvalue The old status value * @param int $newvalue The new status value **/ public function action_post_update_status( $post, $oldvalue, $newvalue ) { if ( is_null( $oldvalue ) ) return; if ( $newvalue == Post::status( 'published' ) && $post->content_type == Post::type('entry') && $newvalue != $oldvalue ) { if ( Options::get( 'statusnet__post_status' ) == '1' ) { $user = User::get_by_id( $post->user_id ); if ( ! empty( $user->info->statusnet_name ) && ! empty( $user->info->statusnet_pass ) ) { $name = $user->info->statusnet_name; $pw = $user->info->statusnet_pass; } else { $name = Options::get( 'statusnet__username' ); $pw = Options::get( 'statusnet__password' ); } $svcurl = 'http://' . Options::get('statusnet__svc') . '/api/statuses/update.xml'; $this->post_status( $svcurl, Options::get( 'statusnet__prefix' ) . $post->title . ' ' . $post->permalink, $name, $pw ); } } } public function action_post_insert_after( $post ) { return $this->action_post_update_status( $post, -1, $post->status ); } /** * Add last service status, time, and image to the available template vars * @param Theme $theme The theme that will display the template **/ public function theme_statusnet( $theme ) { $notices = array(); if ( Options::get( 'statusnet__show' ) && Options::get( 'statusnet__svc' ) && Options::get( 'statusnet__username' ) != '' ) { $statusnet_url = 'http://' . Options::get( 'statusnet__svc' ) . '/api/statuses/user_timeline/' . urlencode( Options::get( 'statusnet__username' ) ) . '.xml'; /* * Only need to get a single notice if @replies are hidden. * (Otherwise, rely on the maximum returned and hope one is a non-reply.) */ if ( !Options::get( 'statusnet__hide_replies' ) && Options::get( 'statusnet__limit' ) ) { $statusnet_url .= '?count=' . Options::get( 'statusnet__limit' ); } if ( Cache::has( 'statusnet_notices' ) ) { $notices = Cache::get( 'statusnet_notices' ); } else { try { $response = RemoteRequest::get_contents( $statusnet_url ); $xml = @new SimpleXMLElement( $response ); // Check we've got a load of statuses returned if ( $xml->getName() === 'statuses' ) { foreach ( $xml->status as $status ) { if ( ( !Options::get( 'statusnet__hide_replies' ) ) || ( strpos( $status->text, '@' ) === false) ) { $notice = (object) array ( 'text' => (string) $status->text, 'time' => (string) $status->created_at, 'image_url' => (string) $status->user->profile_image_url, 'id' => (int) $status->id, 'permalink' => 'http://' . Options::get('statusnet__svc') . '/notice/' . (string) $status->id, ); $notices[] = $notice; if ( Options::get( 'statusnet__hide_replies' ) && count($notices) >= Options::get( 'statusnet__limit' ) ) break; } else { // it's a @. Keep going. } } if ( !$notices ) { $notice->text = 'No non-replies replies available from service.'; $notice->time = ''; $notice->image_url = ''; } } // You can get error as a root element if service is in maintance mode. else if ( $xml->getName() === 'error' ) { $notice->text = (string) $xml; $notice->time = ''; $notice->image_url = ''; } // Should not be reached. else { $notice->text = 'Received unexpected XML from service.'; $notice->time = ''; $notice->image_url = ''; } } catch ( Exception $e ) { $notice->text = 'Unable to contact service.'; $notice->time = ''; $notice->image_url = ''; } if (!$notices) $notices[] = $notice; // Cache (even errors) to avoid hitting rate limit. Cache::set( 'statusnet_notices', $notices, Options::get( 'statusnet__cache' ) ); } if ( Options::get( 'statusnet__linkify_urls' ) != FALSE ) { /* http: links */ foreach ($notices as $notice) $notice->text = preg_replace( '%https?://\S+?(?=(?:[.:?"!$&\'()*+,=]|)(?:\s|$))%i', "<a href=\"$0\">$0</a>", $notice->text ); } } else { $notice = (object) array ( 'text' => _t('Check username or "Show latest notice" setting in <a href="%s">StatusNet plugin config</a>', array( URL::get( 'admin' , 'page=plugins&configure=' . $this->plugin_id . '&configaction=Configure' ) . '#plugin_' . $this->plugin_id ) , 'statusnet' ), 'time' => '', 'image_url' => '' ); $notices[] = $notice; } $theme->notices = $notices; return $theme->fetch( 'statusnet.tpl' ); } /** * On plugin init, add the template included with this plugin to the available templates in the theme */ public function action_init() { $this->add_template('statusnet.tpl', dirname(__FILE__) . '/statusnet.tpl.php'); } } ?> <file_sep><?php class Freeplace extends Plugin { public function action_update_check() { Update::add( $this->info->name, 'c7d47111-d452-4522-a343-f1d0df1d9095', $this->info->version ); } /** * Create plugin configuration **/ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t('Replace'); } return $actions; } /** * Create configuration panel */ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Replace') : $form = new FormUI( strtolower( get_class( $this ) ) ); $form->append( 'text', 'search', 'null:null', _t('Search:') ); $form->search->add_validator('validate_required'); $form->append( 'text', 'replace', 'null:null', _t('Replace:') ); $form->replace->add_validator('validate_required'); $form->append( 'submit', 'save', _t('Replace') ); $form->on_success( 'do_replace' ); $form->out(); break; } } } /** * UPDATE [your_table_name] SET [your_table_field] = REPLACE([your_table_field], ‘[string_to_find]‘ , ‘[string_to_be_replaced]‘); */ /** * Handler FormUI success action and do the replacement **/ public function filter_do_replace( $show_form, $form ) { if( DB::query( 'UPDATE {posts} SET content = REPLACE(content, ? , ?)', array( $form->search->value, $form->replace->value ) ) ) { Session::notice( sprintf( _t( 'Successfully replaced \'%s\' with \'%s\' in all posts' ), $form->search->value, $form->replace->value ) ); Utils::redirect( URL::get( 'admin', array( 'page' => 'plugins', 'configure' => Plugins::id_from_file( __FILE__ ), 'configaction' => _t('Replace') ) ), false ); } else { Session::error( _t( 'There was an error with replacement.' ) ); } return false; } } ?><file_sep><?php class Snippet extends Plugin { function langSelect() { $output = array( 'actionscript'=>'Actionscript', 'bash'=>'Bash', 'c'=>'C', 'csharp'=>'C#', 'cpp'=>'C++', 'cobol'=>'COBOL', 'coldfusion'=>'ColdFusion', 'css'=>'CSS', 'd'=>'D', 'html'=>'HTML', 'java'=>'Java', 'javascript'=>'Javascript', 'php'=>'PHP', 'python'=>'Python', ); return $output; } function info() { return array( 'name' => 'Snippet', 'version' => '1.0', 'url' => 'http://digitalspaghetti.me.uk/', 'author' => '<NAME>', 'authorurl' => 'http://digitalspaghetti.me.uk', 'license' => 'Apache Licence 2.0', 'description' => 'A plugin to share code snippets.' ); } function action_plugin_activation( $plugin_file ) { if( Plugins::id_from_file(__FILE__) == Plugins::id_from_file($plugin_file) ) { Post::add_new_type('snippet'); } } public function action_plugin_deactivation( $file ) { if ( realpath( $file ) == __FILE__ ) { Post::deactivate_post_type('snippet'); } } public function action_init() { } /** * Add fields to the publish page for snippets * * @param FormUI $form The publish form * @param Post $post * @return array */ public function action_form_publish( $form, $post ) { if( $form->content_type->value == Post::type( 'snippet' ) ) { $postfields = $form->publish_controls->append( 'fieldset', 'snippet', _t( 'Snippet Options') ); $snippet_language = $postfields->append( 'select', 'snippet_language', 'null:null', _t('Language') ); $snippet_language->options = $this->langSelect(); $snippet_language->value = strlen( $post->info->snippet_language ) ? $post->info->snippet_language : '' ; $snippet_language->template = 'tabcontrol_select'; } } public function action_publish_post($post, $form) { if( $post->content_type == Post::type( 'snippet' ) ) { if( strlen( $form->snippet->snippet_language->value ) ) { $post->info->snippet_language = $form->snippet->snippet_language->value; } else { $post->info->__unset( 'snippet_language' ); } } } public function action_handler_display_snippets( $handler_vars ) { Utils::debug($handler_vars); exit(); } public function filter_rewrite_rules( $rules ) { $rules[] = new RewriteRule( array( 'name' => 'display_snippet', 'parse_regex' => '%^snippet/(?P<snippet_language>)/(?P<slug>)/?$%i', 'build_str' => 'snippet/{$slug}', 'handler' => 'UserThemeHandler', 'action' => 'display_snippets', 'priority' => 7, 'is_active' => 1, 'description' => 'Displays snippets of language type', )); return $rules; } } ?> <file_sep><?php /** * Blogger Importer * * @package bloggerimport * @version $Id$ * @author ayunyan <<EMAIL>> * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link http://ayu.commun.jp/habari-bloggerimport */ class BloggerImport extends Plugin implements Importer { private $supported_importers; private $import_batch = 100; /** * action: init * * @access public * @return void */ public function action_init() { $this->load_text_domain('bloggerimport'); $this->supported_importers = array(); $this->supported_importers['blogger'] = _t('Blogger Export File', 'bloggerimport'); } /** * action: update_check * * @access public * @return void */ public function action_update_check() { Update::add($this->info->name, '6e805c3a-c775-11dd-aff6-001b210f913f', $this->info->version); } /** * filter: import_names * * @access public * @param array $import_names * @return array */ public function filter_import_names($import_names) { return array_merge($import_names, $this->supported_importers); } /** * filter: import_stage * * @access public * @param string $stageoutput * @param string $import_name * @param integer $stage * @param integer $step */ public function filter_import_stage($stageoutput, $import_name, $stage, $step) { if (($importer = array_search($import_name, $this->supported_importers)) === false) { return $stageoutput; } if (empty($stage)) $stage = 1; $stage_method = $importer . '_stage_' . $stage; if (!method_exists($this, $stage_method)) { return sprintf(_t('Unknown Stage: %s', 'bloggerimport'), $stage); } $output = $this->$stage_method(array()); return $output; } /** * filter: import_form_enctype * * @access public * @param string $enctype * @param string $import_name * @param string $stage * @return string */ public function filter_import_form_enctype($enctype, $import_name, $stage) { if (($importer = array_search($import_name, $this->supported_importers)) === false) { return $enctype; } if ($importer == 'blogger') { return 'multipart/form-data'; } return $enctype; } /** * first stage of Blogger Export File import process * * @access private * @return string The UI for the first stage of the import process */ private function blogger_stage_1($inputs) { $default_values = array( 'warning' => '' ); $inputs = array_merge( $default_values, $inputs ); extract( $inputs ); ob_start(); ?> <p><?php echo _t('Habari will attempt to import from a Blogger Export File.', 'bloggerimport'); ?></p> <?php if (!empty($warning)): ?> <p class="warning"><?php echo htmlspecialchars($warning); ?></p> <?php endif; ?> <table> <tr><td><?php echo _t('Blogger Export File', 'bloggerimport'); ?></td><td><input type="file" name="file" /></td></tr> </table> <input type="hidden" name="stage" value="2"> <p class="submit"><input type="submit" name="import" value="<?php echo _t('Next', 'bloggerimport'); ?>" /></p> <?php $output = ob_get_contents(); ob_end_clean(); return $output; } /** * second stage of Blogger Export File import process * * @access private * @return string The UI for the first stage of the import process */ private function blogger_stage_2($inputs) { $default_values = array( 'warning' => '' ); $inputs = array_merge($default_values, $inputs); extract($inputs); if (empty($_FILES['file'])) { $inputs['warning'] = _t('Please specify Blogger Export File.', 'bloggerimport'); return $this->blogger_stage_1($inputs); } switch ($_FILES['file']['error']) { case UPLOAD_ERR_OK: break; default: $inputs['warning'] = _t('Upload failed.', 'bloggerimport'); return $this->blogger_stage_1($inputs); } $atom_file = tempnam(null, 'habari_'); if (!move_uploaded_file($_FILES['file']['tmp_name'], $atom_file)) { $inputs['warning'] = _t('Possible file upload attack!', 'bloggerimport'); return $this->blogger_stage_1($inputs); } $_SESSION['bloggerimport_file'] = $atom_file; $ajax_url = URL::get('auth_ajax', array('context' => 'blogger_import_all')); EventLog::log(sprintf(_t('Starting import from "%s"'), _t('Blogger Export File', 'bloggerimport'))); Options::set('import_errors', array()); ob_start(); ?> <p><?php _e('Import In Progress'); ?></p> <div id="import_progress"><?php _e('Starting Import...'); ?></div> <script type="text/javascript"> // A lot of ajax stuff goes here. $(document).ready(function(){ $('#import_progress').load( "<?php echo $ajax_url; ?>", { postindex: 0 } ); }); </script> <?php $output = ob_get_contents(); ob_end_clean(); return $output; } /** * action: auth_ajax_blogger_import_all * * @access public * @param array $handler */ public function action_auth_ajax_blogger_import_all($handler) { $feed = simplexml_load_file($_SESSION['bloggerimport_file']); if (!$feed) { echo '<p>' . _t('Failed parsing File', 'bloggerimport') . '</p>'; return; } $post_id_map = array(); $post_map = array(); $result = DB::get_results("SELECT post_id,value FROM " . DB::table('postinfo') . " WHERE name='blogger_id';"); for ($i = 0; $i < count($result); $i++) { $post_id_map[$result[$i]->value] = $result[$i]->post_id; $post_map[] = $result[$i]->value; } $comment_map = DB::get_column("SELECT value FROM " . DB::table('commentinfo') . " WHERE name='blogger_id';"); $entry_count = count($feed->entry); for ($i = 0; $i < $entry_count; $i++) { $entry = $feed->entry[$i]; switch ((string)$entry->category[0]['term']) { // post case 'http://schemas.google.com/blogger/2008/kind#post': // already exists skipped if (in_array((string)$entry->id, $post_map)) continue; $t_post = array(); $t_post['title'] = MultiByte::convert_encoding((string)$entry->title); $t_post['content'] = MultiByte::convert_encoding((string)$entry->content); $t_post['user_id'] = User::identify()->id; // TODO: import Blogger author $t_post['pubdate'] = HabariDateTime::date_create((string)$entry->published); $t_post['content_type'] = Post::type('entry'); $entry->registerXPathNamespace('app', 'http://purl.org/atom/app#'); $result = $entry->xpath('//app:draft'); if (!empty($result) && (string)$result[0] == 'yes') { $t_post['status'] = Post::status('draft'); } else { $t_post['status'] = Post::status('published'); } $tags = array(); $category_count = count($entry->category); for ($j = 0; $j < count($category_count); $j++) { $tags[] = (string)$entry->category[$i]['term']; } $post = new Post($t_post); $post->tags = array_unique($tags); $post->info->blogger_id = (string)$entry->id; try { $post->insert(); } catch (Exception $e) { EventLog::log($e->getMessage(), 'err', null, null, print_r(array($p, $e), 1)); Session::error($e->getMessage()); $errors = Options::get('import_errors'); $errors[] = $post->title . ' : ' . $e->getMessage(); Options::set('import_errors', $errors); } $post_id_map[(string)$entry->id] = $post->id; break; // comment case 'http://schemas.google.com/blogger/2008/kind#comment': // already exists skipped if (in_array((string)$entry->id, $comment_map)) continue; $result = $entry->xpath('//thr:in-reply-to'); if (empty($result) || !isset($post_id_map[(string)$result[0]['ref']])) continue; $t_comment = array(); $t_comment['post_id'] = $post_id_map[(string)$result[0]['ref']]; $t_comment['name'] = MultiByte::convert_encoding((string)$entry->author->name); if (isset($entry->author->email)) { $t_comment['email'] = (string)$entry->author->email; } if (isset($entry->author->uri)) { $t_comment['url'] = (string)$entry->author->uri; } $t_comment['content'] = MultiByte::convert_encoding((string)$entry->content); $t_comment['status'] = Comment::STATUS_APPROVED; $t_comment['date'] = HabariDateTime::date_create((string)$entry->published); $t_comment['type'] = Comment::COMMENT; $comment = new Comment($t_comment); $comment->info->blogger_id = (string)$entry->id; try { $comment->insert(); } catch (Exception $e) { EventLog::log($e->getMessage(), 'err', null, null, print_r(array($c, $e), 1)); Session::error($e->getMessage()); $errors = Options::get('import_errors'); $errors[] = $e->getMessage(); Options::set('import_errors', $errors); } break; default: break; } } EventLog::log(_t('Import complete from Blogger Export File', 'bloggerimport')); echo '<p>' . _t('Import is complete.') . '</p>'; $errors = Options::get('import_errors'); if(count($errors) > 0 ) { echo '<p>' . _t('There were errors during import:') . '</p>'; echo '<ul>'; foreach ($errors as $error) { echo '<li>' . $error . '</li>'; } echo '</ul>'; } } } ?> <file_sep><?php class Shelves extends Plugin { private static $vocabulary = 'shelves'; private static $content_type = 'entry'; protected $_vocabulary; public function __get( $name ) { switch ( $name ) { case 'vocabulary': if ( !isset( $this->_vocabulary ) ) { $this->_vocabulary = Vocabulary::get( self::$vocabulary ); } return $this->_vocabulary; } } /** * Add the shelf vocabulary and create the admin token * **/ public function action_plugin_activation( $file ) { if ( Plugins::id_from_file( $file ) == Plugins::id_from_file(__FILE__) ) { $params = array( 'name' => self::$vocabulary, 'description' => 'A vocabulary for describing Shelves', 'features' => array( 'hierarchical' ) ); Vocabulary::create( $params ); // create default access token ACL::create_token( 'manage_shelves', _t( 'Manage ') . Options::get( 'shelves__plural', _t( 'shelves', 'shelves' ) ), 'Administration', false ); $group = UserGroup::get_by_name( 'admin' ); $group->grant( 'manage_shelves' ); } } /** * Remove the admin token * **/ public function action_plugin_deactivation( $file ) { // delete default access token ACL::destroy_token( 'manage_shelves' ); } /** * Register admin template **/ public function action_init() { $this->add_template( 'shelves', dirname( $this->get_file() ) . '/shelves_admin.php' ); } /** * Check token to restrict access to the page **/ public function filter_admin_access_tokens( array $require_any, $page ) { switch ( $page ) { case 'shelves': $require_any = array( 'manage_shelves' => true ); break; } return $require_any; } /** * Display the page **/ public function action_admin_theme_get_shelves( AdminHandler $handler, Theme $theme ) { $all_terms = array(); $all_terms = $this->vocabulary->get_tree(); $one_shelf = ucfirst( Options::get( 'shelves__single', _t( 'shelf', 'shelves' ) ) ); if (!isset( $_GET[ 'shelf' ] ) ) { // create new shelf form $form = new FormUI( 'shelf-new' ); $form->set_option( 'form_action', URL::get( 'admin', 'page=shelves' ) ); $create_fieldset = $form->append( 'fieldset', '', _t( 'Create a new %s', array( $one_shelf ) , 'shelves' ) ); $shelf = $create_fieldset->append( 'text', 'shelf', 'null:null', $one_shelf, 'formcontrol_text' ); $shelf->add_validator( 'validate_required' ); $shelf->class = 'pct30'; $parent = $create_fieldset->append( 'select', 'parent', 'null:null', _t( 'Parent', 'shelves' ), 'optionscontrol_select' ); // $template doesn't work $parent->class = 'pct50'; $parent->options = array(); $parent->options[''] = ''; // top should be blank $right = array(); foreach( $all_terms as $term ) { while ( count( $right ) > 0 && $right[count( $right ) - 1] < $term->mptt_right ) { array_pop( $right ); } $parent->options[ $term->id ] = str_repeat( ' - ', count( $right ) ) . $term->term_display; $right[] = $term->mptt_right; } $save_button = $create_fieldset->append( 'submit', 'save', _t( 'Create', 'shelves' ) ); $save_button->class = 'pct20 last'; $cancelbtn = $form->append( 'button', 'btn', _t( 'Cancel', 'shelves' ) ); $form->on_success( array( $this, 'formui_create_submit' ) ); } else { // edit form for existing shelf $which_shelf = $_GET[ 'shelf' ]; $shelf_term = $this->vocabulary->get_term( $which_shelf ); if ( !$shelf_term ) { exit; } $parent_term = $shelf_term->parent(); if ( !$parent_term ) { $parent_term_display = _t( 'none', 'shelves' ); } else { $parent_term_display = $parent_term->term_display; } $form = new FormUI( 'shelf-edit' ); $form->set_option( 'form_action', URL::get( 'admin', 'page=shelves&shelf=' . $_GET[ 'shelf' ] ) ); $shelf_id = $form->append( 'hidden', 'shelf_id' )->value = $shelf_term->id; // send this id, for seeing what has changed $edit_fieldset = $form->append( 'fieldset', '', _t( 'Edit %1$s: <b>%2$s</b>', array( $one_shelf, $shelf_term->term_display ), 'shelves' ) ) ; $shelf = $edit_fieldset->append( 'text', 'shelf', 'null:null', _t( 'Rename %s', array( $one_shelf ), 'shelves' ), 'formcontrol_text' ); $shelf->value = $shelf_term->term_display; $shelf->add_validator( 'validate_required' ); $shelf->class = 'pct30'; $parent = $edit_fieldset->append( 'select', 'parent', 'null:null', sprintf( _t( 'Current Parent: <b>%1$s</b> Change Parent to:', 'shelves' ), $parent_term_display ), 'asdasdaoptionscontrol_select' ); $parent->class = 'pct50'; $parent->options = array(); $parent->options[''] = ''; // top should be blank $right = array(); foreach( $shelf_term->not_descendants() as $term ) { while ( count( $right ) > 0 && $right[count( $right ) - 1] < $term->mptt_right ) { array_pop( $right ); } $parent->options[ $term->id ] = str_repeat( ' - ', count( $right ) ) . $term->term_display; $right[] = $term->mptt_right; } $parent->value = ( !$parent_term ? '': $parent_term->id ); // select the current parent $save_button = $edit_fieldset->append( 'submit', 'save', _t( 'Edit', 'shelves' ) ); $save_button->class = 'pct20 last'; $cancel_button = $form->append( 'submit', 'cancel_btn', _t( 'Cancel', 'shelves' ) ); $form->on_success( array( $this, 'formui_edit_submit' ) ); } $theme->form = $form->get(); $theme->display( 'shelves' ); // End everything exit; } public function formui_create_submit( FormUI $form ) { if( isset( $form->shelf ) && ( $form->shelf->value <> '' ) ) { // time to create the new term. $form_parent = $form->parent->value; $new_term = $form->shelf->value; // If a new term has been set, add it to the shelves vocabulary if ( '' != $form_parent ) { // Make sure the parent term exists. $parent_term = $this->vocabulary->get_term( $form_parent ); if ( null == $parent_term ) { // There's no term for the parent, add it as a top-level term $parent_term = $this->vocabulary->add_term( $form_parent ); } $shelf_term = $this->vocabulary->add_term( $new_term, $parent_term ); } else { $shelf_term = $this->vocabulary->add_term( $new_term ); } } // redirect to the page to update the form Utils::redirect( URL::get( 'admin', array( 'page'=>'shelves' ) ), true ); } public function formui_edit_submit( FormUI $form ) { if( isset( $form->shelf ) && ( $form->shelf->value <> '' ) ) { if( isset( $form->shelf_id ) ) { $current_term = $this->vocabulary->get_term( $form->shelf_id->value ); // If there's a changed parent, change the parent. $cur_parent = $current_term->parent(); $new_parent = $this->vocabulary->get_term( $form->parent->value ); if ( $cur_parent ) { if ( $cur_parent->id <> $form->parent->value ) { // change the parent to the new ID. $this->vocabulary->move_term( $current_term, $new_parent ); } } else { // cur_parent is false, should mean $current_term is a root element $this->vocabulary->move_term( $current_term, $new_parent ); } // If the shelf has been renamed, modify the term } } // redirect to the page to update the form Utils::redirect( URL::get( 'admin', array( 'page'=>'shelves' ) ), true ); } /** * Cover both post and get requests for the page **/ public function alias() { return array( 'action_admin_theme_get_shelves'=> 'action_admin_theme_post_shelves' ); } /** * Add menu item above 'dashboard' **/ public function filter_adminhandler_post_loadplugins_main_menu( array $menu ) { $item_menu = array( 'shelves' => array( 'url' => URL::get( 'admin', 'page=shelves' ), 'title' => _t( 'Manage blog shelves' ), 'text' => ucfirst( Options::get( 'shelves__plural', _t( 'shelves', 'shelves' ) ) ), 'hotkey' => 'W', 'selected' => false, 'access' => array( 'manage_shelves' => true ) ) ); $slice_point = array_search( 'dashboard', array_keys( $menu ) ); // Element will be inserted before "dashboard" $pre_slice = array_slice( $menu, 0, $slice_point ); $post_slice = array_slice( $menu, $slice_point ); $menu = array_merge( $pre_slice, $item_menu, $post_slice ); return $menu; } /** * Add shelves to the publish form **/ public function action_form_publish ( $form, $post ) { if ( $form->content_type->value == Post::type( self::$content_type ) ) { $shelves_options = array( 0 => _t( '(none)', 'shelves' ) ) + $this->vocabulary->get_options(); // Utils::debug( $shelves_options ); die(); $form->append( 'select', 'shelf', 'null:null', ucfirst( Options::get( 'shelves__single', _t( 'shelf', 'shelves' ) ) ), $shelves_options, 'tabcontrol_select' ); $form->shelf->tabindex = $form->tags->tabindex + 1; $form->move_after( $form->shelf, $form->tags ); $form->save->tabindex = $form->save->tabindex + 1; // If this is an existing post, see if it has a shelf already if ( 0 != $post->id ) { $form->shelf->value = $this->get_shelf( $post ); } } } /** * Process shelves when the publish form is received * **/ public function action_publish_post( $post, $form ) { if ( $post->content_type == Post::type( self::$content_type ) ) { $shelves = array(); $shelf = $form->shelf->value; $this->vocabulary->set_object_terms( 'post', $post->id, array( $this->vocabulary->get_term( (int) $shelf ) ) ); } } /** * Simple plugin configuration * @return FormUI The configuration form **/ public function configure() { $ui = new FormUI( 'shelves' ); $ui->append( 'text', 'single', 'shelves__single', _t( 'Singular version of your "shelf" (e.g. "location"):', 'shelves' ) ); $ui->single->add_validator( array( $this, 'validate_both' ) ); $ui->append( 'text', 'plural', 'shelves__plural', _t( 'Plural version of your "shelves" (e.g. "locations"):', 'shelves' ) ); $ui->plural->add_validator( array( $this, 'validate_both' ) ); $ui->on_success( array( $this, 'updated_config' ) ); $ui->append( 'submit', 'save', 'save' ); return $ui; } /** * Ensure either both or neither values is set. **/ public function validate_both( $input, $control, $form ) { if ( ( $control->name == 'single' && $control->value == '' && $form->plural->value != '' ) or ( $control->name == 'plural' && $control->value == '' && $form->single->value != '' ) ) { // This wording isn't entirely accurate - if neither is set, 'shelf/shelves' will be used. return array( _t( 'Both singular and plural values must be set.', 'shelves' ) ); } return array(); } /** * Lowercase the values and give the user a session message to confirm options were saved. **/ public function updated_config( $form ) { $_POST[ $form->single->field ] = strtolower( $form->single->value ); // ugly hack, core ticket #931 $_POST[ $form->plural->field ] = strtolower( $form->plural->value ); Session::notice( _t( 'Shelves nomenclature saved.', 'shelves' ) ); $form->save(); } /** * return an array of shelves, having been cleaned up a bit. Taken from post.php r3907 * @param String $shelves Text from the Shelf text input */ public static function parse_shelves( $shelves ) { if ( is_string( $shelves ) ) { if ( '' === $shelves ) { return array(); } // just as dirrty as it is in post.php ;) $rez = array( '\\"'=>':__unlikely_quote__:', '\\\''=>':__unlikely_apos__:' ); $zer = array( ':__unlikely_quote__:'=>'"', ':__unlikely_apos__:'=>"'" ); // escape $catstr = str_replace( array_keys( $rez ), $rez, $shelves ); // match-o-matic preg_match_all( '/((("|((?<= )|^)\')\\S([^\\3]*?)\\3((?=[\\W])|$))|[^,])+/', $catstr, $matches ); // cleanup $shelves = array_map( 'trim', $matches[0] ); $shelves = preg_replace( array_fill( 0, count( $shelves ), '/^(["\'])(((?!").)+)(\\1)$/'), '$2', $shelves ); // unescape $shelves = str_replace( array_keys( $zer ), $zer, $shelves ); // just as hooray as it is in post.php return $shelves; } elseif ( is_array( $shelves ) ) { return $shelves; } } /** * Add a shelf rewrite rule * @param Array $rules Current rewrite rules **/ public function filter_default_rewrite_rules( $rules ) { $shelf = Options::get( 'shelves__single', _t( 'shelf', 'shelves' ) ); $rule = array( 'name' => 'display_entries_by_shelf', 'parse_regex' => '%^' . $shelf . '/(?P<shelf_slug>[^/]*)(?:/page/(?P<page>\d+))?/?$%i', 'build_str' => $shelf .'/{$shelf_slug}(/page/{$page})', 'handler' => 'UserThemeHandler', 'action' => 'display_entries_by_shelf', 'priority' => 5, 'description' => 'Return posts matching specified shelf.', ); $rules[] = $rule; return $rules; } /** * function filter_template_where_filters * Limit the Posts::get call to shelves * (uses tag_slug because that's really term under the hood) **/ public function filter_template_where_filters( $filters ) { $vars = Controller::get_handler_vars(); if( isset( $vars['shelf_slug'] ) ) { $term = $this->vocabulary->get_term( $vars['shelf_slug'] ); if ( $term instanceof Term ) { $terms = (array)$term->descendants(); $terms = array_map(create_function('$a', 'return $a->term;'), $terms); array_push($terms, $vars['shelf_slug']); $filters['vocabulary'] = array_merge( $filters['vocabulary'], array( self::$vocabulary . ':term' => $terms ) ); } } return $filters; } /** * function filter_theme_act_display_entries_by_shelf * Helper function: Display the posts for a shelf. Probably should be more generic eventually. * Does not appear to work currently. */ public function filter_theme_act_display_entries_by_shelf( $handled, $theme ) { $paramarray = array(); $paramarray[ 'fallback' ] = array( 'shelf.{$shelf}', 'shelf', 'multiple', ); // Makes sure home displays only entries ... maybe not necessary. Probably not, in fact. $default_filters = array( 'content_type' => Post::type( self::$content_type ), ); $paramarray[ 'user_filters' ] = $default_filters; $theme->act_display( $paramarray ); return true; } /** * function get_shelf * Gets the shelf for the post * @return int The shelf id for this post */ private function get_shelf( $post ) { $result = $this->vocabulary->get_object_terms( 'post', $post->id ); if( $result ) { // since this is not a 'multiple' vocabulary, there should be only one. return $result[0]->id; } return false; } /** * function filter_post_get * Allow post->shelf * @return array The shelf for this post **/ public function filter_post_get( $out, $name, $post ) { if( $name != 'shelf' ) { return $out; } $shelves = array(); $result = $this->vocabulary->get_object_terms( 'post', $post->id ); if( $result ) { // since this is not a 'multiple' vocabulary, there should be only one. return $result[0]->term_display; } return false; } /** * function delete_shelf * Deletes an existing shelf and all relations to it. **/ public static function delete_shelf( $shelf = '' ) { $vocabulary = Vocabulary::get( self::$vocabulary ); // should there be a Plugins::act( 'shelf_delete_before' ...? $term = $vocabulary->get_term( $shelf ); if ( !$term ) { return false; // no match for shelf } $result = $vocabulary->delete_term( $term ); if ( $result ) { EventLog::log( sprintf( _t( '%1$s \'%2$s\' deleted.' ), array( Options::get( 'shelves__singule', _t( 'shelf', 'shelves' ) ), $shelf ) ), 'info', 'content', 'shelves' ); } // should there be a Plugins::act( 'shelf_delete_after' ...? return $result; } /** * Allow searching by ($singular):whatever **/ public function filter_posts_search_to_get( $arguments, $flag, $value, $match, $search_string ) { if ( Options::get( 'shelves__single', _t( 'shelf', 'shelves' ) ) == $flag ) { $arguments['vocabulary'][$this->vocabulary->name . ':term_display'][] = $value; } return $arguments; } } class ShelvesFormat extends Format { public static function link_shelf( $a, $b ) { return '<a href="' . URL::get( "display_entries_by_shelf", array( "shelf_slug" => $b ) ) . "\" rel=\"shelf\">$a</a>"; } } ?><file_sep><!-- sidebar --> <h3>Search</h3> <div id="search"> <?php $theme->display ('searchform' ); ?> </div> <h3><?php if($request->display_home) { echo "Other Entries"; } else { echo "Recent Entries"; } ?></h3> <div id="recent-entries"> <ul> <?php if($request->display_home) { $limit = "5,15"; } else { $limit = "0,10"; } $entries = DB::get_results("SELECT * FROM ".DB::Table('posts')." WHERE content_type = '1' AND status = '2' ORDER BY pubdate DESC LIMIT $limit"); foreach ($entries as $entry) { ?> <li><a href="<?php Site::out_url( 'habari' ); ?>/<?php echo $entry->slug; ?>" title="<?php echo $entry->title; ?>"><?php echo $entry->title; ?></a></li> <?php } ?> </ul> </div> <?php $theme->area( 'sidebar' ); ?> <!-- /sidebar --> <file_sep><?php class IncomingLinks extends Plugin { /** * Adds an incoming links module to the dashboard * */ // Setting the expiry to 2 hours means it will never expire, because the cron job runs every hour. private $cache_expiry = 7200; /** * Required Plugin Informations */ public function info() { return array( 'name' => 'IncomingLinks', 'version' => '1.0', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Incoming Links Dashboard Module', 'copyright' => '2008' ); } /** * */ public function action_plugin_activation( $file ) { if ( realpath( $file ) == __FILE__ ) { Modules::add( 'Incoming Links' ); // Add a periodical execution event to be triggered hourly CronTab::add_hourly_cron( 'incoming_links', 'incoming_links', 'Find links to this blog.' ); } } function action_plugin_deactivation( $file ) { if ( Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__) ) { // remove the module from the dash if it is active Modules::remove_by_name( 'Incoming Links' ); // Remove the periodical execution event CronTab::delete_cronjob( 'incoming_links' ); // Clear the cached links Cache::expire( 'incoming_links' ); } } /** * Plugin incoming_links filter, executes for the cron job defined in action_plugin_activation() * @param boolean $result The incoming result passed by other sinks for this plugin hook * @return boolean True if the cron executed successfully, false if not. */ public function filter_incoming_links( $result ) { $incoming_links = $this->get_incoming_links(); Cache::set( 'incoming_links', $incoming_links, $this->cache_expiry ); return $result; // Only change a cron result to false when it fails. } public function filter_dash_modules( $modules ) { $modules[]= 'Incoming Links'; $this->add_template( 'dash_incoming_links', dirname( __FILE__ ) . '/dash_incoming_links.php' ); return $modules; } public function filter_dash_module_incoming_links( $module, $module_id, $theme ) { $theme->incoming_links = $this->theme_incoming_links(); $module['content']= $theme->fetch( 'dash_incoming_links' ); return $module; } public function theme_incoming_links() { // There really should be something in the cache, CronJob should have put it there, but if there's not, go get the links now if ( Cache::has( 'incoming_links' ) ) { $incoming_links = Cache::get( 'incoming_links' ); } else { $incoming_links = $this->get_incoming_links(); Cache::set( 'incoming_links', $incoming_links, $this->cache_expiry ); } return $incoming_links; } private function get_incoming_links() { $links = array(); try { $search = new RemoteRequest( 'http://blogsearch.google.com/blogsearch_feeds?scoring=d&num=10&output=atom&q=link:' . Site::get_url( 'habari' ) ); $search->set_timeout( 5 ); $result = $search->execute(); if ( Error::is_error( $result ) ) { throw $result; } $response = $search->get_response_body(); $xml = new SimpleXMLElement( $response ); foreach( $xml->entry as $entry ) { //<!-- need favicon discovery and caching here: img class="favicon" src="http://skippy.net/blog/favicon.ico" alt="favicon" / --> $links[]= array( 'href' => (string)$entry->link['href'], 'title' => (string)$entry->title ); } } catch(Exception $e) { $links['error']= $e->getMessage(); } return $links; } /** * Enable update notices to be sent using the Habari beacon */ public function action_update_check() { Update::add( 'IncomingLinks', 'f33b2428-facb-43b7-bb44-a8d78cb3ff9d', $this->info->version ); } } ?> <file_sep><?php /** * * Copyright 2010 <NAME> - http:/peeters.22web.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * Keywords plugin adds Meta Keywords and Description for each post. * Inspired by MetaSEO plugin by Habari Community - http://habariproject.org * * @package Keywords * @version 0.1 * @author <NAME> - http:/peeters.22web.net * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 (unless otherwise stated) * @link http://peeters.22web.net/project-habari-keywords */ class Keywords extends Plugin { /** * @var $them Theme object that is currently being use for display */ private $theme; /** * Beacon Support for Update checking * * @access public * @return void **/ public function action_update_check() { Update::add('Keywords', '988D9D60-F159-11DF-B86D-78F8DFD72085', $this->info->version); } /** * We only want to use this to obtain reference on current Theme object. * * @param $theme Theme object being displayed */ function action_add_template_vars($theme) { $this->theme = $theme; } /** * function filter_final_output * * this filter is called before the display of any page, so it is used * to make any final changes to the output before it is sent to the browser * * @param $buffer string the page being sent to the browser * @return string the modified page */ public function filter_final_output($buffer) { $keywords = $this->get_keywords(); if (strlen($keywords)) { $template_keywords = $this->extract_keywords($buffer); if (strlen($template_keywords)) { $buffer = str_replace($template_keywords, $keywords, $buffer); } } $description = $this->get_description(); if (strlen($description)) { $template_description = $this->extract_description($buffer); if (strlen($template_description)) { $buffer = str_replace($template_description, $description, $buffer); } } return $buffer; } /** * Add additional controls to the publish page tab * * @param FormUI $form The form that is used on the publish page * @param Post $post The post being edited */ public function action_form_publish($form, $post) { $fieldset = $form->publish_controls->append('fieldset', 'meta', 'Meta'); $keywords = $fieldset->append('text', 'keywords', 'null:null', 'Keywords'); $keywords->value = strlen($post->info->keywords) ? $post->info->keywords : ''; $keywords->template = 'tabcontrol_text'; $description = $fieldset->append('textarea', 'description', 'null:null', 'Description'); $description->value = isset($post->info->description) ? $post->info->description : ''; $description->template = 'tabcontrol_textarea'; } /** * Modify a post before it is updated * * @param Post $post The post being saved, by reference * @param FormUI $form The form that was submitted on the publish page */ public function action_publish_post($post, $form) { if (strlen($form->meta->keywords->value)) { $post->info->keywords = htmlspecialchars(Utils::truncate(strip_tags($form->meta->keywords->value), 200, false), ENT_COMPAT, 'UTF-8'); } else { $post->info->__unset('keywords'); } if (strlen($form->meta->description->value)) { $post->info->description = htmlspecialchars(Utils::truncate(strip_tags($form->meta->description->value), 200, false), ENT_COMPAT, 'UTF-8'); } else { $post->info->__unset('description'); } } /** * Return the string list of keywords for the post * * @access private * @return string */ private function get_keywords() { $out = ''; $keywords = ''; $matched_rule = URL::get_matched_rule(); if (is_object($matched_rule)) { $rule = $matched_rule->name; switch($rule) { case 'display_entry': case 'display_page': if(isset($this->theme->post)) { if (strlen($this->theme->post->info->keywords)) { $keywords = $this->theme->post->info->keywords; } else if (count($this->theme->post->tags) > 0) { $keywords = implode(', ', $this->theme->post->tags); } } break; case 'display_entries_by_tag': $keywords = Controller::get_var('tag'); break; default: } } $keywords = htmlspecialchars(strip_tags($keywords), ENT_COMPAT, 'UTF-8'); if (strlen($keywords)) { $out = "<meta name=\"keywords\" content=\"".$keywords."\">"; } return $out; } /** * Return the description for the post * * @access private * @return string */ private function get_description() { $out = ''; $description = ''; $matched_rule = URL::get_matched_rule(); if (is_object($matched_rule)) { $rule = $matched_rule->name; switch($rule) { case 'display_entry': case 'display_page': if(isset($this->theme->post)) { if (strlen($this->theme->post->info->description)) { $description = $this->theme->post->info->description; } } break; default: } } $description = htmlspecialchars(strip_tags($description), ENT_COMPAT, 'UTF-8'); if (strlen($description)) { $out = "<meta name=\"description\" content=\"".$description."\">"; } return $out; } private function extract_keywords($content) { $tags = preg_match('/(<meta name="keywords" content=".*">)/i', $content, $patterns); $res = $patterns[1]; return $res; } private function extract_description($content) { $tags = preg_match('/(<meta name="description" content=".*">)/i', $content, $patterns); $res = $patterns[1]; return $res; } } ?> <file_sep><h3>Monthly Archives</h3> <?php $theme->monthly_archives(5, 'N'); ?> <file_sep><div id="fireeagle"> <?php if (!empty($fireeagle_location)): ?> <h2><?php echo _t('Location', 'fireeagle'); ?></h2> <?php echo sprintf(_t('I\'m at %s.', 'fireeagle'), htmlspecialchars($fireeagle_location)); ?> <?php if (Plugins::is_loaded('14c8414f-6cdf-11dd-b14a-001b210f913f')): ?> <a href="http://maps.google.com/?ll=<?php echo $fireeagle_latitude . ',' . $fireeagle_longitude; ?>&amp;z=<?php echo $zoom; ?>&amp;_markers=<?php echo $fireeagle_latitude . ',' . $fireeagle_longitude; ?>&amp;_size=180x180&amp;_controls=none"><?php echo htmlspecialchars($fireeagle_location); ?></a> <?php endif; ?> <?php endif; ?> </div><file_sep>// Inline edit var inEdit = { init: function() { inEdit.editables = '.date a.edit-date, .title a.author.edit-author, .authorinfo a.edit-url, .authorinfo a.edit-email, .time span.edit-time, .content.edit-content'; if ($('#comments').length === 0) { // Only works for comments, presently return; } $(inEdit.editables, $('.item')).filter(':not(a)').each(function() { $(this).addClass('editable'); $(this).click(function() { if (inEdit.activated != $(this).parents('.item').attr('id').substring(8)) { inEdit.deactivate(); inEdit.activate($(this).parents('.item')); } return false; }); }); }, activated: false, editables: null, getDestination: function( classes ) { classes = classes.split(" "); var clas = null; for (var key in classes) { if (classes.hasOwnProperty(key)) { clas = classes[key]; if (clas.search('edit-') != -1) { destination = clas.substring(clas.search('edit-') + 5); return destination; } } } return false; }, activate: function( parent ) { $(parent).hide().addClass('ignore'); parent = $(parent).clone().addClass('clone').removeClass('ignore').show().insertAfter(parent); editables = $(inEdit.editables, parent); inEdit.activated = $(parent).attr('id').substring(8); var form = $('<form action="#"></form>').addClass('inEdit'); parent.wrap(form); editables.each(function() { var classes = $(this).attr('class'); destination = inEdit.getDestination(classes); var val = $(this).text(); var width = $(this).width(); var field; $(this).hide(); if ($(this).hasClass('area')) { field = $('<textarea></textarea>'); field.height(100) .attr('class', classes) .removeClass('pct75') .width(width - 13); } else { field = $('<input></input>'); field.attr('class', classes) .width(width + 5); } field.addClass('editor').removeClass('editable') .val(val) .insertAfter($(this)); }); $('ul.dropbutton li:not(.cancel):not(.submit)', parent).remove(); $('ul.dropbutton li.cancel, ul.dropbutton li.submit', parent).removeClass('nodisplay'); $('ul.dropbutton li.submit', parent).addClass('first-child'); $('ul.dropbutton li.cancel', parent).addClass('last-child'); dropButton.init(); dropButton.init(); var submit = $('<input type="submit"></input>') .addClass('inEditSubmit') .val('Update') .hide() .appendTo(parent); $("form").submit(function() { inEdit.update(); return false; }); itemManage.initItems(); itemManage.changeItem(); }, update: function() { spinner.start(); query = {}; $('.editor').each(function() { query[inEdit.getDestination($(this).attr('class'))]= $(this).val(); }); query.id = inEdit.activated; query.timestamp = $('input#timestamp').attr('value'); query.nonce = $('input#nonce').attr('value'); query.digest = $('input#PasswordDigest').attr('value'); $.ajax({ type: 'POST', url: habari.url.ajaxInEdit, data: query, dataType: 'json', success: function( result ){ spinner.stop(); jQuery.each( result, function( index, value) { humanMsg.displayMsg( value ); } ); inEdit.deactivate(); loupeInfo = timeline.getLoupeInfo(); itemManage.fetch( loupeInfo.offset, loupeInfo.limit, false ); } }); }, deactivate: function() { inEdit.activated = false; $('.item').show().removeClass('ignore'); $('form.inEdit').remove(); itemManage.changeItem(); } }; $(document).ready(function(){ $('a.author').addClass('edit-author'); $('a.url').addClass('edit-url'); $('a.email').addClass('edit-email'); $('span.content').addClass('edit-content area'); itemManage.inEdit = true; inEdit.init(); }); <file_sep><?php class URLApprove extends Plugin { const DIRECT = 1; const REDIRECT = 2; private $fetch_real = false; public function action_init() { $this->load_text_domain('urlapprove'); } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions['urlapprove'] = _t( 'Configure' ); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { $ui = new FormUI( 'urlapprove' ); $ui->append( 'checkbox', 'redirect_default', 'urlapprove__redirect_default', _t( 'Redirect all comment author links by default', 'urlapprove' ) ); $ui->append( 'textarea', 'whitelist', 'urlapprove__whitelist', _t('Whitelist of domains that will not be redirected, one per line (does not auto-approve)') ); $ui->append( 'submit', 'submit', 'Submit' ); $ui->out(); } } public function action_admin_header() { $script = <<< SCRIPT //Need to call this on ajax comment reload \$(function(){ \$('.comments .item:has(.commenter_redirected)').addClass('redirected')}); SCRIPT; $style = <<< STYLE #comments .redirected .author { color: red; font-style: italic; } STYLE; Stack::add('admin_header_javascript', $script, 'urlapprove', array('jquery', 'admin')); Stack::add('admin_stylesheet', array($style, 'screen'), 'urlapprove'); } public function filter_comment_actions($actions, $comment) { if($comment->url == '') { return $actions; } if($comment->info->redirecturl == URLApprove::REDIRECT || (!isset($comment->info->redirecturl) && Options::get('urlapprove__redirect_default') == true) ) { $actions['direct'] = array('url' => 'javascript:itemManage.update(\'direct\','. $comment->id . ');', 'title' => _t('Use Direct link to author URL'), 'label' => _t('Direct Link')); } else { $actions['redirect'] = array('url' => 'javascript:itemManage.update(\'redirect\','. $comment->id . ');', 'title' => _t('Use Redirected link to author URL'), 'label' => _t('Redirect Link')); } return $actions; } public function filter_admin_comments_action($status_msg, $action, $comments ) { switch($action) { case 'direct': $value = URLApprove::DIRECT; $status_msg = _t('Comment set to link directly.'); break; case 'redirect': $value = URLApprove::REDIRECT; $status_msg = _t('Comment set to use redirector.'); break; default: return $status_msg; } foreach($comments as $comment) { $comment->info->redirecturl = $value; $comment->info->commit(); } return $status_msg; } public function action_comment_insert_before($comment) { if($comment->url != '') { $lastcomment = Comments::get(array('url' => $comment->url, 'limit' => 1, 'orderby'=>'`date` DESC', 'fetch_fn'=>'get_row')); if($lastcomment instanceof Comment) { if(isset($lastcomment->info->redirecturl)) { $comment->info->redirecturl = $lastcomment->info->redirecturl; } } } } protected function get_hash($commentid) { return substr(md5($commentid . $_SERVER['REMOTE_ADDR'] . Options::get('GUID') . HabariDateTime::date_create()->yday), 0, 6); } private function get_whitelist() { static $whitelist = null; if(is_null($whitelist)) { $whitelist = explode("\n", Options::get('urlapprove__whitelist')); $whitelist = array_map('trim', $whitelist); $whitelist = Plugins::filter('urlapprove_whitelist', $whitelist); } return $whitelist; } public function filter_comment_url_out($value, $comment) { $whitelist = $this->get_whitelist(); if(count($whitelist) > 0 && $comment->url != '') { $comment_url = InputFilter::parse_url($value); $domain = $comment_url['host']; if(in_array($domain, $whitelist)) { return $value; } } if(isset($comment->info->redirecturl)){ if($comment->info->redirecturl == URLApprove::REDIRECT) { $value = URL::get('comment_url_redirect', array('id' => $comment->id, 'ccode' => $this->get_hash($comment->id))); } } elseif(Options::get('urlapprove__redirect_default') == true) { $value = URL::get('comment_url_redirect', array('id' => $comment->id, 'ccode' => $this->get_hash($comment->id))); } return $value; } public function filter_rewrite_rules($rules) { $rules[] = new RewriteRule(array( 'name' => 'comment_url_redirect', 'parse_regex' => '/^(?P<id>([0-9]+))\/(?P<ccode>([0-9a-f]+))\/redirect[\/]{0,1}$/i', 'build_str' => '{$id}/{$ccode}/redirect', 'handler' => 'FeedbackHandler', 'action' => 'comment_url_redirect', 'priority' => 7, 'is_active' => 1, )); return $rules; } public function action_handler_comment_url_redirect($handler_vars) { $comment = Comment::get($handler_vars['id']); $hash = $this->get_hash($handler_vars['id']); if($hash == $handler_vars['ccode']) { Utils::redirect($comment->url); exit; } header('HTTP/1.1 410 Gone'); exit; } } ?><file_sep><?php /** * Twitter Plugin * * Lets you show your current Twitter status in your theme, as well * as an option automatically post your new posts to Twitter. * * Usage: <?php $theme->twitter(); ?> to show your latest tweet in a theme. * A sample tweets.php template is included with the plugin. This can be copied to your * active theme and modified. * **/ class Twitter extends Plugin { /** * Required plugin information * @return array The array of information **/ public function info() { return array( 'name' => 'Twitter', 'version' => '0.13', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Twitter plugin for Habari', 'copyright' => '2009' ); } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Twitter', 'DD2774BA-96ED-11DC-ABEF-3BAA56D89593', $this->info->version ); } /** * Add help text to plugin configuration page **/ public function help() { $help = _t( "This plugin does two things: Post a notification to your twitter stream linking to a newly published post, and retrieving and displaying your recent status update on your blog. Either or both can be enabled.<br>A 'tweets' template file for themes is provided." ); return $help; } /** * Add actions to the plugin page for this plugin * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id **/ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = 'Configure'; } return $actions; } /** * Sets the new 'hide_replies' option to '0' to mimic current, non-reply-hiding * functionality. **/ public function action_plugin_activation( $file ) { if(Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__)) { if ( Options::get( 'twitter__hide_replies' ) == null ) { Options::set( 'twitter__hide_replies', 0 ); } if (( Options::get( 'twitter__linkify_urls' ) == null ) or ( Options::get( 'twitter__linkify_urls' ) > 1 )) { Options::set( 'twitter__linkify_urls', 0 ); } if ( Options::get( 'twitter__hashtags_query' ) == null ) { Options::set( 'twitter__hashtags_query', 'http://hashtags.org/search?query=' ); } } } /** * Respond to the user selecting an action on the plugin page * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook **/ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { if ( $action == _t( 'Configure' ) ) { $ui = new FormUI( strtolower( get_class( $this ) ) ); $twitter_username = $ui->append( 'text', 'username', 'twitter__username', _t('Twitter Username:') ); $twitter_password = $ui->append( 'password', '<PASSWORD>', '<PASSWORD>', _t('Twitter Password:') ); $post_fieldset = $ui->append( 'fieldset', 'post_settings', _t( 'Autopost Updates from Habari' ) ); $twitter_post = $post_fieldset->append( 'checkbox', 'post_status', 'twitter__post_status', _t('Autopost to Twitter:') ); $twitter_post = $post_fieldset->append( 'text', 'prepend', 'twitter__prepend', _t('Prepend to Autopost:') ); $twitter_post->value = "New Blog Post:"; $tweet_fieldset = $ui->append( 'fieldset', 'tweet_settings', _t( 'Displaying Status Updates' ) ); $twitter_show = $tweet_fieldset->append( 'checkbox', 'show', 'twitter__show', _t( 'Display twitter status updates in Habari' ) ); $twitter_show = $tweet_fieldset->append( 'checkbox', 'hide_replies', 'twitter__hide_replies', _t( 'Do not show @replies') ); $twitter_show = $tweet_fieldset->append( 'checkbox', 'linkify_urls', 'twitter__linkify_urls', _t('Linkify URLs') ); $twitter_hashtags = $tweet_fieldset->append( 'text', 'hashtags_query', 'twitter__hashtags_query', _t('#hashtags query link:') ); $twitter_cache_time = $ui->append( 'text', 'cache', 'twitter__cache', _t('Cache expiry in seconds:') ); $ui->on_success( array( $this, 'updated_config' ) ); $ui->append( 'submit', 'save', _t('Save') ); $ui->out(); } } } /** * Add Twitter options to the user profile page. * Should only be displayed when a user accesses their own profile. **/ public function action_form_user( $form, $edit_user ) { $twitter_name = ( isset( $edit_user->info->twitter_name ) ) ? $edit_user->info->twitter_name : ''; $twitter_pass = ( isset( $edit_user->info->twitter_pass ) ) ? $edit_user->info->twitter_pass : ''; $twitter = $form->insert('page_controls', 'wrapper', 'twitter', _t( 'Twitter' ) ); $twitter->class = 'container settings'; $twitter->append( 'static', 'twitter', '<h2>' . htmlentities( _t('Twitter'), ENT_COMPAT, 'UTF-8' ) . '</h2>' ); $form->move_after( $twitter, $form->change_password ); $twitter_name = $form->twitter->append( 'text','twitter_name', 'null:null', _t( 'Twitter Username'), 'optionscontrol_text' ); $twitter_name->class[] = 'item clear'; $twitter_name->value = $edit_user->info->twitter_name; $twitter_name->charlimit = 64; $twitter_name->helptext = _t( 'Used for autoposting your published entries to Twitter' ); $twitter_pass = $form->twitter->append( 'text','twitter_pass', 'null:null', _t( 'Twitter Password'), 'optionscontrol_text' ); $twitter_pass->class[] = 'item clear'; $twitter_pass->type = 'password'; $twitter_pass->value = $edit_user->info->twitter_pass; $twitter_pass->helptext = ''; } /** * Give the user a session message to confirm options were saved. **/ public function updated_config( FormUI $ui ) { Session::notice( _t( 'Twitter options saved.', 'twitter' ) ); $ui->save(); } /** * Add the Twitter options to the list of valid field names. * This causes adminhandler to recognize the Twitter fields and * to set the userinfo record appropriately **/ public function filter_adminhandler_post_user_fields( $fields ) { $fields['twitter_name'] = 'twitter_name'; $fields['twitter_pass'] = '<PASSWORD>'; return $fields; } /** * Post a status to Twitter * @param string $tweet The new status to post **/ public function post_status( $tweet, $name, $pw ) { $request = new RemoteRequest( 'http://twitter.com/statuses/update.xml', 'POST' ); $request->add_header( array( 'Authorization' => 'Basic ' . base64_encode( "{$name}:{$pw}" ) ) ); $request->set_body( 'source=habari&status=' . urlencode( $tweet ) ); $request->execute(); } /** * React to the update of a post status to 'published' * @param Post $post The post object with the status change * @param int $oldvalue The old status value * @param int $newvalue The new status value **/ public function action_post_update_status( $post, $oldvalue, $newvalue ) { if ( is_null( $oldvalue ) ) return; if ( $newvalue == Post::status( 'published' ) && $post->content_type == Post::type('entry') && $newvalue != $oldvalue ) { if ( Options::get( 'twitter__post_status' ) == '1' ) { $user = User::get_by_id( $post->user_id ); if ( ! empty( $user->info->twitter_name ) && ! empty( $user->info->twitter_pass ) ) { $name = $user->info->twitter_name; $pw = $user->info->twitter_pass; } else { $name = Options::get( 'twitter__username' ); $pw = Options::get( 'twitter__password' ); } $this->post_status( Options::get( 'twitter__prepend' ) . $post->title . ' ' . $post->permalink, $name, $pw ); } } } public function action_post_insert_after( $post ) { return $this->action_post_update_status( $post, -1, $post->status ); } /** * Add last Twitter status, time, and image to the available template vars * @param Theme $theme The theme that will display the template **/ public function theme_twitter( $theme ) { if ( Options::get( 'twitter__show' ) && Options::get( 'twitter__username' ) != '' ) { $twitter_url = 'http://twitter.com/statuses/user_timeline/' . urlencode( Options::get( 'twitter__username' ) ) . '.xml'; // We only need to get a single tweet if we're hiding replies (otherwise we can rely on the maximum returned and hope there's a non-reply) if ( Options::get( 'twitter__hide_replies' ) != '1' ) { $twitter_url .= '?count=1'; } if ( Cache::has( 'twitter_tweet_text' ) && Cache::has( 'twitter_tweet_time' ) && Cache::has( 'tweet_image_url' ) ) { $theme->tweet_text = Cache::get( 'twitter_tweet_text' ); $theme->tweet_time = Cache::get( 'twitter_tweet_time' ); $theme->tweet_image_url = Cache::get( 'tweet_image_url' ); } else { try { $r = new RemoteRequest( $twitter_url ); $r->set_timeout( 10 ); $r->execute(); $response = $r->get_response_body(); $xml = @new SimpleXMLElement( $response ); // Check we've got a load of statuses returned if ( $xml->getName() === 'statuses' ) { foreach ( $xml->status as $status ) { if ( ( Options::get( 'twitter__hide_replies' ) != '1' ) || ( strpos( $status->text, '@' ) !== 0) ) { $theme->tweet_text = (string) $status->text; $theme->tweet_time = (string) $status->created_at; $theme->tweet_image_url = (string) $status->user->profile_image_url; break; } else { // it's a @. Keep going. } } if ( !isset( $theme->tweet_text ) ) { $theme->tweet_text = 'No non-replies replies available from Twitter.'; $theme->tweet_time = ''; $theme->tweet_image_url = ''; } } // You can get error as a root element if Twitter is in maintenance mode. else if ( $xml->getName() === 'error' ) { $theme->tweet_text = (string) $xml; $theme->tweet_time = ''; $theme->tweet_image_url = ''; } // Um, yeah. We shouldn't ever hit this. else { $theme->tweet_text = 'Received unexpected XML from Twitter.'; $theme->tweet_time = ''; $theme->tweet_image_url = ''; } // Cache (even errors) to avoid hitting rate limit. Cache::set( 'twitter_tweet_text', $theme->tweet_text, Options::get( 'twitter__cache' ) ); Cache::set( 'twitter_tweet_time', $theme->tweet_time, Options::get( 'twitter__cache' ) ); Cache::set( 'tweet_image_url', $theme->tweet_image_url, Options::get( 'twitter__cache' ) ); } catch ( Exception $e ) { $theme->tweet_text = 'Unable to contact Twitter.'; $theme->tweet_time = ''; $theme->tweet_image_url = ''; } } } else { $theme->tweet_text = _t('Please set your username in the <a href="%s">Twitter plugin config</a>', array( URL::get( 'admin' , 'page=plugins&configure=' . $this->plugin_id . '&configaction=Configure' ) . '#plugin_' . $this->plugin_id ) , 'twitter' ); $theme->tweet_time = ''; $theme->tweet_image_url = ''; } if ( Options::get( 'twitter__linkify_urls' ) != FALSE ) { /* link to all http: */ $theme->tweet_text = preg_replace( '%https?://\S+?(?=(?:[.:?"!$&\'()*+,=]|)(?:\s|$))%i', "<a href=\"$0\">$0</a>", $theme->tweet_text ); /* link to usernames */ $theme->tweet_text = preg_replace( "/(?<!\w)@([\w-_.]{1,64})/", "@<a href=\"http://twitter.com/$1\">$1</a>", $theme->tweet_text ); /* link to hashtags */ $theme->tweet_text = preg_replace( '/(?<!\w)#((?>\d{1,64}|)[\w-.]{1,64})/', "<a href=\"" . Options::get('twitter__hashtags_query') ."$1\">#$1</a>", $theme->tweet_text ); } return $theme->fetch( 'tweets' ); } /** * On plugin init, add the template included with this plugin to the available templates in the theme */ public function action_init() { $this->add_template('tweets', dirname(__FILE__) . '/tweets.php'); } } ?> <file_sep><!-- sidebar --> <div id="sidebar"> <div id="search-form"> <form action="<?php URL::out('display_search'); ?>" method="get"> <fieldset> <h3><label for="criteria"><?php _e('Search', 'demorgan'); ?></label></h3> <input type="text" id="criteria" name="criteria" value="<?php if (isset($criteria)) { echo htmlentities($criteria, ENT_COMPAT, 'UTF-8'); } ?>" /> <input id="search-submit" type="submit" value="Search" /> </fieldset> </form> </div> <ul id="sidebar-1" class="xoxo"> <?php $theme->display('recententries.widget'); $theme->freshcomments(); $theme->show_recentcomments(); $theme->flickrfeed(); if (Plugins::is_loaded('FlickrRSS')) $theme->display('flickrrss.widget'); $theme->show_blogroll(); $theme->deliciousfeed(); if (Plugins::is_loaded('FreshSurf')) $theme->display('freshsurf.widget'); ?> </ul> <ul id="sidebar-2" class="xoxo"> <?php if (strlen(Options::get('about')) > 0) { ?> <li id="widget-about" class="widget"> <h3><?php _e('About', 'demorgan'); ?></h3> <p><?php Options::out('about'); ?></p> </li> <?php } ?> <?php $theme->display('tagcloud.widget'); $theme->jaiku(); $theme->twitter(); $theme->twitterlitte(); $theme->audioscrobbler(); $theme->display('feedlink.widget'); $theme->display('admin.widget'); ?> </ul> </div> <hr /> <!-- /sidebar --> <file_sep><?php if( isset($spelling) && strlen($spelling) > 0 ): ?> <div class="spellcorrect"> Did you mean: <a href="<?php echo Url::get("display_search", array("criteria" => $spelling)); ?>"> <?php echo $spelling ?> </a> </div> <?php endif; ?><file_sep><h2>Popular Posts</h2> <ul> <?php foreach ( $popular_posts as $post ) { echo "<li><a href='{$post->permalink}'>{$post->title}</a></li>\n"; } ?> </ul> <file_sep><?php class Piwik extends Plugin { /** * Display help text * @return string The help text */ public function help() { return '<p>Piwik is an Open Source Web analytics package. Piwik is self-hosted software. You need to install and configure Piwik separately. Piwik needs PHP and a MySQL database to store data on site visits. <p>For more details, see <a href="http://piwik.org/">http://piwik.org/</a> <p>This plugin embeds the Piwik (Javascript) tracking code in the theme footer. To install the plugin, unpack under the \'/user/plugins\' directory in your Habari installation. Then activate and configure the plugin from the dashboard (Admin-Plugins). <p>The configuration options are: <ul> <li>Pwiki site URL: This is the full URL of the Piwik site (e.g. \'http://www.example.com/piwik/\').</li> <li>Piwik site number: Piwik can track multiple Web sites. The site number is displayed in the Piwik-Settings administration screen under the \'Site\' tab in the \'ID\' field.</li> <li>Tracked logged-in users: Visits by logged in users can optionally be ignored.</li> </ul>'; } public function filter_plugin_config($actions, $plugin_id) { if ( $this->plugin_id() == $plugin_id ) { $actions[]= _t('Configure'); } return $actions; } public function action_plugin_ui($plugin_id, $action) { if ( $this->plugin_id() == $plugin_id && $action == _t('Configure')){ $form = new FormUI(strtolower(get_class($this))); $form->append('text', 'siteurl', 'option:piwik__siteurl', _t('Piwik site URL')); $form->append('text', 'sitenum', 'option:piwik__sitenum', _t('Piwik site number')); $form->append('checkbox', 'trackloggedin', 'option:piwik__trackloggedin', _t( 'Track logged-in users', 'piwik' )); $form->append('submit', 'save', 'Save'); $form->on_success( array( $this, 'save_config' ) ); $form->out(); } } /** * Invoked when the before the plugin configurations are saved * * @param FormUI $form The configuration form being saved * @return true */ public function save_config( $form ) { $form->save(); Session::notice('Piwik plugin configuration saved'); return false; } public function action_plugin_deactivation( $file ) { if ( realpath( $file ) == __FILE__ ) { Options::delete('piwik__siteurl'); Options::delete('piwik__sitenum'); Options::delete('piwik__trackloggedin'); Modules::remove_by_name( 'Piwik' ); } } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Piwik', 'xxx', $this->info->version ); } public function action_plugin_activation($file) { if (Plugins::id_from_file($file) != Plugins::id_from_file(__FILE__)) return; Options::set('piwik__trackloggedin', false); } public function theme_footer($theme) { $class= strtolower( get_class( $this ) ); $siteurl = Options::get( $class . '__siteurl'); if (strrpos($siteurl,'/') !== 0) $siteurl .= '/'; $ssl_siteurl = str_replace("http://", "https://", $siteurl); $sitenum = Options::get( $class . '__sitenum'); $trackloggedin = Options::get( $class . '__trackloggedin'); if ( URL::get_matched_rule()->entire_match == 'user/login') { // Login page; don't dipslay return; } if ( User::identify()->loggedin ) { // Only track the logged in user if we were told to if ( !($trackloggedin) ) { return; } } echo <<<EOD <!-- Piwik --> <script type="text/javascript"> var pkBaseURL = (("https:" == document.location.protocol) ? "${ssl_siteurl}" : "{$siteurl}"); document.write(unescape("%3Cscript src='" + pkBaseURL + "piwik.js' type='text/javascript'%3E%3C/script%3E")); </script><script type="text/javascript"> try { var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", {$sitenum}); piwikTracker.trackPageView(); piwikTracker.enableLinkTracking(); } catch( err ) { } </script> <!-- End Piwik Tag --> EOD; } } ?> <file_sep><?php define( 'DRUPAL_IMPORT_BATCH', 100 ); /** * Drupal Importer - Imports data from Drupal into Habari */ class DrupalImport extends Plugin implements Importer { private $supported_importers = array(); /** * Initialize plugin. * Set the supported importers. **/ public function action_init() { $this->supported_importers = array( _t( 'Drupal 6.x Database' ) ); } /** * Return a list of names of things that this importer imports * * @return array List of importables. */ public function filter_import_names($import_names) { return array_merge( $import_names, $this->supported_importers ); } /** * Plugin filter that supplies the UI for the Drupal importer * * @param string $stageoutput The output stage UI * @param string $import_name The name of the selected importer * @param string $stage The stage of the import in progress * @param string $step The step of the stage in progress * @return output for this stage of the import */ public function filter_import_stage($stageoutput, $import_name, $stage, $step) { // Only act on this filter if the import_name is one we handle... if ( ! in_array( $import_name, $this->supported_importers ) ) { // Must return $stageoutput as it may contain the stage HTML of another importer return $stageoutput; } $inputs = array(); // Validate input from various stages... switch ( $stage ) { case 1: if ( isset( $_POST ) ) { $valid_fields = array( 'db_name', 'db_host', 'db_user', 'db_pass', 'db_prefix', 'import_comments' ); $inputs = array_intersect_key( $_POST->getArrayCopy(), array_flip( $valid_fields ) ); if ( $drupaldb = $this->drupal_connect( $inputs['db_host'], $inputs['db_name'], $inputs['db_user'], $inputs['db_pass'], $inputs['db_prefix'] ) ) { $has_node_type = count( $drupaldb->get_results( "SHOW TABLES LIKE '{$inputs['db_prefix']}node_type'" ) ); if ( $has_node_type ) { $stage = 2; } else { $inputs['warning'] = _t( 'Specified database does not appear to be a Drupal 6.x database. Please enter connection values for a Drupal 6.x database.' ); } } else { $inputs['warning'] = _t( 'Could not connect to the Drupal database using the values supplied. Please correct them and try again.' ); } } break; case 2: if ( isset( $_POST ) ) { $valid_fields = array( 'db_name', 'db_host', 'db_user', 'db_pass', 'db_prefix', 'import_comments', 'entry_type', 'page_type', 'tag_vocab' ); $inputs = array_intersect_key( $_POST->getArrayCopy(), array_flip( $valid_fields ) ); // We could re-do the Drupal types/vocab lookup... is that really necessary? $stage = 3; } break; } // Based on the stage of the import we're on, do different things... switch ( $stage ) { case 1: default: $output = $this->stage1( $inputs ); break; case 2: $output = $this->stage2( $inputs ); break; case 3: $output = $this->stage3( $inputs ); } return $output; } /** * Create the UI for stage one of the Drupal import process * * @param array $inputs Inputs received via $_POST to the importer * @return string The UI for the first stage of the import process */ private function stage1($inputs) { $default_values = array( 'db_name' => '', 'db_host' => 'localhost', 'db_user' => '', 'db_pass' => '', 'db_prefix' => '', 'import_comments' => 1, 'warning' => '' ); $inputs = array_merge( $default_values, $inputs ); extract( $inputs ); if ( $warning != '' ) { $warning = "<p class=\"warning\">{$warning}</p>"; } $import_comments_checked = $import_comments ? ' checked="checked"' : ''; $output = <<< DRUPAL_IMPORT_STAGE1 <p>Habari will attempt to import from a Drupal 6.x Database.</p> {$warning} <p>Please provide the connection details for an existing Drupal 6.x database:</p> <table> <tr><td>Database Name</td><td><input type="text" name="db_name" value="{$db_name}"></td></tr> <tr><td>Database Host</td><td><input type="text" name="db_host" value="{$db_host}"></td></tr> <tr><td>Database User</td><td><input type="text" name="db_user" value="{$db_user}"></td></tr> <tr><td>Database Password</td><td><input type="password" name="db_pass" value="{$db_pass}"></td></tr> <tr><td>Table Prefix</td><td><input type="text" name="db_prefix" value="{$db_prefix}"></td></tr> </table> <input type="hidden" name="stage" value="1"> <p class="extras" style="border: solid 1px #ccc; padding: 5px;"> Extras - additional data from Drupal modules <table> <tr> <td>Import comments</td> <td><input type="checkbox" name="import_comments" value="1"{$import_comments_checked}></td> </tr> </table> </p> <p class="submit"><input type="submit" name="import" value="Import" /></p> DRUPAL_IMPORT_STAGE1; return $output; } /** * Create UI to prompt user to map Drupal content types to Habari standard * types. * * @param array $inputs Inputs received via $_POST to the importer. * @return string The UI for the second stage of the import process. */ private function stage2($inputs) { $default_values = array( 'entry_type' => 'blog', 'page_type' => 'page', 'tag_vocab' => 0, 'warning' => '' ); $inputs = array_merge( $default_values, $inputs ); extract( $inputs ); if ( $warning != '' ) { $warning = "<p class=\"warning\">{$warning}</p>"; } $drupaldb = $this->drupal_connect( $db_host, $db_name, $db_user, $db_pass, $db_prefix ); // Retrieve lists of Drupal content types and vocabularies. $drupal_types = $drupaldb->get_results( "SELECT type,name FROM {$db_prefix}node_type" ); $drupal_vocabs = $drupaldb->get_results( "SELECT vid,name FROM {$db_prefix}vocabulary" ); $entry_options = $page_options = '<option value="">None</option>'; $vocab_options = '<option value="0">Do not import tags</option>'; foreach ( $drupal_types as $type ) { $entry_options .= "\n" . '<option value="' . $type->type . '"' . ($entry_type == $type->type ? ' selected="selected" ' : '') . '>' . $type->name . '</option>'; $page_options .= "\n" . '<option value="' . $type->type . '"' . ($page_type == $type->type ? ' selected="selected" ' : '') . '>' . $type->name . '</option>'; } foreach ( $drupal_vocabs as $vocab ) { $vocab_options .= "\n" . '<option value="' . $vocab->vid . '"' . ($tag_vocab == $vocab->vid ? ' selected="selected" ' : '') . '>' . $vocab->name . '</option>'; } $output = <<< DRUPAL_IMPORT_STAGE2 <p>Habari will attempt to import from a Drupal 6.x Database.</p> {$warning} <p>Select the content types to import as entries and pages, and the vocabulary to import as tags:</p> <table> <tr><td>Entry Content Type</td><td><select name="entry_type">{$entry_options}</select></td></tr> <tr><td>Page Content Type</td><td><select name="page_type">{$page_options}</select></td></tr> <tr><td>Tag Vocabulary</td><td><select name="tag_vocab" >{$vocab_options}</td></tr> </table> <input type="hidden" name="stage" value="2"> <input type="hidden" name="db_host" value="{$db_host}"> <input type="hidden" name="db_name" value="{$db_name}"> <input type="hidden" name="db_user" value="{$db_user}"> <input type="hidden" name="db_pass" value="{$db_pass}"> <input type="hidden" name="db_prefix" value="{$db_prefix}"> <input type="hidden" name="import_comments" value="{$import_comments}"> <p class="submit"><input type="submit" name="import" value="Import" /></p> DRUPAL_IMPORT_STAGE2; return $output; } /** * Create the UI for stage two of the Drupal import process * This stage kicks off the ajax import. * * @param array $inputs Inputs received via $_POST to the importer * @return string The UI for the third stage of the import process */ private function stage3($inputs) { extract( $inputs ); $ajax_url = URL::get( 'auth_ajax', array( 'context' => 'drupal_import_users' ) ); EventLog::log( sprintf( _t( 'Starting import from "%s"' ), $db_name ) ); Options::set( 'import_errors', array() ); $output = <<< DRUPAL_IMPORT_STAGE3 <p>Import In Progress</p> <div id="import_progress">Starting Import...</div> <script type="text/javascript"> // A lot of ajax stuff goes here. $( document ).ready( function(){ $( '#import_progress' ).load( "{$ajax_url}", { db_host: "{$db_host}", db_name: "{$db_name}", db_user: "{$db_user}", db_pass: "{$db_pass}", db_prefix: "{$db_prefix}", import_comments: "{$import_comments}", entry_type: "{$entry_type}", page_type: "{$page_type}", tag_vocab: "{$tag_vocab}", postindex: 0 } ); } ); </script> DRUPAL_IMPORT_STAGE3; return $output; } /** * Attempt to connect to the Drupal database * * @param string $db_host The hostname of the Drupal database * @param string $db_name The name of the Drupal database * @param string $db_user The user of the Drupal database * @param string $db_pass The user's password for the Drupal database * @param string $db_prefix The table prefix for the Drupal instance in the database * @return mixed false on failure, DatabseConnection on success */ private function drupal_connect($db_host, $db_name, $db_user, $db_pass, $db_prefix) { // Connect to the database or return false try { $drupaldb = new DatabaseConnection( ); $drupaldb->connect( "mysql:host={$db_host};dbname={$db_name}", $db_user, $db_pass, $db_prefix ); return $drupaldb; } catch ( Exception $e ) { return false; } } /** * The plugin sink for the auth_ajax_drupal_import_posts hook. * Responds via authenticated ajax to requests for post importing. * * @param AjaxHandler $handler The handler that handled the request, contains $_POST info */ public function action_auth_ajax_drupal_import_posts($handler) { $valid_fields = array( 'db_name', 'db_host', 'db_user', 'db_pass', 'db_prefix', 'import_comments', 'postindex', 'entry_type', 'page_type', 'tag_vocab' ); $inputs = array_intersect_key( $_POST->getArrayCopy(), array_flip( $valid_fields ) ); extract( $inputs ); $drupaldb = $this->drupal_connect( $db_host, $db_name, $db_user, $db_pass, $db_prefix ); if ( $drupaldb ) { $postcount = $drupaldb->get_value( "SELECT count( nid ) FROM {$db_prefix}node WHERE type IN ( '{$entry_type}', '{$page_type}' );" ); $min = $postindex * DRUPAL_IMPORT_BATCH + ($postindex == 0 ? 0 : 1); $max = min( ($postindex + 1) * DRUPAL_IMPORT_BATCH, $postcount ); $user_map = array(); $userinfo = DB::table( 'userinfo' ); $user_info = DB::get_results( "SELECT user_id, value FROM {$userinfo} WHERE name= 'drupal_uid';" ); foreach ( $user_info as $info ) { $user_map[$info->value] = $info->user_id; } echo "<p>Importing posts {$min}-{$max} of {$postcount}.</p>"; $posts = $drupaldb->get_results( " SELECT n.nid, nr.body as content, n.title, n.uid as user_id, FROM_UNIXTIME( n.created ) as pubdate, FROM_UNIXTIME( n.changed ) as updated, n.status as post_status, n.type as post_type FROM {$db_prefix}node AS n INNER JOIN {$db_prefix}node_revisions AS nr ON (nr.vid = n.vid) ORDER BY n.nid DESC LIMIT {$min}, " . DRUPAL_IMPORT_BATCH, array(), 'Post' ); $post_map = DB::get_column( "SELECT value FROM {postinfo} WHERE name='drupal_nid';" ); foreach ( $posts as $post ) { if ( in_array( $post->nid, $post_map ) ) { continue; } if ( $tag_vocab ) { $tags = $drupaldb->get_column( "SELECT DISTINCT td.name FROM {$db_prefix}term_node AS tn INNER JOIN {$db_prefix}term_data AS td ON (td.tid = tn.tid AND td.vid = {$tag_vocab}) WHERE tn.nid = {$post->nid}" ); } else { $tags = array(); } $post->content = MultiByte::convert_encoding( $post->content ); $post->title = MultiByte::convert_encoding( $post->title ); $post_array = $post->to_array(); switch ( $post_array['post_status'] ) { case '1': $post_array['status'] = Post::status( 'published' ); break; default: $post_array['status'] = Post::status( 'draft' ); break; } unset( $post_array['post_status'] ); switch ( $post_array['post_type'] ) { case $entry_type: $post_array['content_type'] = Post::type( 'entry' ); break; case $page_type: $post_array['content_type'] = Post::type( 'page' ); break; } unset( $post_array['post_type'] ); $post_array['content'] = preg_replace( '/<!--\s*break\s*-->/', '<!--more-->', $post_array['content'] ); $p = new Post( $post_array ); $p->id = null; $p->user_id = $user_map[$p->user_id]; $p->tags = $tags; $p->info->drupal_nid = $post_array['nid']; // Store the Drupal post id in the post_info table for later $p->exclude_fields( array( 'nid' ) ); try { $p->insert(); } catch ( Exception $e ) { EventLog::log( $e->getMessage(), 'err', null, null, print_r( array( $p, $e ), 1 ) ); $errors = Options::get( 'import_errors' ); $errors[] = $p->title . ' : ' . $e->getMessage(); Options::set( 'import_errors', $errors ); } } if ( $max < $postcount ) { $ajax_url = URL::get( 'auth_ajax', array( 'context' => 'drupal_import_posts' ) ); $postindex ++; echo <<< DRUPAL_IMPORT_AJAX1 <script type="text/javascript"> $( '#import_progress' ).load( "{$ajax_url}", { db_host: "{$db_host}", db_name: "{$db_name}", db_user: "{$db_user}", db_pass: "{$<PASSWORD>}", db_prefix: "{$db_prefix}", import_comments: "{$import_comments}", entry_type: "{$entry_type}", page_type: "{$page_type}", tag_vocab: "{$tag_vocab}", postindex: {$postindex} } ); </script> DRUPAL_IMPORT_AJAX1; } else { $ajax_url = URL::get( 'auth_ajax', array( 'context' => 'drupal_import_comments' ) ); echo <<< DRUPAL_IMPORT_AJAX2 <script type="text/javascript"> $( '#import_progress' ).load( "{$ajax_url}", { db_host: "{$db_host}", db_name: "{$db_name}", db_user: "{$db_user}", db_pass: "{$<PASSWORD>}", db_prefix: "{$db_prefix}", import_comments: "{$import_comments}", entry_type: "{$entry_type}", page_type: "{$page_type}", tag_vocab: "{$tag_vocab}", commentindex: 0 } ); </script> DRUPAL_IMPORT_AJAX2; } } else { EventLog::log( sprintf( _t( 'Failed to import from "%s"' ), $db_name ), 'crit' ); echo '<p>' . _t( 'The database connection details have failed to connect.' ) . '</p>'; } } /** * The plugin sink for the auth_ajax_drupal_import_posts hook. * Responds via authenticated ajax to requests for post importing. * * @param mixed $handler * @return */ public function action_auth_ajax_drupal_import_users($handler) { $valid_fields = array( 'db_name', 'db_host', 'db_user', 'db_pass', 'db_prefix', 'import_comments', 'userindex', 'entry_type', 'page_type', 'tag_vocab' ); $inputs = array_intersect_key( $_POST->getArrayCopy(), array_flip( $valid_fields ) ); extract( $inputs ); $drupaldb = $this->drupal_connect( $db_host, $db_name, $db_user, $db_pass, $db_prefix ); if ( $drupaldb ) { $drupal_users = $drupaldb->get_results( " SELECT uid, name as username, pass as <PASSWORD>, mail as email FROM {$db_prefix}users WHERE uid > 0 ", array(), 'User' ); $usercount = 0; _e( '<p>Importing users...</p>' ); foreach ( $drupal_users as $user ) { $habari_user = User::get_by_name( $user->username ); // If username exists if ( $habari_user instanceof User ) { $habari_user->info->drupal_uid = $user->uid; $habari_user->update(); } else { try { $user->info->drupal_uid = $user->uid; // This should probably remain commented until we implement ACL more, // or any imported user will be able to log in and edit stuff //$user->password = <PASSWORD>}' . $<PASSWORD>; $user->exclude_fields( array( 'uid', 'drupal_uid' ) ); $user->insert(); $usercount ++; } catch ( Exception $e ) { EventLog::log( $e->getMessage(), 'err', null, null, print_r( array( $user, $e ), 1 ) ); $errors = Options::get( 'import_errors' ); $errors[] = $user->username . ' : ' . $e->getMessage(); Options::set( 'import_errors', $errors ); } } } $ajax_url = URL::get( 'auth_ajax', array( 'context' => 'drupal_import_posts' ) ); echo <<< DRUPAL_IMPORT_USERS1 <script type="text/javascript"> // A lot of ajax stuff goes here. $( document ).ready( function(){ $( '#import_progress' ).load( "{$ajax_url}", { db_host: "{$db_host}", db_name: "{$db_name}", db_user: "{$db_user}", db_pass: "{$db_pass}", db_prefix: "{$db_prefix}", import_comments: "{$import_comments}", entry_type: "{$entry_type}", page_type: "{$page_type}", tag_vocab: "{$tag_vocab}", postindex: 0 } ); } ); </script> DRUPAL_IMPORT_USERS1; } else { EventLog::log( sprintf( _t( 'Failed to import from "%s"' ), $db_name ), 'crit' ); echo '<p>' . _t( 'Failed to connect using the given database connection details.' ) . '</p>'; } } /** * The plugin sink for the auth_ajax_drupal_import_comments hook. * Responds via authenticated ajax to requests for comment importing. * * @param AjaxHandler $handler The handler that handled the request, contains $_POST info */ public function action_auth_ajax_drupal_import_comments($handler) { $valid_fields = array( 'db_name', 'db_host', 'db_user', 'db_pass', 'db_prefix', 'import_comments', 'commentindex', 'entry_type', 'page_type', 'tag_vocab' ); $inputs = array_intersect_key( $_POST->getArrayCopy(), array_flip( $valid_fields ) ); extract( $inputs ); $drupaldb = $this->drupal_connect( $db_host, $db_name, $db_user, $db_pass, $db_prefix ); if ( $drupaldb ) { $commentcount = $drupaldb->get_value( "SELECT count( c.cid ) FROM {$db_prefix}comments AS c INNER JOIN {$db_prefix}node AS n ON (n.nid = c.nid) WHERE n.type IN ('{$entry_type}', '{$page_type}')" ); $min = $commentindex * DRUPAL_IMPORT_BATCH + 1; $max = min( ($commentindex + 1) * DRUPAL_IMPORT_BATCH, $commentcount ); echo "<p>Importing comments {$min}-{$max} of {$commentcount}.</p>"; $postinfo = DB::table( 'postinfo' ); $post_info = DB::get_results( "SELECT post_id, value FROM {$postinfo} WHERE name= 'drupal_nid';" ); foreach ( $post_info as $info ) { $post_map[$info->value] = $info->post_id; } if ( $import_comments ) { $comments = $drupaldb->get_results( " SELECT c.nid as drupal_post_nid, c.comment as content, c.name, c.mail as email, c.homepage as url, INET_ATON( c.hostname ) as ip, c.status, FROM_UNIXTIME( c.timestamp ) as date FROM {$db_prefix}comments AS c INNER JOIN {$db_prefix}node AS n on ( n.nid = c.nid ) LIMIT {$min}, " . DRUPAL_IMPORT_BATCH, array(), 'Comment' ); } else { $comments = array(); } foreach ( $comments as $comment ) { $comment->type = Comment::COMMENT; $comment->status = $comment->status == '0' ? 1 : 0; $comment->content = MultiByte::convert_encoding( $comment->content ); $comment->name = MultiByte::convert_encoding( $comment->name ); $carray = $comment->to_array(); if ( $carray['ip'] == '' ) { $carray['ip'] = 0; } if ( ! isset( $post_map[$carray['drupal_post_nid']] ) ) { Utils::debug( $carray ); } else { $carray['post_id'] = $post_map[$carray['drupal_post_nid']]; unset( $carray['drupal_post_nid'] ); $c = new Comment( $carray ); //Utils::debug( $c ); try { $c->insert(); } catch ( Exception $e ) { EventLog::log( $e->getMessage(), 'err', null, null, print_r( array( $c, $e ), 1 ) ); $errors = Options::get( 'import_errors' ); $errors[] = $e->getMessage(); Options::set( 'import_errors', $errors ); } } } if ( $max < $commentcount ) { $ajax_url = URL::get( 'auth_ajax', array( 'context' => 'drupal_import_comments' ) ); $commentindex ++; echo <<< DRUPAL_IMPORT_AJAX1 <script type="text/javascript"> $( '#import_progress' ).load( "{$ajax_url}", { db_host: "{$db_host}", db_name: "{$db_name}", db_user: "{$db_user}", db_pass: "{<PASSWORD>}", db_prefix: "{$db_prefix}", import_comments: "{$import_comments}", entry_type: "{$entry_type}", page_type: "{$page_type}", tag_vocab: "{$tag_vocab}", commentindex: {$commentindex} } ); </script> DRUPAL_IMPORT_AJAX1; } else { EventLog::log( 'Import complete from "' . $db_name . '"' ); echo '<p>' . _t( 'Import is complete.' ) . '</p>'; $errors = Options::get( 'import_errors' ); if ( count( $errors ) > 0 ) { echo '<p>' . _t( 'There were errors during import:' ) . '</p>'; echo '<ul>'; foreach ( $errors as $error ) { echo '<li>' . $error . '</li>'; } echo '</ul>'; } } } else { EventLog::log( sprintf( _t( 'Failed to import from "%s"' ), $db_name ), 'crit' ); echo '<p>' . _t( 'Failed to connect using the given database connection details.' ) . '</p>'; } } } ?> <file_sep><? /** * Quick and dirty Google Analytics interface * */ class Google_Analytics { // URLs that we use const login_url = 'https://www.google.com/accounts/ClientLogin'; const accounts_url = 'https://www.google.com/analytics/feeds/accounts/default'; const reports_url = 'https://www.google.com/analytics/feeds/data'; const dxp_ns = 'http://schemas.google.com/analytics/2009'; private $auth = null; private $startDate; private $stopDate; private $profile; /** * Constructor * * Set up authentication with Google and get $auth token * * @param string $email Email/Userid for GA login * @param string $password <PASSWORD> for GA login * @return GoogleAnalytics */ public function __construct( $email, $password ) { $this->authenticate( $email, $password ); } /** * Authenticate Google Account * * @param string $email Email/Userid for login * @param string $password <PASSWORD> for login */ private function authenticate( $email, $password ) { $post = array( 'accountType' => 'GOOGLE', 'Email' => $email, 'Passwd' => $<PASSWORD>, 'service' => 'analytics' ); $response = $this->request( self::login_url, $post ); parse_str( str_replace( array( "\n", "\r\n" ), '&', $response ), $auth ); if ( ! is_array( $auth ) || empty( $auth['Auth'] ) ) { // How are we supposed to throw errors with habari? throw new Exception( 'GoogleAnalytics::Authentication Error: "' . strip_tags( $response->get_response_body() ) . '"' ); } $this->auth = $auth['Auth']; } /** * Return the authentication token * * @return array */ private function auth_header() { return array( 'Authorization: GoogleLogin auth=' . $this->auth ); } /** * Set Profile ID (Example: ga:12345) * * @param string $id ID of profile to use **/ public function set_profile( $id ) { $this->profile = $id; } /** * Sets the date range for Analytics data. * * @param string $startDate (YYYY-MM-DD) * @param string $stopDate (YYYY-MM-DD) */ public function set_date_range( $startDate, $stopDate ) { $this->startDate = $startDate; $this->stopDate = $stopDate; } /** * Return a list of all profiles for the logged in account * * @return array **/ function get_profiles() { $response = $this->request( self::accounts_url, null, null, $this->auth_header() ); $xml = simplexml_load_string( $response ); $entries = $xml->entry; $profiles = array(); foreach ( $entries as $entry ) { $tmp = array(); $tmp['title'] = (string) $entry->title; $tmp['entryid'] = (string) $entry->id; $properties = $entry->children( self::dxp_ns ); $tmp['tableid'] = (string) $properties->tableId; $tmp['accountId'] = (string) $properties->accountId; $tmp['accountName'] = (string) $properties->accountName; $tmp['profileId'] = (string) $properties->profileId; $tmp['webPropertyId'] = (string) $properties->webPropertyId; $profiles[] = $tmp; } // We only want to return the profile => display $ret = array(); foreach ( $profiles as $profile ) { $ret[$profile['tableid']] = $profile['title']; } return $ret; } /** * Parse Google Analytics XML to an array ( dimension => metric ) * Check http://code.google.com/intl/nl/apis/analytics/docs/gdata/gdataReferenceDimensionsMetrics.html * for dimension and metrics * * @param array $dimensions Dimensions to use * @param array $metrics Metrics to use * @param array $sort OPTIONAL: Dimension or dimensions to sort by * @param string $startDate OPTIONAL: Start of report period * @param string $stopDate OPTIONAL: Stop of report period * * @return array results */ public function getData( $dimensions, $metrics, $sort = null, $startDate = null, $stopDate = null ) { $parameters = array( 'ids' => $this->profile ); if ( is_array( $dimensions ) ) { $dimensions_string = ''; foreach ( $dimensions as $dimension ) { $dimensions_string .= ',' . $dimension; } $parameters['dimensions'] = substr( $dimensions_string, 1 ); } else { $parameters['dimensions'] = $dimensions; } if ( is_array( $metrics ) ) { $metrics_string = ''; foreach ( $metrics as $metric ) { $metrics_string .= ',' . $metric; } $parameters['metrics'] = substr( $metrics_string, 1 ); } else { $parameters['metrics'] = $metrics; } if ( $sort == null && isset( $parameters['metrics'] ) ) { $parameters['sort'] = $parameters['metrics']; } elseif ( is_array( $sort ) ) { $sort_string = ''; foreach ( $sort as $s ) { $sort_string .= ',' . $s; } $parameters['sort'] = substr( $sort_string, 1 ); } else { $parameters['sort'] = $sort; } if ( $startDate == null ) { $startDate = date( 'Y-m-d', strtotime( '1 month ago' ) ); } $parameters['start-date'] = $startDate; if ( $stopDate == null ) { $stopDate = date( 'Y-m-d' ); } $parameters['end-date'] = $stopDate; $request = $this->request( self::reports_url, null, $parameters, $this->auth_header() ); $xml = simplexml_load_string( $request ); $result = array(); $entries = $xml->entry; foreach ( $entries as $entry ) { $title = $entry->title; $dxp = $entry->children( self::dxp_ns ); $d_dimension = $dxp->dimension->attributes(); $d_metric = $dxp->metric->attributes(); // Multiple dimensions given? // @todo double check this. I'm not sure if it's going to work right or not. if ( strpos( $title, '|' ) !== false && strpos( $parameters['dimensions'], ',' ) !== false ) { $tmp = explode(',', $parameters['dimensions'] ); $tmp[] = '|'; $tmp[] = '='; $title = preg_replace( '/\s\s+/', ' ', trim( str_replace( $tmp, '', $title ) ) ); } $title = str_replace( $parameters['dimensions'] . '=', '', $title ); $result[$title] = (int) $d_metric->value; } return $result; } /** * Wrapper for Habari's RemoteRequest call * * @param string $url URL to call * @param array $get GET Variables * @param array $post POST Variables * @param array $headers HEADER Variables * @return array **/ private function request( $url, $post = null, $get = null, $headers = null ) { if ( is_array( $post ) ) { $response = new RemoteRequest( $url, 'POST' ); $response->set_postdata( $post ); } else { $response = new RemoteRequest( $url, 'GET' ); if ( is_array( $get ) ) { $response->set_params( $get ); } } if ( is_array( $headers ) ) { $response->add_headers( $headers ); } if ( $response->execute() ) { return $response->get_response_body(); } else { return false; } } } // GoogleAnalytics ?><file_sep><?php class IEAdmin extends Plugin { const JS_VERSION = '2.1(beta4)'; // to be updated as this changes. public function info() { return array( 'name' => 'IE_Admin', 'version' => '1.0', 'url' => 'http://habariproject.org/', 'author' => 'The Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Adds the <a href="http://code.google.com/p/ie7-js/">ie7-js</a> stylesheet to the Habari Admin.', ); } public function action_update_check() { Update::add( $this->info->name, $this->info->guid, $this->info->version ); } public function configure() { $ui = new FormUI( 'ieadmin' ); $ver = $ui->append( 'text', 'ieversion', 'ieadmin__ieversion', _t( 'IE version to be compatible with (e.g. 8)', 'ieadmin' ) ); $ver->add_validator( 'validate_regex', '/^[7-9]*$/', _t( 'Please enter a valid version number between 7-9.', 'ieadmin' ) ); $ui->append( 'text', 'jsversion','ieadmin__jsversion', _t( 'Script version, if not using "' . self::JS_VERSION . '"', 'isadmin' ) ); $ui->append( 'submit', 'save', 'save' ); return $ui; } public function action_admin_header_after( $theme ) { $i_v = ( Options::get( 'ieadmin__ieversion' ) ? Options::get( 'ieadmin__ieversion' ) : 7 ); $j_v = ( Options::get( 'ieadmin__jsversion' ) ? Options::get( 'ieadmin__jsversion' ) : self::JS_VERSION ); echo "<!--[if lt IE $i_v]>\n\t<script src=\"http://ie7-js.googlecode.com/svn/version/$j_v/IE$i_v.js\"></script>\n\t<![endif]-->"; } } ?> <file_sep><?php class prettyPrettyAdmin extends Plugin { /** * Removes system admin stylesheet from all admin headers, replaces it with the one from this plugin. * */ public function action_admin_header( $theme ) { Stack::remove('admin_stylesheet', 'admin'); Stack::add('admin_stylesheet', array($this->get_url(true) . 'admin.css', 'screen')); } } ?> <file_sep><table class="calendar" summary="calendar"> <caption> <a href="<?php echo $prev_month_url; ?>">&laquo;</a> <?php echo $year . ' / ' . $month; ?> <a href="<?php echo $next_month_url; ?>">&raquo;</a> </caption> <?php for ($week = 0; $week < count($calendar); $week++): ?> <?php if ($week == 0): ?> <tr> <?php for ($wday = 0; $wday < count($calendar[$week]); $wday++): ?> <th class="<?php echo strtolower($calendar[$week][$wday]['label']); ?>"><?php echo $calendar[$week][$wday]['label']; ?></th> <?php endfor; ?> </tr> <?php else: ?> <tr> <?php for ($wday = 0; $wday < count($calendar[$week]); $wday++): ?> <?php if (isset($calendar[$week][$wday]['url'])): ?> <td><a href="<?php echo $calendar[$week][$wday]['url']; ?>"><?php echo $calendar[$week][$wday]['label']; ?></a></td> <?php else: ?> <td><?php echo $calendar[$week][$wday]['label']; ?></td> <?php endif; ?> <?php endfor; ?> </tr> <?php endif; ?> <?php endfor; ?> </table> <file_sep><?php /** * Fresh Surf * A plugin to show your most recent del.icio.us posts */ /* Use in theme: <ul> <?php foreach ( $delicious->post as $item ): ?> <li><a href="<?php echo $item['href']; ?>"><?php echo $item['description']; ?></a></li> <?php endforeach; ?> </ul> */ class FreshSurf extends Plugin{ const BASE_URL = 'api.del.icio.us/v1/'; /** * Required Plugin Information */ public function info() { return array('name' => 'Fresh Surf', 'version' => '0.1', 'url' => 'http://habariproject.org', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Recent del.icio.us posts', 'copyright' => '2008' ); } /** * Add actions to the plugin page for this plugin * * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id */ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = 'Configure'; } return $actions; } /** * Respond to the user selecting an action on the plugin page * * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook */ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case 'Configure' : $ui = new FormUI(strtolower(get_class( $this ) ) ); $delicious_username = $ui->append('text', 'username', 'freshsurf__username', 'del.icio.us Username:' ); $delicious_password = $ui->append('password', '<PASSWORD>', '<PASSWORD>', 'del.icio.us Password:' ); $delicious_count = $ui->append('text', 'count', 'freshsurf__count', 'number of posts to show' ); $ui->append( 'submit', 'save', _t('Save' ) ); $ui->out(); break; } } } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'FreshSurf', '6ecc8310-3bbc-11dd-ae16-0800200c9a66', $this->info->version ); } function action_add_template_vars( $theme ) { $username = Options::get( 'freshsurf__username' ); $password = Options::get( '<PASSWORD>' ); $count = Options::get( 'freshsurf__count' ); if( $username != '' && $password != '' ) { if(Cache::has( 'freshsurf__' . $username ) ) { $response = Cache::get( 'freshsurf__' . $username ); } else { $request = new RemoteRequest("https://{$username}:{$password}@" . self::BASE_URL . "posts/recent?count={$count}", 'GET', 20 ); $request->execute(); $response = $request->get_response_body(); Cache::set( 'freshsurf__' . $username, $response); } $delicious = @simplexml_load_string( $response ); if( $delicious instanceof SimpleXMLElement ) { $theme->delicious = $delicious; } else { $theme->delicious = @simplexml_load_string('<posts><post href="#" description="Could not load feed from delicious. Is username/password correct?"/></posts>' ); Cache::expire( 'freshsurf__' . $username ); } } else { $theme->delicious = @simplexml_load_string('<posts></posts>' ); } } } ?> <file_sep><?php /** * * */ class textlinkads extends Plugin { public function info() { return array( 'name' => 'Text Link Ads', 'version' => '1.0', 'url' => 'http://redalt.com/plugins/textlinkads', 'author' => '<NAME>', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Display Text Link Ads as a block in your theme', 'copyright' => '2009' ); } public function filter_block_list($block_list) { $block_list['textlinkads'] = _t('Text Link Ads'); return $block_list; } public function action_block_content_textlinkads($block) { if(!Cache::has('textlinkads')) { $request_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''; $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ''; $inventory_key = '<KEY>'; $tla_uri = 'http://www.text-link-ads.com/xml.php?inventory_key=' . $inventory_key . '&referer=' . urlencode($request_uri) . '&user_agent=' . urlencode($user_agent); Cache::set('textlinkads', RemoteRequest::get_contents($tla_uri)); Utils::debug('Cache set'); } $xml = new SimpleXMLElement(Cache::get('textlinkads')); $links = array(); foreach($xml->Link as $link) { $ad = new StdClass(); $ad->before = (string) $link->BeforeText; $ad->after = (string) $link->AfterText; $ad->text = (string) $link->Text; $ad->url = (string) $link->URL; $links[(string) $link->LinkID] = $ad; } $block->links = $links; } public function action_init() { $this->add_template('block.textlinkads', dirname(__FILE__) . '/block.textlinkads.php'); } } ?><file_sep><?php class Loupable extends Plugin { function info() { return array( 'name' => 'Loupable', 'version' => '1.0', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Allows you to insert an interactive loupe navigation on the front-end of your site', ); } public function action_init() { $this->add_template('loupe.public', dirname(__FILE__) . '/loupe.public.php'); } public function action_init_theme() { Stack::add( 'template_stylesheet', array( URL::get_from_filesystem(__FILE__) . '/loupable.css', 'screen' ), 'loupable' ); Stack::add( 'template_header_javascript', Site::get_url('scripts') . '/jquery.js', 'jquery' ); Stack::add( 'template_header_javascript', URL::get_from_filesystem(__FILE__) . '/loupable.js', 'loupable' ); } public function action_add_template_vars($theme, $handler_vars) { $items = array(); if(isset($theme->request->display_home) && $theme->request->display_home) { $posts = Posts::get(array('content_type' => Post::type('entry'), 'status' => Post::status('published'), 'nolimit' => true, 'orderby' => 'pubdate ASC')); foreach($posts as $post) { $item = array(); $item['url'] = $post->permalink; $item['title'] = $post->title; $item['time'] = strtotime($post->pubdate); $items[] = $item; } } $theme->timeline_items = $items; } } ?><file_sep></div> <!-- sidebar --> <?php Plugins::act( 'theme_sidebar_top' ); ?> <div id="sidebar"> <!-- searchform --> <h2><label for="s"><?php _e('Search:'); ?></label></h2> <ul> <li> <?php Plugins::act( 'theme_searchform_before' ); ?> <form id="searchform" method="get" action="<?php URL::out( 'display_search' ); ?>"> <p><input type="text" name="criteria" id="s" size="15"></p> <p><input type="submit" name="submit" value="<?php _e('Search'); ?>"></p> </form> <?php Plugins::act( 'theme_searchform_after' ); ?> </li> </ul> <!-- /searchform --> <?php if ( count( $pages ) != 0 ): ?> <h2><?php _e('Pages:'); ?></h2> <ul> <?php foreach ( $pages as $page ) { echo "<li><a href=\"{$page->permalink}\" title=\"{$page->title}\">{$page->title}</a></li>"; } ?> </ul> <?php endif; if ( $tags ): ?> <h2><?php _e('Tags'); ?></h2> <ul> <?php foreach ( $tags as $tag ) { $tag_count = Posts::count_by_tag( $tag->tag, 'published' ); echo "<li><a href=\"" . URL::get( 'display_entries_by_tag', 'tag=' . $tag->slug ) . "\">{$tag->tag}</a></li>"; } ?> </ul> <?php endif; ?> <h2><?php _e('Meta'); ?></h2> <ul> <?php if ( $loggedin ): ?> <li><a href="<?php Site::out_url( 'admin' ); ?>" title="Admin area">Site Admin</a></li> <?php else: ?> <li><a href="<?php URL::out( 'user', array( 'page' => 'login' ) ); ?>" title="login">Login</a></li> <?php endif; ?> <li><a href="http://habariproject.org/" title="<?php _e('Powered by Habari'); ?>">Habari</a></li> <li><a title="Atom Feed for Posts" href="<?php URL::out( 'atom_feed', array( 'index' => '1' ) ); ?>">Posts Feed</a> </li> <li><a title="Atom Feed for Comments" href="<?php URL::out( 'atom_feed_comments' ); ?>">Comments Feed</a></li> </ul> <?php $theme->area( 'sidebar' ); ?> </div> <!-- #sidebar --> <?php Plugins::act( 'theme_sidebar_bottom' ); ?> <!-- /sidebar --> <file_sep><?php if (!empty($blogs)) { ?> <li id="widget-blogroll" class="widget"> <h3><?php echo $blogroll_title; ?></h3> <ul> <?php foreach ($blogs as $blog) { printf('<li class="vcard"><a href="%1$s" class="url" title="%2$s" rel="%3$s %4$s">%5$s</a></li>', $blog->info->url, $blog->content, $blog->info->relationship, $blog->xfn_relationships, $blog->title); } ?> </ul> </li> <?php } ?> <file_sep>Plugin: Meta SEO URL: http://habariproject.org Version: 0.5 Author: <NAME> Purpose Meta SEO performs several search engine optimization tasks for you. It will: 1.Generate a description meta tag and inject it into the head of a page. Descriptions are created for your home page, individual post pages, and static pages. For your home page, it will use the description you entered on the plugin's configuration page. For entry and static pages, it adds the option to create a description on the publish page. If you enter your own description, this will be used to create the description meta tag. If you don't the first part of the post will be used to create the tag. 2. Generate a keywords meta tag and inject it into the head of a page. For the home page, it will use the tags you have selected in the plugin configuration. For entries and static pages, it adds the option to the publish page to create your own keywords. If you do so, it will use this to generate the tag. If you don't, it will use the tags you tagged the post with. For tag archives, it will use the archive's tag. 3. Generate a title more suitable for search engines than the standard blog title. For individual post and static pages, it will add the option to the publish page to enter your own title. If you do so, that title will be used to create the html title for the page. If you don't, the title of the entry will be used to generate the html title for the page. Archive and search pages will receive a title appropriate to the type of archive or the search performed. 4. Generate a robots meta tag. Duplicate content can lead to lower search engine rankings. The robots tag tells search engines whether or not to index a page, and whether to follow links on the page. By default, Meta SEO has all links followed, but only your home page and individual post and static pages indexed. Requirements The theme must call $theme->header() in its head template. Installation 1. Copy the plugin directory into your user/plugins directory or the site's plugins directory. 2. Go to the plugins page of your Habari admin panel. 3. Click on the Activate button for Meta SEO. Usage If your theme, usually in the header template, contains a description, keywords, or robots meta tag, back up the template that contains them, then delete them from your working copy of the template. Configuration for Meta SEO is performed by clicking the Configure button in its listing on your plugins page. The configuration screen has two main sections - the home page options, and the robots tag options. 1. Home Page - Use the configuration screen to set the description and keywords you wish to use for your home page. These default to your blog's tagline and the first 50 tags you have in your blog. 2. Robots Tag - Meta SEO sees your site as having four main types of pages: the home page, individual posts and static pages, archive pages, and other pages such as search results and the 404 page. The robots tag for the other pages is always set to not index the page, but to follow the links on the page. Use the configuration screen to tell Meta SEO how to create the robots tag for the first three type of pages. If the Index checkbox is marked, the robots tag will contain 'index'. Otherwise, it will contain 'noindex'. If the Follow checkbox is marked, the robots tag will contain 'follow'. Otherwise, it will contain 'nofollow'. 3. After you're done making your configuration changes, click the 'Save' button at the bottom of the form to save the changes. The main part of the form will close. Click the 'Close' button to completely close the form. 4. Individual Post and Static Pages - Meta SEO adds a new form to Habari's publish page that is accessed by clicking the Meta SEO button. When the form opens, you will have options to enter a new title, keywords, and description for the entry. If you do so, these will be used to generate the meta tags for the entry. If you leave any empty, MetaSEO will generate the tags from the entry's regular title, tags, and the beginning of its content. Uninstallation 1. Got to the plugins page of your Habari admin panel. 2. Click on the Deactivate button. 3. Delete the Meta SEO directory from your user/plugins directory. Cleanup 1. The plugin places several items in your Options table. All are preceded by the word MetaSEO. You can safely delete these entries after you uninstall the plugin. 2. The plugin stores items in the postinfo table whenever you create a custom title, keywords, or description. These have the names 'html_title', 'metaseo_desc', and 'metaseo_keywords'. These entries can be safely deleted. Changelog Version 0.5 Change: Converted Publish page fields to use Habari's built-in form controls. Version 0.4 Change: Converted configuration dialog to use Habari's updated form system. User's of previous versions will need to deactivate MetaSEO and reactivate it for the options to be generated properly. I would also recommend that you delete the old MetaSEO options from your database. Version 0.31 Fixed: Post titles in atom feed were all replaced by the site name and tagline. Fixed: Style changes in the configuration form to compensate for the new admin interface. Version 0.3 Change: Made the keywords to use on the home page an option. Change: Made indexing and following links an option for the home page, individual posts and static pages, and archive pages. Change: Added an entry box for the entry or page keywords on the publish page. Change: Added an entry box for the entry or page description on the publish page. Change: Added a style sheet for the configuration page. Fixed: Code cleanup. Version 0.2 - Initial release<file_sep><?php /** * Jambo a contact form plugin for Habari * * @package jambo * * @todo document the functions. * @todo use AJAX to submit form, fallback on default if no AJAX. * @todo allow "custom fields" to be added by user. */ require_once 'jambohandler.php'; class Jambo extends Plugin { const VERSION = '1.4.2'; const OPTION_NAME = 'jambo'; private $theme; public function help() { return _t( 'Add a contact form by inserting either <code>&lt;!-- jambo --&gt;</code> or <code>&lt;!-- contactform --&gt;</code> into an entry or page.' ); } private static function default_options() { return array( 'send_to' => $_SERVER['SERVER_ADMIN'], 'subject_prefix' => _t( '[CONTACT FORM] ' ), 'show_form_on_success' => 1, 'success_msg' => _t( 'Thank you for your feedback. I\'ll get back to you as soon as possible.' ), 'error_msg' => _t( 'The following errors occurred with the information you submitted. Please correct them and re-submit the form.' ) ); } public function action_plugin_activation( $file ) { if ( Plugins::id_from_file( $file ) == Plugins::id_from_file( __FILE__ ) ) { foreach ( self::default_options() as $name => $value ) { Options::set( self::OPTION_NAME . '__' . $name, $value ); } } } // helper function to return option values public static function get( $name ) { return Options::get( self::OPTION_NAME . '__' . $name ); } /** * Return plugin metadata for this plugin * * @return array Plugin metadata */ public function info() { return array( 'url' => 'http://drunkenmonkey.org/projects/jambo', 'name' => 'Jambo', 'license' => 'Apache License 2.0', 'author' => '<NAME>', 'authorurl' => 'http://drunkenmonkey.org/projects/jambo', 'version' => self::VERSION, 'description' => 'Adds a contact form to any page or post.' ); } public function set_priorities() { return array( 'filter_post_content_out' => 11 ); } /* Set up options */ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t('Configure'); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure') : $ui = new FormUI( self::OPTION_NAME ); // Add a text control for the address you want the email sent to $send_to = $ui->append( 'text', 'send_to', 'option:jambo__send_to', _t( 'Where To Send Email: ' ) ); $send_to->add_validator( 'validate_required' ); // Add a text control for the prefix to the subject field $subject_prefix = $ui->append( 'text', 'subject_prefix', 'option:jambo__subject_prefix', _t( 'Subject Prefix: ' ) ); $subject_prefix->add_validator( 'validate_required' ); $show_form_on_success = $ui->append( 'checkbox', 'show_form_on_success', 'option:jambo__show_form_on_success', _t( 'Show Contact Form After Sending?: ' ) ); // Add a text control for the prefix to the success message $success_msg = $ui->append( 'textarea', 'success_msg', 'option:jambo__success_msg', _t( 'Success Message: ' ) ); $success_msg->add_validator( 'validate_required' ); // Add a text control for the prefix to the subject field $error_msg = $ui->append( 'textarea', 'error_msg', 'option:jambo__error_msg', _t( 'Error Message: ') ); $error_msg->add_validator( 'validate_required' ); $ui->append( 'submit', 'save', 'Save' ); $ui->out(); break; } } } public function filter_rewrite_rules( $rules ) { $rules[] = new RewriteRule(array( 'name' => 'jambo', 'parse_regex' => '/^jambo\/send\/(?P<jcode>[0-9a-f]+)[\/]{0,1}$/i', 'build_str' => 'jambo/send/{$jcode}', 'handler' => 'JamboHandler', 'action' => 'send', 'priority' => 2, 'rule_class' => RewriteRule::RULE_PLUGIN, 'is_active' => 1, 'description' => 'Rewrite for Jambo Contact Form Plugin submittion.' )); return $rules; } public function filter_rewrite_args( $args, $rulename ) { switch( $rulename ) { case 'jambo': $args['jcode']= $this->get_code(); setcookie( 'habari_rc[' . $args['jcode'] . ']', md5( Options::get('GUID') . 'other salt' ), time()+60*60*2, '/' ); break; } return $args; } // this allows theme authors/users to create a customized jambo.form template // for Jambo to output it's form. we should have a default smarty template too. public function filter_available_templates( $templates, $class ) { if ( !in_array( 'jambo.form', $templates ) ) { switch ( strtolower($class) ) { case 'rawphpengine': $templates = array_merge( $templates, array('jambo.form') ); break; case 'hiengine': $templates = array_merge( $templates, array('jambo.form') ); break; } } return $templates; } public function filter_include_template_file( $template_path, $template_name, $class ) { if ( $template_name == 'jambo.form' ) { if ( ! file_exists( $template_path ) ) { switch ( strtolower($class) ) { case 'rawphpengine': $template_path = dirname( $this->get_file() ) . '/templates/jambo.form.php'; break; case 'smartyengine': $template_path = dirname( $this->get_file() ) . '/templates/jambo.form.tpl'; break; case 'hiengine': $template_path = dirname( $this->get_file() ) . '/templates/jambo.form.hi'; break; } } } return $template_path; } // here we store the current theme object for use later // saves us from creating a new theme object and using more resources. public function action_add_template_vars( $theme, $handler_vars ) { $this->theme = $theme; } public function filter_post_content_out( $content ) { $content = str_ireplace( array('<!-- jambo -->', '<!-- contactform -->'), $this->get_form(), $content ); return $content; } public function filter_jambo_email( $email, $handlervars ) { if ( !$this->verify_code($handlervars['jcode']) ) { ob_end_clean(); header('HTTP/1.1 403 Forbidden'); die(_t('<h1>The selected action is forbidden.</h1><p>Please enable cookies in your browser.</p>')); } if ( ! $this->verify_OSA( $handlervars['osa'], $handlervars['osa_time'] ) ) { ob_end_clean(); header('HTTP/1.1 403 Forbidden'); die(_t('<h1>The selected action is forbidden.</h1><p>You are submitting the form too fast and look like a spam bot.</p>')); } if ( empty( $email['name'] ) ) { $email['valid']= false; $email['errors']['name']= _t( '<em>Your Name</em> is a <strong>required field</strong>.' ); } if ( empty( $email['email'] ) ) { $email['valid']= false; $email['errors']['email']= _t( '<em>Your Email</em> is a <strong>required field</strong>.' ); } // validate email addy as per RFC2822 and RFC2821 with a little exception (see: http://www.regular-expressions.info/email.html) elseif( !preg_match("@^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*\@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$@i", $email['email'] ) ) { $email['valid']= false; $email['errors']['email']= _t( '<em>Your Email</em> must be a <strong>valid email address.</strong>' ); } if ( empty( $email['message'] ) ) { $email['valid']= false; $email['errors']['message']= _t( '<em>Your Remarks</em> is a <strong>required field</strong>.' ); } if( $email['valid'] !== false ) { $comment = new Comment( array( 'name' => $email['name'], 'email' => $email['email'], 'content' => $email['message'], 'ip' => sprintf("%u", ip2long( $_SERVER['REMOTE_ADDR'] ) ), 'post_id' => ( isset( $post ) ? $post->id : 0 ), ) ); $handlervars['ccode'] = $handlervars['jcode']; $_SESSION['comments_allowed'][] = $handlervars['ccode']; Plugins::act('comment_insert_before', $comment); if( Comment::STATUS_SPAM == $comment->status ) { ob_end_clean(); header('HTTP/1.1 403 Forbidden'); die(_t('<h1>The selected action is forbidden.</h1><p>Your attempted contact appears to be spam. If it wasn\'t, return to the previous page and try again.</p>')); } } return $email; } /** * Get a 10-digit hex code that identifies the user submitting the feedback * @param The IP address of the commenter * @return A 10-digit hex code **/ private function get_code( $ip = '' ) { if( $ip == '' ) { $ip = ip2long($_SERVER['REMOTE_ADDR']); } $code = substr(md5( Options::get('GUID') . 'more salt' . $ip ), 0, 10); $code = Plugins::filter('jambo_code', $code, $ip); return $code; } /** * Verify a 10-digit hex code that identifies the user submitting the feedback * @param The IP address of the commenter * @return True if the code is valid, false if not **/ private function verify_code( $suspect_code, $ip = '' ) { return ( $suspect_code == $this->get_code( $ip ) ); } private function get_OSA( $time ) { $osa = 'osa_' . substr( md5( $time . Options::get( 'GUID' ) . self::VERSION ), 0, 10 ); $osa = Plugins::filter('jambo_OSA', $osa, $time); return $osa; } private function verify_OSA( $osa, $time ) { if ( $osa == $this->get_OSA( $time ) ) { if ( ( time() > ($time + 5) ) && ( time() < ($time + 5*60) ) ) { return true; } } return false; } private function OSA( $vars ) { if ( array_key_exists( 'osa', $vars ) && array_key_exists( 'osa_time', $vars ) ) { $osa = $vars['osa']; $time = $vars['osa_time']; } else { $time = time(); $osa = $this->get_OSA( $time ); } return "<input type=\"hidden\" name=\"osa\" value=\"$osa\" />\n<input type=\"hidden\" name=\"osa_time\" value=\"$time\" />\n"; } /** * */ public static function input( $type, $name, $label, $vars = array() ) { $style = ( array_key_exists( 'errors', $vars ) && array_key_exists( $name, $vars['errors'] ) ) ? 'class="input-warning"' : ''; $value = array_key_exists( $name, $vars ) ? $vars[$name] : ''; switch ( $type ) { default: case 'text': return '<input type="text" size="40" maxlength="50" name="' . $name . '" value="' . $value . '" ' . $style . ' />'; break; case 'textarea': return '<textarea ' . $style . ' rows="8" cols="30" name="' . $name . '">' . $value . '</textarea>'; break; } } private function get_form() { if ( $this->theme instanceof Theme && $this->theme->template_exists( 'jambo.form' ) ) { $vars = array_merge( User::commenter(), Session::get_set( 'jambo_email' ) ); $this->theme->jambo = new stdClass; $jambo = $this->theme->jambo; $jambo->form_action = URL::get('jambo'); $jambo->success_msg = self::get( 'success_msg' ); $jambo->error_msg = self::get('error_msg'); $jambo->show_form = true; $jambo->success = false; $jambo->error = false; if ( array_key_exists( 'valid', $vars ) && $vars['valid'] ) { $jambo->success = true; $jambo->show_form = self::get( 'show_form_on_success' ); } if ( array_key_exists( 'errors', $vars ) ) { $jambo->error = true; $jambo->errors = $vars['errors']; } $jambo->name = $this->input( 'text', 'name', 'Your Name: (Required)', $vars ); $jambo->email = $this->input( 'text', 'email', 'Your Email: (Required)', $vars ); $jambo->subject = $this->input( 'text', 'subject', 'Subject: ', $vars ); $jambo->message = $this->input( 'textarea', 'message', 'Your Remarks: (Required)', $vars ); $jambo->osa = $this->OSA( $vars ); return $this->theme->fetch( 'jambo.form' ); } return null; } } ?> <file_sep><?php /** * Laconica Twitter-Compat API Plugin * * Show your latest Laconica notices in your theme and/or * post your latest blog post to your Laconica service. * * Usage: <?php $theme->laconica(); ?> to show your latest notices. * Copy the laconica.tpl.php template to your active theme to customize * output display. * **/ class Laconica extends Plugin { /** * Required plugin information * @return array The array of information **/ public function info() { return array( 'name' => 'Laconica', 'version' => '0.6.2', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Post to and display from <a href="http://laconi.ca">Laconica</a> servers.', 'copyright' => '2009' ); } /** * Update beacon support. UID is real, but not reg'd with project. **/ public function action_update_check() { Update::add( 'Laconica', '8676A858-E4B1-11DD-9968-131C56D89593', $this->info->version ); } public function help() { $help = _t('<p>For the <strong>Laconica Service</strong> setting, enter the portion of your Laconica server home page URL between the slash at the end of <tt>http://</tt> and the slash before your user name: <tt>http://</tt><strong>laconica.service</strong><tt>/</tt><em>yourname</em>.</p> <p>To use identi.ca, for example, since your URL is something like <tt>http://identi.ca/yourname</tt>, you would enter <tt>identi.ca</tt>.</p> <p>To display your latest notices, call <code>$theme->laconica();</code> at the appropriate place in your theme.</p>'); return $help; } /** * Add actions to the plugin page for this plugin * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id **/ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = 'Configure'; } return $actions; } /** * Set defaults. **/ public function action_plugin_activation( $file ) { if(Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__)) { if ( Options::get( 'laconica__hide_replies' ) !== 0 ) { Options::set( 'laconica__hide_replies', 1 ); } if ( Options::get( 'laconica__linkify_urls' ) !== 0 ) { Options::set( 'laconica__linkify_urls', 1 ); } if ( !Options::get( 'laconica__svc' ) ) { Options::set( 'laconica__svc', 'identi.ca' ); } if ( Options::get( 'laconica__show' ) !== 0 ) { Options::set( 'laconica__show', 1 ); } if ( !Options::get( 'laconica__limit' ) ) { Options::set( 'laconica__limit', 1 ); } } } /** * Respond to the user selecting an action on the plugin page * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook **/ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { if ( $action == _t( 'Configure' ) ) { $ui = new FormUI( strtolower( get_class( $this ) ) ); $laconica_svc = $ui->append( 'text', 'svc', 'laconica__svc', _t('Laconica Service:') ); // $laconica_svc->add_validator('validate_url'); $laconica_username = $ui->append( 'text', 'username', 'laconica__username', _t('Service Username:') ); $laconica_password = $ui->append( 'password', '<PASSWORD>', '<PASSWORD>', _t('Service Password:') ); $laconica_post = $ui->append( 'checkbox', 'post_status', 'laconica__post_status', _t('Autopost to Service') ); $laconica_post->options = array( '0' => _t('Disabled'), '1' => _t('Enabled') ); $laconica_post = $ui->append( 'text', 'prefix', 'laconica__prefix', _t('Autopost Prefix (e.g., "New post: "):') ); $laconica_show = $ui->append( 'checkbox', 'show', 'laconica__show', _t('Show latest notices') ); $laconica_limit = $ui->append( 'select', 'limit', 'laconica__limit', _t('Limit of notices to show') ); $laconica_limit->options = array_combine(range(1, 20), range(1, 20)); $laconica_show = $ui->append( 'checkbox', 'hide_replies', 'laconica__hide_replies', _t('Hide @replies') ); $laconica_show = $ui->append( 'checkbox', 'linkify_urls', 'laconica__linkify_urls', _t('Linkify URLs') ); $laconica_cache_time = $ui->append( 'text', 'cache', 'laconica__cache', _t('Cache expiry in seconds:') ); $ui->on_success( array( $this, 'updated_config' ) ); $ui->append( 'submit', 'save', _t('Save') ); $ui->out(); } } } /** * Returns true if plugin config form values defined in action_plugin_ui should be stored in options by Habari * @return bool True if options should be stored **/ public function updated_config( FormUI $ui ) { Session::notice( _t( 'Laconica options saved.', 'laconica' ) ); $ui->save(); } /** * Add the Laconica user options to the list of valid field names. * This causes adminhandler to recognize the laconica fields and * to set the userinfo record appropriately **/ public function filter_adminhandler_post_user_fields( $fields ) { $fields['laconica_name'] = 'laconica_name'; $fields['laconica_pass'] = '<PASSWORD>'; return $fields; } /** * Post a status to service * @param string $svcurl Catenation of user server, API endpoints * @param string $notice The new status to post **/ public function post_status( $svcurl, $notice, $name, $pw ) { $request = new RemoteRequest( $svcurl, 'POST' ); $request->add_header( array( 'Authorization' => 'Basic ' . base64_encode( "{$name}:{$pw}" ) ) ); $request->set_body( 'source=habari&status=' . urlencode( $notice ) ); $request->execute(); } /** * React to the update of a post status to 'published' * @param Post $post The post object with the status change * @param int $oldvalue The old status value * @param int $newvalue The new status value **/ public function action_post_update_status( $post, $oldvalue, $newvalue ) { if ( is_null( $oldvalue ) ) return; if ( $newvalue == Post::status( 'published' ) && $post->content_type == Post::type('entry') && $newvalue != $oldvalue ) { if ( Options::get( 'laconica__post_status' ) == '1' ) { $user = User::get_by_id( $post->user_id ); if ( ! empty( $user->info->laconica_name ) && ! empty( $user->info->laconica_pass ) ) { $name = $user->info->laconica_name; $pw = $user->info->laconica_pass; } else { $name = Options::get( 'laconica__username' ); $pw = Options::get( 'laconica__password' ); } $svcurl = 'http://' . Options::get('laconica__svc') . '/index.php?action=api&apiaction=statuses&method=update.xml'; $this->post_status( $svcurl, Options::get( 'laconica__prefix' ) . $post->title . ' ' . $post->permalink, $name, $pw ); } } } public function action_post_insert_after( $post ) { return $this->action_post_update_status( $post, -1, $post->status ); } /** * Add last service status, time, and image to the available template vars * @param Theme $theme The theme that will display the template **/ public function theme_laconica( $theme ) { $notices = array(); if ( Options::get( 'laconica__show' ) && Options::get( 'laconica__svc' ) && Options::get( 'laconica__username' ) != '' ) { $laconica_url = 'http://' . Options::get( 'laconica__svc' ) . '/index.php?action=api&apiaction=statuses&method=user_timeline&argument=' . urlencode( Options::get( 'laconica__username' ) ) . '.xml'; /* * Only need to get a single notice if @replies are hidden. * (Otherwise, rely on the maximum returned and hope one is a non-reply.) */ if ( !Options::get( 'laconica__hide_replies' ) && Options::get( 'laconica__limit' ) ) { $laconica_url .= '&count=' . Options::get( 'laconica__limit' ); } if ( Cache::has( 'laconica_notices' ) ) { $notices = Cache::get( 'laconica_notices' ); } else { try { $response = RemoteRequest::get_contents( $laconica_url ); $xml = @new SimpleXMLElement( $response ); // Check we've got a load of statuses returned if ( $xml->getName() === 'statuses' ) { foreach ( $xml->status as $status ) { if ( ( !Options::get( 'laconica__hide_replies' ) ) || ( strpos( $status->text, '@' ) === false) ) { $notice = (object) array ( 'text' => (string) $status->text, 'time' => (string) $status->created_at, 'image_url' => (string) $status->user->profile_image_url ); $notices[] = $notice; if ( Options::get( 'laconica__hide_replies' ) && count($notices) >= Options::get( 'laconica__limit' ) ) break; } else { // it's a @. Keep going. } } if ( !$notices ) { $notice->text = 'No non-replies replies available from service.'; $notice->time = ''; $notice->image_url = ''; } } // You can get error as a root element if service is in maintance mode. else if ( $xml->getName() === 'error' ) { $notice->text = (string) $xml; $notice->time = ''; $notice->image_url = ''; } // Should not be reached. else { $notice->text = 'Received unexpected XML from service.'; $notice->time = ''; $notice->image_url = ''; } } catch ( Exception $e ) { $notice->text = 'Unable to contact service.'; $notice->time = ''; $notice->image_url = ''; } if (!$notices) $notices[] = $notice; // Cache (even errors) to avoid hitting rate limit. Cache::set( 'laconica_notices', $notices, Options::get( 'laconica__cache' ) ); } if ( Options::get( 'laconica__linkify_urls' ) != FALSE ) { /* http: links */ foreach ($notices as $notice) $notice->text = preg_replace( '%https?://\S+?(?=(?:[.:?"!$&\'()*+,=]|)(?:\s|$))%i', "<a href=\"$0\">$0</a>", $notice->text ); } } else { $notice = (object) array ( 'text' => _t('Check username or "Show latest notice" setting in <a href="%s">Laconica plugin config</a>', array( URL::get( 'admin' , 'page=plugins&configure=' . $this->plugin_id . '&configaction=Configure' ) . '#plugin_' . $this->plugin_id ) , 'laconica' ), 'time' => '', 'image_url' => '' ); $notices[] = $notice; } $theme->notices = $notices; return $theme->fetch( 'laconica.tpl' ); } /** * On plugin init, add the template included with this plugin to the available templates in the theme */ public function action_init() { $this->add_template('laconica.tpl', dirname(__FILE__) . '/laconica.tpl.php'); } } ?> <file_sep><?php class RandomPostLink extends Plugin { function filter_rewrite_rules($rules) { $rules[] = RewriteRule::create_url_rule('"randompost"', 'PluginHandler', 'randompost'); return $rules; } function action_plugin_act_randompost($handler) { $criteria = array( 'status' => Post::status('published'), 'type' => Post::type('entry'), 'orderby' => 'RAND()', 'limit' => 1, ); $post = Post::get($criteria); Utils::redirect($post->permalink); } } ?><file_sep><?php /** * jsmincdn * * @version $Id$ * @copyright 2009 */ class jsMinCDN extends Plugin { function help() { return _t('There is no helping you now.'); } function action_plugin_activation( $plugin_file ) { } function configure() { $ui = new FormUI('jsmincdn'); $scripts = $ui->append( 'checkboxes', 'scripts', 'jsmincdn__storage', 'Select the scripts that should be served as minimized.' ); $options = array_keys(Stack::get_named_stack('admin_header_javascript')); $scripts->options = array_combine($options, $options); $ui->append('submit', 'submit', 'Submit'); return $ui; } function filter_stack_out($stack, $stack_name, $filter) { static $incmin = false; if ( is_callable($filter) && strcasecmp(implode('::', $filter), 'stack::scripts') == 0) { // Load the minifier class once if(!$incmin) { include 'jsmin/jsmin.php'; $incmin = true; } // Get the script names to minify $domin = Options::get('jsmincdn__storage'); // Find greatest common sequences $seqs = array(); $script_build = 'jsmincdn'; $seq = array(); foreach( $stack as $name => $element ) { $doomit = false; if($domin && in_array($name, $domin)) { $script_build .= '.' . $name; $seq[$name] = $element; } else { if(count($seq) > 0) { $seqs[$script_build] = $seq; $script_build = 'jsmincdn'; $seq = array(); } $seqs[$name] = $element; } } if(count($seq) > 0) { $seqs[$script_build] = $seq; $script_build = 'jsmincdn'; $seq = array(); } $script = ''; $restack = array(); $script_build = ''; $output = ''; foreach( $seqs as $seqname => $seqelement ) { if(is_string($seqelement)) { $doomit = true; $restack[$seqname] = $seqelement; } elseif(Cache::has(array('jsmincdn_post', $seqname))) { $doomit = false; $output = Cache::get(array('jsmincdn_post', $seqname)); //$restack[$seqname] = $output; $restack[$seqname] = URL::get('jsmincdn', array('name' => $seqname)); } else { foreach($seqelement as $name => $element) { if(strpos($element, "\n") !== FALSE) { $output = $element; } elseif(Cache::has(array('jsmincdn', $element))) { $output = Cache::get(array('jsmincdn', $element)); } elseif( strpos($element, Site::get_url('scripts')) === 0 ) { $base = substr($element, strlen(Site::get_url('scripts'))); $filename = HABARI_PATH . '/scripts' . $base; $output = file_get_contents($filename); Cache::set(array('jsmincdn', $element), $output, 3600 * 24); } elseif( strpos($element, Site::get_url('habari')) === 0 ) { $base = substr($element, strlen(Site::get_url('habari'))); $filename = HABARI_PATH . $base; $output = file_get_contents($filename); Cache::set(array('jsmincdn', $element), $output, 3600 * 24); } elseif( strpos($element, Site::get_url('admin_theme')) === 0 ) { $base = substr($element, strlen(Site::get_url('admin_theme'))); $filename = HABARI_PATH . '/system/admin' . $base; $output = file_get_contents($filename); Cache::set(array('jsmincdn', $element), $output, 3600 * 24); } elseif( ( strpos($element, 'http://') === 0 || strpos($element, 'https://' ) === 0 ) ) { $output = RemoteRequest::get_contents($element); Cache::set(array('jsmincdn', $element), $output, 3600 * 24); } else { $output = $element; } $script .= "\n\n/* {$name} */\n\n"; $script .= JSMin::minify($output); } //$restack[$seqname] = $script; $restack[$seqname] = URL::get('jsmincdn', array('name' => $seqname)); Cache::set(array('jsmincdn_post', $seqname), $script, 3600 * 24); } } $stack = $restack; } return $stack; } public function action_handler_script_cache( $handler_vars ) { $cache_name = $handler_vars['name']; $script = Cache::get(array('jsmincdn_post', $cache_name)); header('content-type: text/javascript'); echo $script; } public function filter_rewrite_rules( $rules ) { $rules[] = new RewriteRule( array( 'name' => 'jsmincdn', 'parse_regex' => '%^jsmincdn/(?P<name>.+)/?$%i', 'build_str' => 'jsmincdn/{$name}/', 'handler' => 'UserThemeHandler', 'action' => 'script_cache', 'priority' => 3, 'is_active' => 1, 'description' => 'Reply with a script from cache', )); return $rules; } } ?><file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title><?php Options::out( 'title' ); ?></title> <script src="http://ajax.cdnjs.com/ajax/libs/headjs/0.9/head.min.js"></script> <?php $theme->header( ); ?> </head> <body class="<?php $theme->body_class( ); ?>"> <div id="wrapper"> <header id="nameplate" role="banner"> <hgroup> <h1 class="logo"><a href="<?php Site::out_url( 'habari' ); ?>" rel="home"><?php Options::out( 'title' ); ?></a></h1> <h2 class="tagline"><?php Options::out( 'tagline' ); ?></h2> </hgroup> <nav id="mainmenu" role="navigation"> <?php $theme->area( 'nav' ); ?> </nav> </header><file_sep><?php class HTML5Shiv extends Plugin { /** * Set priority to move inserted tags nearer to the end * @return array **/ public function set_priorities() { return array( 'theme_header' => 11, ); } /** * Add tags to headers. * @return array **/ public function theme_header( $theme ) { return '<!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]-->'; } } ?> <file_sep><?php class PrePublish extends Plugin { public function info() { return array( 'name' => 'PrePublish', 'version' => '1.0', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Publish all "published" posts, regardless of pubdate', 'copyright' => '2011' ); } public function action_publish_post( $post ) { if ( Post::status_name( $post->status ) == 'scheduled' ) { $post->status = Post::status( 'published' ); } } } ?> <file_sep><?php /** * Bit.ly Plugin * * Generates a bit.ly short URL for each post, and * makes it available in the post's info. A default template is supplied * which can be displayed in the header of the theme. * **/ class Bitly extends Plugin { public function action_init() { $this->add_template('bitly_short_url', dirname(__FILE__) . '/bitly_short_url.php'); } public function action_plugin_ui($plugin_id, $action) { if ($plugin_id == $this->plugin_id()) { switch ($action) { case _t('Configure'): $form = new FormUI(__CLASS__); $login = $form->append('text', 'login', 'bitly__login', _t('Login')); $login->add_validator('validate_required'); $apiKey = $form->append('text', 'api_key', 'bitly__api_key', _t('API Key')); $apiKey->add_validator('validate_required'); $form->append('submit', 'save', 'Save'); $form->on_success( array( $this, 'updated_config' ) ); $form->out(); break; } } } public function updated_config( FormUI $ui ) { Session::notice( _t( 'Bit.ly options saved.', 'bitly' ) ); $ui->save(); } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t( 'Configure' ); } return $actions; } public function theme_show_bitly_shorturl($theme, $post) { $theme->post = $post; return $theme->fetch('bitly_short_url'); } public function action_post_insert_after($post) { if (Post::status('published') != $post->status) { return; } try { $bitly = new BitlyAPI(Options::get('bitly__login'), Options::get('bitly__api_key')); $result = $bitly->shorten($post->permalink); $post->info->short_url = $result->data->url; } catch (Exception $e) { Session::error('Could not communicate with bit.ly API.', 'Bit.ly API'); } } } class BitlyAPI { public $endpoint = 'http://api.bit.ly/v3'; public $format = 'json'; protected $username = null; protected $apiKey = null; public function __construct($username, $apiKey) { $this->username = $username; $this->apiKey = $apiKey; } public function shorten($url) { $params = array( 'login' => $this->username, 'apiKey' => $this->apiKey, 'format' => $this->format, 'longUrl' => $url, ); $reqUrl = $this->endpoint . '/shorten?' . http_build_query($params); $call = new RemoteRequest($reqUrl); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { throw $result; } $response = $call->get_response_body(); $data = json_decode($response); if ($data === null) { throw new Exception("Could not communicate with bit.ly API"); } return $data; } } ?> <file_sep><div id="timeline"> <div class="years"> <?php $year = false; foreach($timeline_items as $item) { if(date('Y', $item['time']) != $year) { ?> <?php if($year != false) { ?></div></div></div><?php } ?> <div class="year"> <span><?php echo date('Y', $item['time']); ?></span> <div class="months"> <?php $year = date('Y', $item['time']); $month = false; } if(date('m', $item['time']) != $month) { ?> <?php if($month != false) { ?></div><?php } ?> <div class="month"> <span><?php echo date('M', $item['time']); ?></span> <?php $month = date('m', $item['time']); } ?> <a class="item" href="<?php echo $item['url']; ?>" title="<?php echo $item['title']; ?> was published on <?php echo date('F j, Y'); ?>"><?php echo $item['title']; ?></a> <?php } ?> </div> </div> </div> </div> <div class="track"> <div class="handle"> <span class="resizehandleleft"></span> <span class="resizehandleright"></span> </div> </div> </div><file_sep><?php class Sitemaps extends Plugin { /** * Filter function called by the plugin hook `rewrite_rules` * Add a new rewrite rule to the database's rules. * * Call `Sitemaps::act('Sitemap')` when a request for `sitemap.xml` is received. * * @param array $db_rules Array of rewrite rules compiled so far * @return array Modified rewrite rules array, we added our custom rewrite rule */ public function filter_rewrite_rules( $db_rules ) { $db_rules[]= RewriteRule::create_url_rule( '"sitemap.xml"', 'Sitemaps', 'Sitemap' ); if ( function_exists( 'gzencode' ) ) { $db_rules[]= RewriteRule::create_url_rule( '"sitemap.xml.gz"', 'Sitemaps', 'SitemapGz' ); } return $db_rules; } /** * Act function called by the `Controller` class. * Dispatches the request to the proper action handling function. * * @param string $action Action called by request, we only support 'Sitemap' */ public function act( $action ) { switch ( $action ) { case 'Sitemap': self::Sitemap(); break; case 'SitemapGz': self::SitemapGz(); break; } } /** * Sitemap function called by the self `act` function. * Generates the `sitemap.xml` file to output. */ public function Sitemap() { /* Clean the output buffer, so we can output from the header/scratch. */ ob_clean(); header( 'Content-Type: application/xml' ); print self::SitemapBuild(); } public function SitemapGz() { ob_clean(); header( 'Content-Type: application/x-gzip' ); print gzencode( self::SitemapBuild() ); } public function SitemapBuild() { //return cached sitemap if exsist if ( Cache::has( 'sitemap' ) ){ $xml = Cache::get( 'sitemap' ); } else { //..or generate a new one $xml = '<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="'.$this->get_url() .'/sitemap.xsl"?><urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>'; $xml = new SimpleXMLElement( $xml ); // Retreive all published posts and pages from the database $content['posts']= Posts::get( array( 'content_type' => 'entry', 'status' => 'published', 'nolimit' => 1 ) ); $content['pages']= Posts::get( array( 'content_type' => 'page', 'status' => 'published', 'nolimit' => 1 ) ); // Add the index page first $url = $xml->addChild( 'url' ); $url_loc = $url->addChild( 'loc', Site::get_url( 'habari' ) ); // Generate the `<url>`, `<loc>`, `<lastmod>` markup for each post and page. foreach ( $content as $entries ) { foreach ( $entries as $entry ) { $url = $xml->addChild( 'url' ); $url_loc = $url->addChild( 'loc', $entry->permalink ); $url_lastmod = $url->addChild( 'lastmod', $entry->updated->get( 'c' ) ); } } $xml = $xml->asXML(); Cache::set( 'sitemap', $xml ); } return $xml; } /** * post_update_status action called when the post status field is updated. * Expires the cached sitemap if the status has been changed. * * @param Post $post The post being updated * @param string $new_status the status feild new value */ public function action_post_update_status( $post, $new_status ) { if ( $post->status != $new_status ){ Cache::expire( 'sitemap' ); } } } ?> <file_sep><?php /** * AtomThreading Class * **/ class AtomThreading extends Plugin { private $class_name = ''; public function info() { return array( 'name' => 'Atom Threading Extensions', 'version' => '0.2', 'url' => 'http://code.google.com/p/bcse/wiki/AtomThreadingExtensions', 'author' => '<NAME>', 'authorurl' => 'http://blog.bcse.info/', 'license' => 'Apache License 2.0', 'description' => _t('Implement Atom threading extensions (RFC4685) on Habari. In other words, this plugin allows you to add Comments Count FeedFlare™ to your feed.', $this->class_name) ); } /** * On plugin activation, set the default options */ public function action_plugin_activation($file) { if (realpath($file) === __FILE__) { $this->class_name = strtolower(get_class($this)); } } /** * On plugin init, add the template included with this plugin to the available templates in the theme */ public function action_init() { $this->class_name = strtolower(get_class($this)); $this->load_text_domain($this->class_name); } /** * Add update beacon support **/ public function action_update_check() { Update::add('Atom Threading Extensions', 'a413fa7e-76cf-4edf-b7c5-53b8aa648eef', $this->info->version); } public function filter_atom_get_collection_namespaces($namespaces) { $namespaces['thr'] = 'http://purl.org/syndication/thread/1.0'; return $namespaces; } public function action_atom_add_post($xml, $post) { $link = $xml->addChild('link'); $link->addAttribute('rel', 'replies'); //type="application/atom+xml" is default, could be omitted //$link->addAttribute('type', 'application/atom+xml'); $link->addAttribute('href', URL::get('atom_feed_entry_comments', array('slug' => $post->slug))); $link->addAttribute('thr:count', $post->comments->approved->count, 'http://purl.org/syndication/thread/1.0'); if ($post->comments->approved->count > 0) $link->addAttribute('thr:updated', HabariDateTime::date_create(end($post->comments->approved)->date)->get(HabariDateTime::ATOM), 'http://purl.org/syndication/thread/1.0'); $xml->addChild('thr:total', $post->comments->approved->count, 'http://purl.org/syndication/thread/1.0'); } public function action_atom_add_comment($xml, $comment) { $in_reply_to = $xml->addChild('thr:in-reply-to', NULL, 'http://purl.org/syndication/thread/1.0'); $in_reply_to->addAttribute('ref', $comment->post->guid); $in_reply_to->addAttribute('href', $comment->post->permalink); $in_reply_to->addAttribute('type', 'text/html'); } } ?><file_sep><?php class TagTray extends Plugin { private $theme; /** * function info * Returns information about this plugin * @return array Plugin info array **/ function info() { return array ( 'name' => 'Tag Tray', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'version' => '1.0', 'description' => 'Displays a tray of tags on the publish page to click on and add to the edited post.', 'license' => 'Apache License 2.0', ); } /** * Add the tray to the publish form * @params FormUI $form The publish form object instance * @params Post $post The post that is being edited **/ public function action_form_publish($form, $post) { // Create the tags selector $tagselector = $form->publish_controls->append('fieldset', 'tagselector', _t('Tags')); $tags_buttons = $tagselector->append('wrapper', 'tags_buttons'); $tags_buttons->class = 'container'; $tags_buttons->append('static', 'clearbutton', '<p class="span-5"><input type="button" value="'._t('Clear').'" id="clear"></p>'); $tags_list = $tagselector->append('wrapper', 'tags_list'); $tags_list->class = ' container'; $tags_list->append('static', 'tagsliststart', '<ul id="tag-list" class="span-19">'); $tags = Tags::get(); $max = Tags::max_count(); foreach ($tags as $tag) { $tags_list->append('tag', 'tag_'.$tag->slug, $tag, 'tabcontrol_text'); } $tags_list->append('static', 'tagslistend', '</ul>'); } /** * Add the required javascript to the publish page * @param Theme $theme The admin theme instance **/ public function action_admin_header($theme) { Stack::add('admin_header_javascript', $this->get_url(true) . 'tagtray.js', 'tagtray'); } } ?><file_sep><?php include 'header.php'; ?> <div class="post"> <?php $first= true; foreach ( $posts as $post ) { include 'entry.php'; $first= false; } ?> </div> <div class="footnav"> Page: <?php $theme->page_selector(); ?> </div> <?php include 'sidebar.php'; ?> <?php include 'footer.php'; ?> <file_sep><div id="lastfm"> <ul id="lastrecent"> <?php if ( isset( $content->lastfm_recent['error'] ) ) : ?> <li> <?php echo $content->lastfm_recent['error']; ?> </li> <?php else : foreach ( $content->lastfm_recent as $track ) : ?> <li> <a href="<?php echo $track['url']; ?>"><?php if ( $track['image'] != '' ) : ?><img src="<?php echo $track['image'];?>" /><?php endif; ?><?php echo $track['name']; ?></a> by <?php echo $track['artist'];?> </li> <?php endforeach; endif; ?> </ul> </div> <file_sep><!-- This file can be copied and modified in a theme directory --> <div id="twitterbox"> <img src="<?php echo htmlspecialchars( $tweet_image_url ); ?>" alt="<?php echo urlencode( Options::get( 'twitter__username' )); ?>"> <p><?php echo $tweet_text . ' @ ' . $tweet_time; ?></p> <p><small>via <a href="http://twitter.com/<?php echo urlencode( Options::get( 'twitter__username' )); ?>">Twitter</a></small></p> </div> <file_sep><!-- To customize this template, copy it to your currently active theme directory and edit it --> <div id="blogroll"> <h2><?php echo Options::get( 'blogroll__list_title' ); ?></h2> <ul> <?php if ( ! empty( $blogs ) ) { foreach( $blogs as $blog ) { ?> <li><a href="<?php echo $blog->url; ?>"><?php echo $blog->name; ?></a></li> <?php } } ?> </ul> </div><file_sep><?php /* * Blogroll Plugin * Usage: <?php $theme->show_blogroll(); ?> * A sample blogroll.php template is included with the plugin. This can be copied to your * active theme and modified to fit your preference. * * @todo Update wiki docs, and inline code docs */ class Blogroll extends Plugin { const VERSION= '1.0-alpha'; public function info() { return array( 'name' => 'Blogroll', 'version' => self::VERSION, 'url' => 'http://wiki.habariproject.org/en/plugins/blogroll', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Displays a blogroll on your blog' ); } public function action_init() { Post::add_new_type('link'); $this->add_template('blogroll_manage', dirname(__FILE__) . '/templates/blogroll_manage.php'); } public function filter_adminhandler_post_loadplugins_main_menu( $menus ) { $menus['blogroll_manage'] = array( 'url' => URL::get( 'admin', 'page=blogroll_manage'), 'title' => _t('Manage Blogroll'), 'text' => _t('Manage Blogroll'), 'selected' => false, 'hotkey' => 'B' ); return $menus; } public function action_admin_theme_get_blogroll_manage( $handler, $theme ) { $theme->admin_page= 'Manage Blogroll'; $theme->admin_title= 'Manage Blogroll'; $form= new FormUI('blogroll'); $form->class[]= 'create'; $tabs= $form->append('tabs', 'opml_tabs'); $opml= $tabs->append('fieldset', 'opmltab', _t('Import/Export OPML')); $theme->form= $form; } public function action_publish_post($post, $form) { if($post->content_type != Post::type('link')) return; $this->action_form_publish($form, $post); if($form->quick_url->value != '') { $data= $this->get_info_from_url($form->quick_url->value); $post->title= $data['name']; $post->info->url= $data['url']; $post->content= $data['description']; $post->info->feedurl= $data['feed']; $post->slug= Utils::slugify($data['name']); } else { $post->info->url= $form->url->value; $post->info->feedurl= $form->feedurl->value; $post->info->ownername= $form->ownername->value; $post->info->relationship= $form->relationship->value; } // exit(); } public function action_form_publish($form, $post) { if($post->content_type != Post::type('link')) return; // Quick link button to automagically discover info $quicklink_controls= $form->append('tabs', 'quicklink_controls'); $quicklink_tab= $quicklink_controls->append('fieldset', 'quicklink_tab', _t('Quick Link')); $quicklink_wrapper= $quicklink_tab->append('wrapper', 'quicklink_wrapper'); $quicklink_wrapper->class='container'; $quicklink_wrapper->append('text', 'quick_url', 'null:null', _t('Quick URL'), 'tabcontrol_text'); $quicklink_wrapper->append('static', 'quick_url_info', '<p class="column span-15">Enter a url or feed url and other information will be automatically discovered.</p>'); $quicklink_wrapper->append('submit', 'addquick', _t('Add'), 'admincontrol_submit'); $quicklink_controls->move_before($quicklink_controls, $form); // Remove fields we don't need $form->silos->remove(); $form->comments_enabled->remove(); $form->newslug->remove(); if($form->post_permalink != NULL) $form->post_permalink->remove(); // Add the url field $form->append('text', 'url', 'null:null', _t('URL'), 'admincontrol_text'); $form->url->class= 'important'; $form->url->tabindex = 2; $form->url->value = $post->info->url; $form->url->move_after($form->title); // Retitle fields $form->title->caption= _t('Blog Name'); $form->content->caption= _t('Description'); $form->content->tabindex= 3; $form->tags->tabindex= 4; // Create the extras splitter & fields $extras = $form->settings; $extras->append('text', 'feedurl', 'null:null', _t('Feed URL'), 'tabcontrol_text'); $extras->feedurl->value = $post->info->feedurl; $extras->append('text', 'ownername', 'null:null', _t('Owner Name'), 'tabcontrol_text'); $extras->ownername->value = $post->info->ownername; $extras->append('select', 'relationship', 'null:null', _t('Relationship'), $this->get_relationships(), 'tabcontrol_select'); $extras->relationship->value = $post->info->relationship; } public static function get_info_from_url( $url ) { $info= array(); $data= RemoteRequest::get_contents( $url ); $feed= self::get_feed_location( $data, $url ); if ( $feed ) { $info['feed']= $feed; $data= RemoteRequest::get_contents( $feed ); } else { $info['feed']= $url; } // try and parse the xml try { $xml= new SimpleXMLElement( $data ); switch ( $xml->getName() ) { case 'RDF': case 'rss': $info['name']= (string) $xml->channel->title; $info['url']= (string) $xml->channel->link; if ( (string) $xml->channel->description ) $info['description']= (string) $xml->channel->description; break; case 'feed': $info['name']= (string) $xml->title; if ( (string) $xml->subtitle ) $info['description']= (string) $xml->subtitle; foreach ( $xml->link as $link ) { $atts= $link->attributes(); if ( $atts['rel'] == 'alternate' ) { $info['url']= (string) $atts['href']; break; } } break; } } catch ( Exception $e ) { return array(); } return $info; } public static function get_feed_location( $html, $url ) { preg_match_all( '/<link\s+(.*?)\s*\/?>/si', $html, $matches ); $links= $matches[1]; $final_links= array(); $href= ''; $link_count= count( $links ); for( $n= 0; $n < $link_count; $n++ ) { $attributes= preg_split('/\s+/s', $links[$n]); foreach ( $attributes as $attribute ) { $att= preg_split( '/\s*=\s*/s', $attribute, 2 ); if ( isset( $att[1] ) ) { $att[1]= preg_replace( '/([\'"]?)(.*)\1/', '$2', $att[1] ); $final_link[strtolower( $att[0] )]= $att[1]; } } $final_links[$n]= $final_link; } for ( $n= 0; $n < $link_count; $n++ ) { if ( isset($final_links[$n]['rel']) && strtolower( $final_links[$n]['rel'] ) == 'alternate' ) { if ( isset($final_links[$n]['type']) && in_array( strtolower( $final_links[$n]['type'] ), array( 'application/rss+xml', 'application/atom+xml', 'text/xml' ) ) ) { $href= $final_links[$n]['href']; } if ( $href ) { if ( strstr( $href, "http://" ) !== false ) { $full_url= $href; } else { $url_parts= parse_url( $url ); $full_url= "http://$url_parts[host]"; if ( isset( $url_parts['port'] ) ) { $full_url.= ":$url_parts[port]"; } if ( $href{0} != '/' ) { $full_url.= dirname( $url_parts['path'] ); if ( substr( $full_url, -1 ) != '/' ) { $full_url.= '/'; } } $full_url.= $href; } return $full_url; } } } return false; } private function get_relationships() { return array( 'external' => 'External', 'nofollow' => 'Nofollow', 'bookmark' => 'Bookmark' ); } } ?><file_sep><?php /** * MovableType Export File Parser * * @version $Id$ * @author ayunyan <<EMAIL>> * @license http://www.opensource.org/licenses/bsd-license.php Modified BSD License * @link http://ayu.commun.jp/ */ class MTFileParser { private $result = array(); /** * constructer * * @access public * @param string $text; */ public function __construct($text) { if (!preg_match("/^[A-Z\s]+: /", $text)) throw new Exception('Invalid Format'); $text = str_replace("\r\n", "\n", $text); $t_posts = explode("--------\n", $text); @reset($t_posts); while (list(, $t_post) = @each($t_posts)) { $t_post = ltrim($t_post); if (empty($t_post)) continue; $t_sections = explode("-----\n", $t_post); $post = array(); @reset($t_sections); while (list(, $t_section) = @each($t_sections)) { $t_section = ltrim($t_section); if (empty($t_section)) continue; $section = $this->parseSection($t_section); if (empty($section['_NAME'])) { $post['_META'] = $section; } elseif ($section['_NAME'] == 'COMMENT' || $section['_NAME'] == 'PING') { if (!isset($post[$section['_NAME']])) $post[$section['_NAME']] = array(); $post[$section['_NAME']][] = $section; } else { $post[$section['_NAME']] = $section; } } $this->result[] = $post; } } /** * get results * * @access public * @return array */ public function getResult() { return $this->result; } /** * parse section * * @access private * @param string $section_text * @return array */ private function parseSection($section_text) { $section = array(); $section['_NAME'] = ''; $section['_BODY'] = ''; $lines = explode("\n", $section_text); $line_count = count($lines); $meta_flag = true; for ($i = 0; $i < $line_count; $i++) { if ($meta_flag && preg_match("/^([A-Z\s]+):\s?(.*?)$/", $lines[$i], $match)) { if ($i == 0 && empty($match[2])) { $section['_NAME'] = $match[1]; } else { if ($match[1] == 'CATEGORY') { if (!isset($section[$match[1]])) $section[$match[1]] = array(); $section[$match[1]][] = $match[2]; } else { $section[$match[1]] = $match[2]; } } } else { $meta_flag = false; $section['_BODY'] .= $lines[$i] . "\n"; } } return $section; } } ?><file_sep><?php $theme->display('head'); ?> <?php $primary = implode( '', ( array ) $theme->area_return('primary') ); $sidebar = implode( '', ( array ) $theme->area_return('sidebar') ); $primary_class = 'yui-b'; $show_sidebar = true; if($sidebar == '') { $show_sidebar = false; $primary_class = ''; } ?> <div id="bd"> <div id="yui-main"> <div id="primary" class="<?php echo $primary_class; ?>"> <?php Session::messages_out(); ?> <?php echo $primary ?> </div> </div> <?php if($show_sidebar): ?> <div id="sidebar" class="yui-b"> <?php echo $sidebar; ?> </div> <?php endif; ?> <div id="columns" class="yui-gb"> <div id="home_a" class="yui-u first"> <?php $theme->area('footer left'); ?> </div> <div id="home_b" class="yui-u"> <?php $theme->area('footer center'); ?> </div> <div id="home_c" class="yui-u"> <?php $theme->area('footer right'); ?> </div> </div> </div> <?php $theme->display('footer'); ?> <file_sep>Plugin: Simple Blacklist URL: http://habariproject.org Version: 1.3.1-alpha2 Author: Habari Project Purpose Any blog that allows people to comment wil receive spam. Simple Blacklist can be a part of your spam fighting armament that will examine all comments against a list of words, phrases, and ip addresses that you manually add to Simple Blacklist. Any time there is a match, Simple Blacklist will silently discard the comment so you never have to see it or deal with it. Requirements Habari 0.6 or higher Installation 1. Copy the plugin directory into your user/plugins directory or the site's plugins directory. 2. Go to the plugins page of your Habari admin panel. 3. Click on the Activate button for Simple Blacklist. Usage Click on the Configure option for Simple Blacklist. The configuration dialog contains two settings. 1. A text box in which you enter the words, phrases, urls, and ip addresses. Each entry must be on its own line. Whenever you find a new item you wish to include in the blacklist, come back here and add it to the list. 2. A checkbox to allow you to decide whether frequent commenters must have their comments compared to the blacklist or not. After you've made your changes to the options, click the Save button to save them to your database, then click the Close button to close the dialog. Uninstallation 1. Got to the plugins page of your Habari admin panel. 2. Click on the Deactivate button. 3. Delete the simpleblacklist directory from your Habari installation. Cleanup 1. The plugin places several items in your Options table. All are prepended with 'simpleblacklist__'. You can safely delete these entries after you uninstall the plugin. Changelog Version 1.3.1-alpha2 Change: Yes/No dropdown made into to a checkbox Version 1.3.1-alpha Fixed: ip addresses weren't being converted to quad form before being checked against the blacklist Version 1.1.1 Fixed: Updated to use new user object properly Version 1.1 Change: Changed configuration dialog to conform to Habari's updated form's interface Change: Prepended name to entries in the options table changed from 'simpleblacklist:' to simpleblacklist_' to conform to new storage guidelines. You will need to copy your old blacklisted words, phrases, and ip addresses. After you do so, you can safely delete the old settings. Version 1.0 Initial release <file_sep><?php class Typekit extends Plugin { /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Typekit', '8cbb17db-dc5f-4a28-ba75-c407e83b9303', $this->info->version ); } /** * Set priority to move inserted tags nearer to the end * @return array **/ public function set_priorities() { return array( 'theme_header' => 11, ); } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t( 'Configure' ); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t( 'Configure' ): $class_name = strtolower( get_class( $this ) ); $ui = new FormUI( $class_name ); $embed = $ui->append( 'text', 'embed', 'typekit__embed', _t( 'Embed Code (required)' ) ); $embed->add_validator( 'validate_required' ); $ui->append( 'static', 'clarification', _t( '<p>Typically this will look like <i>http://use.typekit.com/abcdef.js</i>, and can be found if you click <u>Embed Code</u> in the Kit Editor.</p>' ) ); $ui->on_success( array($this, 'update_config' ) ); $ui->append( 'submit', 'save', 'save' ); $ui->out(); break; } } } /** * Give the user a session message to confirm options were saved. **/ public function update_config( $ui ) { Session::notice( _t( 'Typekit Embed Code stored.', 'typekit' ) ); $ui->save(); } /** * Add tags to headers. * @return array **/ public function theme_header( $theme ) { return $this->get_tags(); } /** * Generate tags for adding to headers. * @return string Tags to add to headers. **/ private function get_tags() { $embed = Options::get( 'typekit__embed' ); return "<script type=\"text/javascript\" src=\"$embed\"></script>" . "\n<script type=\"text/javascript\">try{Typekit.load();}catch(e){}</script>"; } } ?> <file_sep> <li id="widget-freshsurf" class="widget"> <h3><?php _e('Notepad', 'binadamu') ?></h3> <ul> <?php foreach ($delicious->post as $item) { printf('<li><a href="%1$s" title="%2$s" rel="%3$s">%4$s</a></li>', $item['href'], $item['extended'], $item['tag'], $item['description']); } ?> </ul> </li> <file_sep><?php if( isset($similar) && count($similar) > 0 ): ?> <div class="similar"> <h4>Similar Posts to <?php echo $base_post->title; ?></h4> <ul> <?php foreach($similar as $similar_post): ?> <li> <a href="<?php echo URL::get("display_post", array("slug" => $similar_post->slug)); ?>"> <?php echo $similar_post->title; ?> </a> </li> <?php endforeach; ?> </ul> </div> <?php endif; ?><file_sep><?php /** * An interface for search engines to be used by the * Habari multisearch plugin */ interface PluginSearchInterface { /** * Used to know whether we should overwrite * an existing database. */ const INIT_DB = 1; /** * Create the object, requires the index location. * * @param string $path */ public function __construct( $path ); /** * Check whether the preconditions for the plugin are installed * * @return boolean */ public function check_conditions(); /** * Initialise a writable database for updating the index * * @param int flag allow setting the DB to be initialised with PluginSearchInterface::INIT_DB */ public function open_writable_database( $flag = 0 ); /** * Prepare the database for reading */ public function open_readable_database(); /** * Return a list of IDs for the given search criters * * @param string $criteria * @param int $limit * @param int $offset * @return array */ public function get_by_criteria( $criteria, $limit, $offset ); /** * Add a post to the index. * * @param Post $post the post being inserted */ public function index_post( $post ); /** * Update a previously indexed post. * * @param Post $post */ public function update_post( $post ); /** * Remove a post from the index * * @param Post $post the post being deleted */ public function delete_post( $post ); /** * Return a list of post ids that are similar to the current post. * Backends that do not implement this should just return an empty * array. * @return array array of ids */ public function get_similar_posts( $post, $max_recommended = 5 ); /** * Return the spelling correction, if this exists. * * @return string */ public function get_corrected_query_string(); }<file_sep><?php class JWYSIWYG extends Plugin { /* * Required Plugin Information */ function info() { return array( 'name' => 'JWYSIWYG', 'license' => 'Apache License 2.0', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'version' => '0.6-0.4', 'description' => 'Publish posts using the JWYSIWYG editor.', 'copyright' => '2008' ); } public function action_admin_header($theme) { if ( $theme->page == 'publish' ) { Stack::add('admin_header_javascript', $this->get_url() . '/jwysiwyg/jquery.wysiwyg.js'); Stack::add('admin_stylesheet', array($this->get_url() . '/jwysiwyg/jquery.wysiwyg.css', 'screen')); } } public function action_admin_footer($theme) { if ( $theme->page == 'publish' ) { echo <<<JWYSIWYG <script type="text/javascript"> $('label[for=content]').text(''); $(function() { $('#content').wysiwyg(); }); habari.editor = { insertSelection: function(value) { var instance = $.data($('#content')[0], 'wysiwyg'); instance.setContent(instance.getContent() + value); } } </script> JWYSIWYG; } } public function action_update_check() { Update::add( 'JWYSIWYG', 'b5f0c17d-22e6-4d6c-8011-c79481d5efc7', $this->info->version ); } } ?> <file_sep><?php define( 'S9Y_IMPORT_BATCH', 100 ); define( 'S9Y_CONFIG_FILENAME', 'serendipity_config.inc.php'); /** * Serendipity Importer - Imports data from Serendipity into Habari * * @note Currently, this imports data from s9y versions 0.9 and up. * * @package Habari */ class S9YImport extends Plugin implements Importer { private $supported_importers = array(); /** A string that is displayed on trigger of a warning */ private $warning = null; /** HTML ID of the element to run AJAX import actions -- CURRENTLY NOT USED -- */ private $ajax_html_id = 'import_progress'; /** Connection to the s9y database to use during import */ private $s9ydb = null; /** The table prefix for the s9y tables (only used in the private import_xxx() functions */ private $s9y_db_prefix = 's9y_'; /** Cache for imported categories uses as a map from s9y to habari during import. */ private $imported_categories = array(); /** * Cache for imported category names */ protected $imported_category_names = array(); /** * List of already-rewritten categories (prevents duplicate rewrite rules) */ protected $rewritten_categories = array(); /** * Initialize plugin. * Set the supported importers. **/ public function action_init() { $this->supported_importers = array( _t( 'Serendipity Database' ) ); } /** * Return plugin metadata for this plugin * * @return array Plugin metadata */ public function info() { return array( 'name' => 'Serendipity Importer', 'version' => '1.0', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Import Serendipity 0.9+ database.', 'copyright' => '2008' ); } /** * Return a list of names of things that this importer imports * * @return array List of importables. */ public function filter_import_names( $import_names ) { return array_merge( $import_names, $this->supported_importers ); } /** * Plugin filter that supplies the UI for the WP importer * * @param string $stageoutput The output stage UI * @param string $import_name The name of the selected importer * @param string $stage The stage of the import in progress * @param string $step The step of the stage in progress * @return output for this stage of the import */ public function filter_import_stage( $stageoutput, $import_name, $stage, $step ) { // Only act on this filter if the import_name is one we handle... if( !in_array( $import_name, $this->supported_importers ) ) // Must return $stageoutput as it may contain the stage HTML of another importer return $stageoutput; if ( isset( $_POST ) ) $stage = (int) $stage + 1; /* Note that we do the error checking in the stageX() methods, not here... */ $stage_method = 'stage' . $stage; if ( method_exists( $this, $stage_method ) ) return $this->$stage_method(); return FALSE; } /** * Create the UI for stage one of the WP import process * * Stage 1 is responsible for gathering the required input * from the importing user that will be used in the import * process as well as displaying errors for invalid or missing * required information. * * @return string The UI for the first stage of the import process */ private function stage1() { $valid_fields = array( 'db_name' , 'db_host' , 'db_port' , 'db_user' , 'db_pass' , 'db_prefix' , 's9y_version' , 's9y_root_web' , 's9y_input_version' , 'category_import' , 'comments_ignore_unapproved' , 'rewrites_import' ); $inputs = $this->get_valid_inputs( $valid_fields ); $default_values = array( 'db_name' => '' , 'db_host' => 'localhost' , 'db_port' => null , 'db_user' => '' , 'db_pass' => '' , 'db_prefix' => 's9y_' , 'warning' => '' , 'category_import' => 1 , 'comments_ignore_unapproved' => 1 , 'rewrites_import' => 1 , 's9y_root_web' => '' , 's9y_input_version' =>'' ) ; $inputs = array_merge( $default_values, $inputs ); extract( $inputs ); $warning = ''; if( ! empty( $this->warning ) ) $warning = $this->get_warning_html( $this->warning ); $output =<<<WP_IMPORT_STAGE1 <h3>Habari will attempt to import from a Serendipity Database.</h3> {$warning} <p> Please specify the version of Serendipity to be imported <strong>OR</strong> specify the location of the root web directory where we can find the Serendipity configuration file to gather version information: </p> <table> <tr><td>Version:</td><td><input type="text" name="s9y_input_version" value="{$s9y_input_version}"></td></tr> <tr><td>&nbsp;<strong>OR</strong> Web directory root where s9y is installed:</td><td><input type="text" name="s9y_root_web" value="{$s9y_root_web}"></td></tr> </table> <p>Please provide the connection details for an existing Serendipity database:</p> <table> <tr><td>Database Name</td><td><input type="text" name="db_name" value="{$db_name}"></td></tr> <tr><td>Database Host</td><td><input type="text" name="db_host" value="{$db_host}"></td></tr> <tr><td>Database Port</td><td><input type="text" name="db_port" value="{$db_port}">(optional)</td></tr> <tr><td>Database User</td><td><input type="text" name="db_user" value="{$db_user}"></td></tr> <tr><td>Database Password</td><td><input type="password" name="db_pass" value="{$db_pass}"></td></tr> <tr><td>Table Prefix</td><td><input type="text" name="db_prefix" value="{$db_prefix}"></td></tr> </table> <p> Please specify any import options you would like: </p> <table> <tr><td>Import Serendipity Categories as Tags?</td><td><input type="checkbox" name="category_import" value="1" checked="true"></td></tr> <tr><td>Ignore Unapproved Comments?</td><td><input type="checkbox" name="comments_ignore_unapproved" value="1" checked="true"></td></tr> <tr><td>Port rewrites?</td><td><input type="checkbox" name="rewrites_import" value="1" checked="true"></td></tr> </table> <input type="hidden" name="stage" value="1"> <p class="submit"><input type="submit" name="import" value="Proceed with Import" /></p> WP_IMPORT_STAGE1; return $output; } /** * Create the UI for stage two of the WP import process * * This stage verifies the initial configuration values and then * proceeds to gather information about the potentially imported * data and display some confirmation information. If missing or * invalid information was given, this method returns the output * from stage1() * * @return string The UI for the second stage of the import process */ private function stage2() { $valid_fields = array( 'db_name' , 'db_host' , 'db_port' , 'db_user' , 'db_pass' , 'db_prefix' , 's9y_version' , 's9y_root_web' , 's9y_input_version' , 'category_import' , 'comments_ignore_unapproved' , 'rewrites_import' ); $inputs = $this->get_valid_inputs( $valid_fields ); extract( $inputs ); /* Verify required and expected values from input */ if ( isset( $comments_ignore_unapproved) ) $comments_ignore_unapproved = 1; if ( isset( $category_import ) ) $category_import = 1; if ( isset( $rewrites_import ) ) $rewrites_import = 1; if ( empty( $s9y_input_version ) && empty( $s9y_root_web ) ) { /* * We need either the version or the config file * location to determine version of DB */ $this->warning = 'Please enter either a location to find the s9y configuration file (root web directory for s9y) OR the version of s9y to import'; return $this->stage1(); } if ( empty( $db_host ) ) { $this->warning = 'Please enter a value for the database host.'; return $this->stage1(); } if ( empty( $db_name ) ) { $this->warning = 'Please enter a name for the database to import.'; return $this->stage1(); } if ( empty( $db_user ) ) { $this->warning = 'Please enter a database username.'; return $this->stage1(); } if ( FALSE == ($s9ydb = $this->s9y_connect( $db_host, $db_name, $db_user, $db_pass, $db_prefix, $db_port ) ) ) { $this->warning = 'A connection to the specified database could not be created. Please check the values you provided.'; return $this->stage1(); } /* * OK, now calculate some information about the imported data that * we can show to the user in the confirmation screen */ $num_imported_posts = $s9ydb->get_value( "SELECT COUNT(*) FROM `{$db_prefix}entries`" ); $comment_where = ''; if ( $comments_ignore_unapproved == 1 ) $comment_where = "WHERE status = 'Approved' "; $num_imported_comments = $s9ydb->get_value( "SELECT COUNT(*) FROM `{$db_prefix}comments`" . $comment_where); /* * Users are important during import. We want to show the importer that * we have identified X number of posting users (authors) and give the importer * the ability to choose which authors they wish to import. During this * step, let's try to map an incoming (imported) author to an existing Habari * user... */ $user_sql =<<<ENDOFSQL SELECT e.authorid, e.author, a.realname, a.username, a.email,COUNT(*) as num_posts FROM `{$db_prefix}entries` e INNER JOIN `{$db_prefix}authors` a ON e.authorid = a.authorid GROUP BY e.authorid, e.author ENDOFSQL; $imported_users = $s9ydb->get_results( $user_sql ); $num_imported_users = count( $imported_users ); /* Grab the categories from s9y to use as tags in Habari */ $num_imported_tags = 0; if ( $category_import == 1 ) $num_imported_tags = $s9ydb->get_value( "SELECT COUNT(*) FROM `{$db_prefix}category`" ); $output =<<<WP_IMPORT_STAGE2 <h3>To be imported</h3> <p> We have identified information that will be imported into Habari. Please review the information below and continue with the import. </p> <div><strong>Found authors to be imported:</strong>&nbsp;{$num_imported_users} WP_IMPORT_STAGE2; if ( $num_imported_users > 0 ) { $output.=<<<WP_IMPORT_STAGE2 <div style="margin-left: 20px; padding 10px;"> <p>Check which users (and their posts) you wish to import</p> <table> <tr><th>Import?</th><th>Author Name</th><th>Email</th><th>Num Posts</th><th>Match in Habari?</th></tr> WP_IMPORT_STAGE2; foreach ($imported_users as $user) { $output.= "<tr><td><input type='checkbox' name='import_user[{$user->authorid}]' value='1' checked='true' /></td>" . "<td>{$user->realname}</td><td>{$user->email}</td><td>{$user->num_posts}</td><td>&nbsp;"; $user_table_name = DB::table('users'); $match_sql =<<<ENDOFSQL SELECT id, username, email FROM {$user_table_name} WHERE email = ? OR username = ? ENDOFSQL; $match_params = array( $user->email, $user->username ); $habari_matched_users = DB::get_results( $match_sql, $match_params, 'User' ); if ( count( $habari_matched_users ) > 0 ) { $output.= "<strong>Match found for habari user:</strong>&nbsp;"; $matched_user = $habari_matched_users[0]; /* Just take the first match... */ $output.= $matched_user->username . "<input type=\"hidden\" name=\"merge_user_matched[{$user->authorid}]\" value=\"{$matched_user->id}\" />"; } else { /* No matches. Allow importer to select a merged user account */ $all_habari_users = Users::get_all(); if ( isset( $all_habari_user_select ) ) $output.= $all_habari_user_select; else { $all_habari_user_select = "<select name='merge_user[{$user->authorid}]'>"; $all_habari_user_select.= "<option value='__new_user' selected='true'>Create a new user</option>"; foreach ( $all_habari_users as $habari_user ) $all_habari_user_select.= "<option value='{$habari_user->id}'>Merge with {$habari_user->username}</option>"; $output.= $all_habari_user_select; } } $output.= "</td></tr>"; } $output.= "</table></div>"; } /* End num_imported_users > 0 */ else { /* No authors found to import. Display nothing to import and stop process */ $output.= "</div>"; return $output; } $output.=<<<WP_IMPORT_STAGE2 </div> <div><strong>Found Blog Posts to be imported:</strong>&nbsp;{$num_imported_posts}</div> <div><strong>Comments to be imported:</strong>&nbsp;{$num_imported_comments}</div> WP_IMPORT_STAGE2; if ( $category_import == 1 ) { $output.=<<<WP_IMPORT_STAGE2 <div><strong>Tags to be imported:</strong>&nbsp;{$num_imported_tags}</div> WP_IMPORT_STAGE2; } if ( $rewrites_import == 1 ) { $output.=<<<WP_IMPORT_STAGE2 <div><strong>Porting Rewrites.</strong></div> WP_IMPORT_STAGE2; } foreach ( $inputs as $key=>$value ) $output.= "<input type='hidden' name='{$key}' value='" . htmlentities($value) . "' />"; $output.=<<<WP_IMPORT_STAGE2 <input type="hidden" name="stage" id="stage" value="2"> <p class="submit"> <input type="submit" name="import" value="Continue Import >>" /></p> WP_IMPORT_STAGE2; return $output; } /** * Create the UI for stage two of the WP import process * * This stage kicks off the actual import process. * * @return string The UI for the second stage of the import process */ private function stage3() { $valid_fields = array( 'db_name' , 'db_host' , 'db_port' , 'db_user' , 'db_pass' , 'db_prefix' , 's9y_version' , 's9y_root_web' , 's9y_input_version' , 'category_import' , 'comments_ignore_unapproved' , 'rewrites_import' , 'merge_user' , 'merge_user_matched' , 'import_user' ); $inputs = $this->get_valid_inputs( $valid_fields ); extract( $inputs ); /* * Cache some local private variables for use in * the import_xxx() private functions */ $this->comments_ignore_unapproved = $comments_ignore_unapproved; $this->category_import = $category_import; $this->s9y_db_prefix = $db_prefix; $this->port_rewrites = $rewrites_import; if ( $rewrites_import ) { // atom feed link: $rew_url = URL::get( 'atom_feed', array( 'index' => 1 ), true, false, false ); $rewrite = new RewriteRule( array( 'name' => 'from_s9yimporter_atom_feed', 'parse_regex' => '%^feeds/atom(?P<r>.*)$%i', 'build_str' => $rew_url . '(/{$p})', 'handler' => 'actionHandler', 'action' => 'redirect', 'priority' => 1, 'is_active' => 1, 'rule_class' => RewriteRule::RULE_CUSTOM, 'description' => 'redirects s9y atom feed to habari feed', ) ); $rewrite->insert(); // rss feed link: $rew_url = Plugins::is_loaded( 'RSS 2.0' ) ? URL::get( 'rss_feed', array( 'index' => 1 ), true, false, false ) : URL::get( 'atom_feed', array( 'index' => 1 ), true, false, false ); $rewrite = new RewriteRule( array( 'name' => 'from_s9yimporter_rss_feed', 'parse_regex' => '%^feeds/index.rss(?P<r>.*)$%i', 'build_str' => $rew_url . '(/{$p})', 'handler' => 'actionHandler', 'action' => 'redirect', 'priority' => 1, 'is_active' => 1, 'rule_class' => RewriteRule::RULE_CUSTOM, 'description' => 'redirects s9y rss feed to habari feed', ) ); $rewrite->insert(); // comments feed link: $rew_url = Plugins::is_loaded( 'RSS 2.0' ) ? URL::get( 'rss_feed_comments', array( ), true, false, false ) : URL::get( 'atom_feed_comments', array( ), true, false, false ); $rewrite = new RewriteRule( array( 'name' => 'from_s9yimporter_comments_feed', 'parse_regex' => '%^feeds/comments.rss(?P<r>.*)$%i', 'build_str' => $rew_url . '(/{$p})', 'handler' => 'actionHandler', 'action' => 'redirect', 'priority' => 1, 'is_active' => 1, 'rule_class' => RewriteRule::RULE_CUSTOM, 'description' => 'redirects s9y rss feed to habari feed', ) ); $rewrite->insert(); } if ( FALSE !== ( $this->s9ydb = $this->s9y_connect( $db_host, $db_name, $db_user, $db_pass, $db_prefix, $db_port ) ) ) { /* * First step is to go through our import_user and * merge_user arrays and see if we need to merge the * incoming authoring user with an existing user in * Habari, ignore the user, or create a new Habari user. * * $import_user= array( [imported_user_id] => [1 | null], [next_imported_user_id] => [1 | null], ...) * $merge_user= array( [imported_user_id] => [habari_user_id | "__new_user"], ...) */ $users = array(); foreach ( $import_user as $import_user_id=>$import_this ) { /* Is this s9y user selected for import? */ if ( $import_this != 1 ) continue; $users[$import_user_id]= array('imported_user_id'=>$import_user_id); /* Was there a direct match for this imported user? */ if ( in_array( $import_user_id, array_keys( $merge_user_matched ) ) ) $users[$import_user_id]['habari_user_id']= $merge_user_matched[$import_user_id]; /* Is this s9y user manually selected to merge with a habari user? */ if ( isset($merge_user) && in_array( $import_user_id, array_keys( $merge_user ) ) ) if ( $merge_user[$import_user_id] != '__new_user') $users[$import_user_id]['habari_user_id']= $merge_user[$import_user_id]; } echo "Starting import transaction.<br />"; $this->s9ydb->begin_transaction(); if ( $category_import ) { /* * If we are importing the categories as taxonomy, * let's go ahead and import the base category tags * now, and during the post import, we'll attach * the category tag to the relevant posts. * * mysql> desc s9y_category; * +----------------------+--------------+------+-----+---------+----------------+ * | Field | Type | Null | Key | Default | Extra | * +----------------------+--------------+------+-----+---------+----------------+ * | categoryid | int(11) | | PRI | NULL | auto_increment | * | category_name | varchar(255) | YES | | NULL | | * | category_icon | varchar(255) | YES | | NULL | | * | category_description | text | YES | | NULL | | * | authorid | int(11) | YES | MUL | NULL | | * | category_left | int(11) | YES | MUL | 0 | | * | category_right | int(11) | YES | | 0 | | * | parentid | int(11) | | MUL | 0 | | * +----------------------+--------------+------+-----+---------+----------------+ */ $sql =<<<ENDOFSQL SELECT categoryid, category_name FROM `{$db_prefix}category ENDOFSQL; if ( FALSE !== ( $imported_categories = $this->s9ydb->get_results( $sql, array(), 'QueryRecord' ) ) ) { $num_categories_imported = 0; foreach ( $imported_categories as $imported_category ) { if ( $tag_check = Tags::get_one( $imported_category->category_name ) ) { // tag already exists $this->imported_categories[$imported_category->categoryid]= $tag_check->id; $this->imported_category_names[$imported_category->categoryid] = $imported_category->category_name; ++$num_categories_imported; continue; } if ( $new_tag = Tag::create( array( 'tag_text' => $imported_category->category_name ) ) ) { $this->imported_categories[$imported_category->categoryid]= $new_tag->id; $this->imported_category_names[$imported_category->categoryid] = $imported_category->category_name; ++$num_categories_imported; } else { $this->s9ydb->rollback(); return FALSE; } } printf("%d categories imported as tags...<br />", $num_categories_imported); } } /* * Now that we have an array of the users to import, * let's grab some information about those users and * call the import_user() method for each one. * * mysql> desc s9y_authors; * +-----------------+-----------------+------+-----+---------+----------------+ * | Field | Type | Null | Key | Default | Extra | * +-----------------+-----------------+------+-----+---------+----------------+ * | realname | varchar(255) | NO | | | | * | username | varchar(20) | YES | | NULL | | * | password | varchar(32) | YES | | NULL | | * | authorid | int(11) | NO | PRI | NULL | auto_increment | * | mail_comments | int(1) | YES | | 1 | | * | mail_trackbacks | int(1) | YES | | 1 | | * | email | varchar(128) | NO | | | | * | userlevel | int(4) unsigned | NO | | 0 | | * | right_publish | int(1) | YES | | 1 | | * +-----------------+-----------------+------+-----+---------+----------------+ */ $sql =<<<ENDOFSQL SELECT a.authorid, a.realname, a.username, a.email FROM `{$db_prefix}authors` a ENDOFSQL; $sql.= " WHERE a.authorid IN (" . implode(',', array_keys($users)) . ")"; $import_users = $this->s9ydb->get_results( $sql, array(), 'QueryRecord' ); $result = TRUE; foreach ($import_users as $import_user) $result&= $this->import_user( $import_user->authorid , $import_user , ( isset ( $users[$import_user->authorid]['habari_user_id'] ) ? (int) $users[$import_user->authorid]['habari_user_id'] : NULL ) ); if ( $result ) { echo "Committing import transaction.<br />"; $this->s9ydb->commit(); return "import finished."; /* Display success */ } else { echo "Rolling back failed import transaction.<br />"; $this->s9ydb->rollback(); /* Display failure -- but how..? */ return FALSE; } } } /** * Imports a single user from the s9y database into the * habari database. * * Note that this function either creates a new habari * user account or uses an existing habari account (merges). * * Also note that this function is the start of the import * process for a user and will call import_post() for each * of the user's posts, which in turn calls import_comment() * for each of that post's comments. * * @param import_user_id ID in s9y database for this user * @param habari_user_id ID of habari user to merge or * NULL for new account * @param import_user_info QueryRecord of imported user information * @return TRUE or FALSE if import of user succeeded */ private function import_user( $import_user_id, $import_user_info = array(), $habari_user_id = NULL ) { /* * We either grab the user to merge with or create * a new one, depending on if $habari_user_id is null * or not... */ if ( is_null( $habari_user_id ) ) { /* New habari user account */ $habari_user = new User(); $habari_user->email = $import_user_info->email; $habari_user->username = $import_user_info->username; $habari_user->info->s9y_id = $import_user_info->authorid; $habari_user->info->s9y_realname = $import_user_info->realname; } else { $habari_user = User::get_by_id($habari_user_id); $habari_user->info->s9y_id = $import_user_info->authorid; $habari_user->info->s9y_realname = $import_user_info->realname; } try { if ( is_null( $habari_user_id ) ) $habari_user->insert(); else { echo "Merging s9y user \"<b>{$import_user_info->username}</b>\" into Habari user with email: " . $habari_user->email; if ($habari_user->update()) echo "...merge " . $this->success_html() . "<br />"; else echo "...merge " . $this->fail_html() . "<br />"; } } catch( Exception $e ) { /** @TODO: This should be a specific exception, not the general one... */ EventLog::log( $e->getMessage(), 'err', null, null, print_r( array( $habari_user, $e ), 1 ) ); Session::error( $e->getMessage() ); return FALSE; } /* * If we are here, the user has been inserted/updated, and so * we proceed with adding the imported user's posts, attaching * them to the user just created or updated. * mysql> desc s9y_entries; * +-------------------+----------------------+------+-----+---------+----------------+ * | Field | Type | Null | Key | Default | Extra | * +-------------------+----------------------+------+-----+---------+----------------+ * | id | int(11) | | PRI | NULL | auto_increment | * | title | varchar(200) | YES | MUL | NULL | | * | timestamp | int(10) unsigned | YES | MUL | NULL | | * | body | text | YES | | NULL | | * | comments | int(4) unsigned | YES | | 0 | | * | trackbacks | int(4) unsigned | YES | | 0 | | * | extended | text | YES | | NULL | | * | exflag | int(1) | YES | | NULL | | * | author | varchar(20) | YES | | NULL | | * | authorid | int(11) | YES | MUL | NULL | | * | isdraft | enum('true','false') | | MUL | true | | * | allow_comments | enum('true','false') | | | true | | * | last_modified | int(10) unsigned | YES | MUL | NULL | | * | moderate_comments | enum('true','false') | | | true | | * +-------------------+----------------------+------+-----+---------+----------------+ * */ $sql =<<<ENDOFSQL SELECT e.id , e.extended , e.body , e.title , e.`timestamp` , e.last_modified , e.isdraft FROM {$this->s9y_db_prefix}entries e WHERE e.authorid = ? ENDOFSQL; $posts = $this->s9ydb->get_results( $sql, array($import_user_id), 'QueryRecord' ); if ( count( $posts ) > 0 ) { $result = TRUE; echo "Starting import of <b>" . count( $posts ) . "</b> posts...<br/ >"; foreach ( $posts as $post ) $result&= $this->import_post( $post, $habari_user->id ); if ( $result ) echo $this->success_html() . "<br />"; else echo $this->fail_html() . "<br />"; return $result; } else { echo "No posts to import for {$import_user_info->username}.<br />"; return TRUE; } } /** * Imports a single post from the s9y database into the * habari database. * * Note that this function calls import_comment() for each * comment attached to the imported post * * @param post_info QueryRecord of imported post information * @param habari_user_id The habari user ID of the post's author * @return TRUE or FALSE if import of post succeeded */ private function import_post( $post_info = array(), $habari_user_id ) { /* * Import the post itself */ $post = new Post(); $post->user_id = $habari_user_id; $post->guid = $post->guid; /* @TODO: This works to create a GUID, but man, it's weird. */ $post->info->s9y_id = $post_info->id; $post->title = $this->transcode( $post_info->title ); $content = ( empty( $post_info->extended ) ? $post_info->body : $post_info->body . $post_info->extended ); $post->content = $this->transcode( $content ); $post->status = ( $post_info->isdraft == "true" ? Post::status( 'draft' ) : Post::status( 'published' ) ); $post->content_type = Post::type( 'entry' ); $post->updated = date('Y-m-d H:i:s', $post_info->last_modified); $post->pubdate = ( $post_info->isdraft == "false" ? date( 'Y-m-d H:i:s', $post_info->timestamp ) : NULL ); if ( $this->category_import && isset ( $categories ) && $categories instanceof QueryRecord ) $post->tags = $categories->to_array(); if ( $post->insert() ) { if ( $this->port_rewrites ) { $rewrite = new RewriteRule( array( 'name' => 'from_s9yimporter_' . $post_info->id, 'parse_regex' => '%^archives/' . $post_info->id . '-(?P<r>.*)$%i', 'build_str' => $post->slug . '(/{$p})', 'handler' => 'actionHandler', 'action' => 'redirect', 'priority' => 1, 'is_active' => 1, 'rule_class' => RewriteRule::RULE_CUSTOM, 'description' => 'redirects /archives/' . $post_info->id .' to /' . $post->slug, ) ); $rewrite->insert(); } /* * If we are going to import taxonomy, , then first check to see if * this post has any categories attached to it, and import the relationship * using the cached habari->s9y tag map. * * mysql> desc s9y_entrycat; * +------------+---------+------+-----+---------+-------+ * | Field | Type | Null | Key | Default | Extra | * +------------+---------+------+-----+---------+-------+ * | entryid | int(11) | NO | PRI | 0 | | * | categoryid | int(11) | NO | PRI | 0 | | * +------------+---------+------+-----+---------+-------+ */ $result = TRUE; if ( $this->category_import ) { $sql =<<<ENDOFSQL SELECT c.categoryid FROM {$this->s9y_db_prefix}category c INNER JOIN {$this->s9y_db_prefix}entrycat ec ON c.categoryid = ec.categoryid AND ec.entryid = ? ENDOFSQL; if ( FALSE !== ( $categories = $this->s9ydb->get_results( $sql, array( $post_info->id ), 'QueryRecord' ) ) ) { foreach ( $categories as $category ) { $result&= $this->import_post_category( $post->id, $this->imported_categories[$category->categoryid] ); if ( $this->port_rewrites && !isset( $this->rewritten_categories[ $category->categoryid ] ) ) { // rss feed link: $this->rewritten_categories[ $category->categoryid ] = 1; $rew_url = URL::get( 'atom_feed_tag', array( 'tag' => $this->imported_category_names[ $category->categoryid ] ), true, false, false ); $rewrite = new RewriteRule( array( 'name' => 'from_s9yimporter_category_feed', 'parse_regex' => '%^feeds/categories/' . $category->categoryid . '-(?P<r>.*)$%i', 'build_str' => $rew_url . '(/{$p})', 'handler' => 'actionHandler', 'action' => 'redirect', 'priority' => 1, 'is_active' => 1, 'rule_class' => RewriteRule::RULE_CUSTOM, 'description' => 'redirects s9y category feed to habari feed', ) ); $rewrite->insert(); } } } } /* * Grab the comments and insert `em * * mysql> desc s9y_comments; * +------------+----------------------+------+-----+---------+----------------+ * | Field | Type | Null | Key | Default | Extra | * +------------+----------------------+------+-----+---------+----------------+ * | id | int(11) | NO | PRI | NULL | auto_increment | * | entry_id | int(10) unsigned | NO | MUL | 0 | | * | parent_id | int(10) unsigned | NO | MUL | 0 | | * | timestamp | int(10) unsigned | YES | | NULL | | * | title | varchar(150) | YES | | NULL | | * | author | varchar(80) | YES | | NULL | | * | email | varchar(200) | YES | | NULL | | * | url | varchar(200) | YES | | NULL | | * | ip | varchar(15) | YES | | NULL | | * | body | text | YES | | NULL | | * | type | varchar(100) | YES | MUL | regular | | * | subscribed | enum('true','false') | NO | | true | | * | status | varchar(50) | NO | MUL | | | * | referer | varchar(200) | YES | | NULL | | * +------------+----------------------+------+-----+---------+----------------+ */ $sql =<<<ENDOFSQL SELECT id , parent_id , `timestamp` , title , author , email , url , ip , body , type , subscribed , status , referer FROM {$this->s9y_db_prefix}comments WHERE entry_id = ? ENDOFSQL; if ( $this->comments_ignore_unapproved ) $sql.= " AND status = 'Approved' "; $comments = $this->s9ydb->get_results( $sql, array( $post_info->id ), 'QueryRecord' ); if ( count( $comments ) > 0 ) { echo "Starting import of <b>" . count( $comments ) . "</b> comments for post \"" . $post->title . "\"..."; foreach ( $comments as $comment ) $result&= $this->import_comment( $comment, $post->id ); if ( $result ) echo $this->success_html() . "<br />"; else echo $this->fail_html() . "<br />"; return $result; } else return TRUE; } else { /* Something went wrong on $post->insert() */ EventLog::log($e->getMessage(), 'err', null, null, print_r(array($post, $e), 1)); Session::error( $e->getMessage() ); return FALSE; } } /** * Imports a single category from the s9y database into the * habari database * * @param post_id ID of the new Habari post to attach tag to * @param tag_id ID of the Habari tag to attach the post to * @return TRUE or FALSE if import of tag2post relationship succeeded */ private function import_post_category( $post_id, $tag_id ) { if ( Tag::attach_to_post( $tag_id, $post_id ) ) return TRUE; else { EventLog::log($e->getMessage(), 'err', null, null, print_r(array($tag_id, $post_id, $e), 1)); Session::error( $e->getMessage() ); return FALSE; } } /** * Imports a single comment from the s9y database into the * habari database * * @param comment_info QueryRecord of comment information to import * @param habari_post_id ID of the post to attach the comment to * @return TRUE or FALSE if import of comment succeeded */ private function import_comment( $comment_info = array(), $habari_post_id ) { /* A mapping for s9y comment status to habari comment status codes */ $status_map = array( 'APPROVED'=> Comment::STATUS_APPROVED , 'PENDING'=> Comment::STATUS_UNAPPROVED ); /* A mapping for s9y comment type to habari comment type codes */ $type_map = array( 'TRACKBACK'=> Comment::TRACKBACK , 'NORMAL'=> Comment::COMMENT ); $comment = new Comment(); $comment->post_id = $habari_post_id; $comment->info->s9y_id = $comment_info->id; if ( ! empty( $comment_info->parent_id ) && $comment_info->parent_id != "0" ) $comment->info->s9y_parent_id = $comment_info->parent_id; $comment->ip = sprintf ("%u", ip2long($comment_info->ip) ); $comment->status = $status_map[strtoupper($comment_info->status)]; $comment->type = $type_map[strtoupper($comment_info->type)]; $comment->name = $this->transcode( $comment_info->author ); $comment->url = $comment_info->url; $comment->date = date('Y-m-d H:i:s', $comment_info->timestamp); $comment->email = $this->transcode( $comment_info->email ); $comment->content = $this->transcode( $comment_info->body ); if ( $comment->insert() ) return TRUE; else { EventLog::log($e->getMessage(), 'err', null, null, print_r(array($comment, $e), 1)); Session::error( $e->getMessage() ); return FALSE; } } /** * Utility method for stripping out POSTed fields that * are not valid for a particular stage. * * @param valid_fields Array of field names that are valid * @return cleaned array */ private function get_valid_inputs( $valid_fields ) { return array_intersect_key( $_POST, array_flip( $valid_fields ) ); } /** * Return a string with the warning message formatted * for HTML output * * @param message Warning message string * @return string of HTML */ private function get_warning_html( $message ) { return "<p style=\"color: red;\" class=\"warning\">{$message}</p>"; } /** * Tries to get and cache the version of s9y by retrieving the configuration * file that Serendipity uses to store the version of software running on the * host * * @param array inputs from POST, cleaned. * @return string version of s9y */ private function get_s9y_version( $inputs ) { if (array_key_exists('s9y_version', array_values($inputs))) return $inputs['s9y_version']; /* Try to find the version from the s9y configuration file */ if (! isset($inputs['s9y_root_web'])) { $this->add_error('Please provide a root web directory for finding the s9y cnfiguration file.'); return false; } else $root_web = rtrim($input['s9y_root_web'], ' ' . DIRECTORY_SEPARATOR); $config_file = $root_web . DIRECTORY_SEPARATOR . S9Y_CONFIG_FILENAME; if (! is_readable($config_file)) { $this->add_error('The configuration file for s9y (' . $config_file . ') is not readable.'); return false; } /* Pull in the configuration file and grab the version information from it */ $config_file_contents = file_get_contents($config_file); $matches = array(); if (1 == preg_match("/^\$serendipity\[\'version\'\]\s+\=\s+\'([^']+)\'", $config_file_contents, $matches)) $version = $matches[1]; else { $this->add_error('No version information found in s9y configuration file'); return false; } return $version; } /** * Attempt to connect to the Serendipity database * * @param string $db_host The hostname of the WP database * @param string $db_name The name of the WP database * @param string $db_user The user of the WP database * @param string $db_pass The user's password for the WP database * @param string $db_prefix The table prefix for the WP instance in the database * @param string $db_port The port number of the WP database * @return mixed false on failure, DatabseConnection on success */ private function s9y_connect( $db_host, $db_name, $db_user, $db_pass, $db_prefix, $db_port = null) { // Connect to the database or return false try { $s9ydb = new DatabaseConnection(); $connect_str = "mysql:host={$db_host};dbname={$db_name}"; if ( !is_null( $db_port ) ) { $connect_str .= ";port={$db_port}"; } $s9ydb->connect( $connect_str, $db_user, $db_pass, $db_prefix ); return $s9ydb; } catch( PDOException $e ) { return FALSE; } } private function success_html() { return "<b style=\"color: green;\">" . _t( "succeeded" ) . "</b>"; } private function fail_html() { return "<b style=\"color: red;\">" . _t( "failed" ) . "</b>"; } protected function transcode( $content ) { return iconv( 'Windows-1252', 'UTF-8', $content ); } } ?> <file_sep><ul class="tag-cloud"> <?php foreach ( $taglist as $tag ): ?> <li><a href="<?php echo URL::get( 'display_entries_by_tag', array( 'tag' => $tag->slug ) ); ?>" title="<?php echo $tag->tag; ?>" rel="tag" style="font-size: 125%;"><?php echo $tag->tag; ?></a></li> <?php endforeach; ?> </ul> <file_sep><span>Subpages:</span> <?php $out = array(); foreach ( $subpages as $subpage ) { $out[] = "<a href='{$subpage->permalink}'>{$subpage->title}</a>"; } echo join(' | ', $out); ?> <file_sep><div id="ohloh_badge"> <?php echo $ohloh_badge; ?> </div> <file_sep><?php require('linkhandler.php'); require('linkdatabase.php'); class LinkBlog extends Plugin { /** * Create help file */ public function help() { $str= ''; $str.= '<p>LinkBlog allows you to create posts with specific links attached to them.</p>'; $str.= '<h3>Installation Instructions</h3>'; $str.= '<p>Your theme needs to have a <code>link.single</code> template, or a generic <code>single</code> template. If it does not, you can usually copy <code>entry.single</code> to <code>link.single</code> and use it.</p>'; return $str; } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t('Configure'); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure') : $ui = new FormUI( strtolower( get_class( $this ) ) ); $ui->append( 'text', 'original_text', 'linkblog__original', _t('Text to use for describing original in feeds:') ); $ui->append( 'checkbox', 'atom_permalink', 'linkblog__atom_permalink', _t('Override atom permalink with link URL') ); $ui->append( 'submit', 'save', _t('Save') ); $ui->out(); break; } } } /** * Add update beacon support **/ public function action_update_check() { Update::add( $this->info->name, '517e7fb2-77de-20b4-1996-feccd13ea0ba', $this->info->version ); } /** * Register content type **/ public function action_plugin_activation( $plugin_file ) { self::install(); } public function action_plugin_deactivation( $plugin_file ) { Post::deactivate_post_type( 'link' ); } /** * install various stuff we need */ static public function install() { Post::add_new_type( 'link' ); // Give anonymous users access $group = UserGroup::get_by_name('anonymous'); $group->grant('post_link', 'read'); // Set default settings Options::set('linkblog__original', '<p><a href="{permalink}">Permalink</a></p>'); Options::set('linkblog__atom_permalink', false); self::database(); } /** * install database */ static public function database() { $q = 'CREATE TABLE IF NOT EXISTS ' . DB::table('link_traffic') . '( `id` int(10) unsigned NOT NULL auto_increment, `post_id` int(10) unsigned NOT NULL, `date` int(10) unsigned NOT NULL, `type` int(5) unsigned NOT NULL, `ip` int(10) unsigned default NULL, `referrer` varchar(255) default NULL, PRIMARY KEY (`id`) );'; return DB::dbdelta( $q ); } /** * Register templates **/ public function action_init() { // Create templates $this->add_template('link.single', dirname(__FILE__) . '/link.single.php'); // register tables DB::register_table('link_traffic'); // Add rewrite rules $this->add_rule('"link"/"redirect"/slug', 'link_redirect'); self::database(); } /** * Redirect a link to its original destination **/ public function action_plugin_act_link_redirect($handler) { $slug= $handler->handler_vars['slug']; $post= Post::get(array('slug' => $slug)); if($post == FALSE) { $handler->theme->display('404'); exit; } $type= Traffum::TYPE_SEND_NORMAL; if(isset($handler->handler_vars['refer']) && $handler->handler_vars['refer'] == 'atom') { $type= Traffum::TYPE_SEND_ATOM; } Traffum::create(array('post_id' => $post->id, 'type' => $type)); Utils::redirect($post->info->url); exit; } /** * Create name string **/ public function filter_post_type_display($type, $foruse) { $names = array( 'link' => array( 'singular' => _t('Link'), 'plural' => _t('Links'), ) ); return isset($names[$type][$foruse]) ? $names[$type][$foruse] : $type; } /** * Modify publish form */ public function action_form_publish($form, $post) { if ($post->content_type == Post::type('link')) { $url= $form->append('text', 'url', 'null:null', _t('URL'), 'admincontrol_text'); $url->value= $post->info->url; $form->move_after($url, $form->title); } } /** * Initiate tracking on display */ function action_add_template_vars( $theme ) { static $set= false; if($set == true || !is_object($theme->matched_rule) || $theme->matched_rule->action != 'display_post' || $theme->post->content_type != Post::type('link')) { return; } $post= $theme->post; $type= Traffum::TYPE_VIEW_NORMAL; if(Controller::get_var('refer') != NULL && Controller::get_var('refer') == 'atom') { $type= Traffum::TYPE_VIEW_ATOM; } Traffum::create(array('post_id' => $post->id, 'type' => $type)); $set= true; } /** * Save our data to the database */ public function action_publish_post( $post, $form ) { if ($post->content_type == Post::type('link')) { $this->action_form_publish($form, $post); $post->info->url= $form->url->value; } } public function filter_post_link($permalink, $post) { if($post->content_type == Post::type('link')) { return self::get_redirect_url($post); } else { return $permalink; } } public function filter_post_permalink_atom($permalink, $post) { if($post->content_type == Post::type('link')) { if(Options::get('linkblog__atom_permalink') == TRUE) { return self::get_redirect_url($post, 'atom'); } } return $permalink; } public static function get_redirect_url($post, $context = NULL) { $params= array('slug' => $post->slug); if(isset($context) && $context == 'atom') { $params['refer']= 'atom'; } $url= URL::get('link_redirect', $params); return $url; } public static function get_permalink_url($post, $context = NULL) { $url= $post->permalink; if(isset($context) && $context == 'atom') { $url.= '?refer=atom'; } return $url; } public function filter_post_content_atom($content, $post) { if($post->content_type == Post::type('link')) { $text= Options::get('linkblog__original'); $text= str_replace('{original}', self::get_redirect_url($post, 'atom'), $text); $text= str_replace('{permalink}', self::get_permalink_url($post, 'atom'), $text); return $content . $text; } else { return $content; } } /** * Add the posts to the blog home */ public function filter_template_user_filters($filters) { if(isset($filters['content_type'])) { $filters['content_type']= Utils::single_array( $filters['content_type'] ); $filters['content_type'][]= Post::type('link'); } return $filters; } /** * Provide the alternate representation of the new feeds **/ public function filter_atom_get_collection_alternate_rules( $rules ) { $rules['link_feed'] = 'display_home'; return $rules; } /** * Add needed rewrite rules **/ public function filter_rewrite_rules($rules) { $feed_regex= $feed_regex = implode( '|', LinkHandler::$feeds ); $rules[] = new RewriteRule( array( 'name' => 'link_feed', 'parse_regex' => '%feed/(?P<name>' . $feed_regex . ')/?$%i', 'build_str' => 'feed/{$name}', 'handler' => 'LinkHandler', 'action' => 'feed', 'priority' => 7, 'is_active' => 1, 'description' => 'Displays the link feeds', )); return $rules; } } ?><file_sep><?php /** * Google Analytics Dashboard Modules Plugin * * @todo figure out why the dropdown doesn't show the first time you hit save. have to hit it twice to make it show up. * @todo clean up documentation. It's sad, I know. * **/ include 'class.analytics.php'; class ga_dashboard extends Plugin { private $class_name = ''; private $config = array(); private $reports = array(); private $funcs = array(); // Default options private $default_options = array( 'user_id' => '', 'user_pw' => '', 'cache_expiry' => 3600, 'profile' => '' ); /** * On plugin init **/ public function action_init() { $this->class_name = strtolower( get_class( $this ) ); foreach ( $this->default_options as $name => $value ) { $this->config[$name] = Options::get( $this->class_name . '__' . $name ); } if ( $this->plugin_configured( $this->config ) ) { $this->validate_reports( $this->load_available_reports() ); // Add our template files for valid reports and register our functions foreach ( $this->reports as $rpt => $data ) { $this->add_template( $data['slug'], $data['template'] ); // This is janky. dynamic_dash_filter() is too. $this->funcs[$data['module']] = "$rpt"; Plugins::register( array( $this, 'dynamic_dash_filter' ), 'filter', 'dash_module_' . $data['slug'] ); } } } /** * action_plugin_activation * Registers the core modules with the Modules class. Add these modules to the * dashboard if the dashboard is currently empty. * @param string $file plugin file */ public function action_plugin_activation( $file ) { foreach ( $this->default_options as $name => $value ) { $current_value = Options::get( $this->class_name . '__' . $name ); if ( is_null( $current_value ) ) { Options::set( $this->class_name . '__' . $name, $value ); } } if( Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__) ) { foreach ( $this->reports as $rpt => $data ) { Modules::add( $data['module'] ); } } } /** * action_plugin_deactivation * Unregisters the core modules. * @param string $file plugin file */ public function action_plugin_deactivation( $file ) { if( Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__) ) { foreach ( $this->reports as $rpt => $data ) { Modules::remove_by_name( $data['module'] ); } } } public function action_admin_header( $theme ) { Stack::add( 'admin_header_javascript', "http://www.google.com/jsapi"); Stack::add( 'admin_header_javascript', $this->get_url(true) . 'ga_base.js'); } /** * filter_dash_modules * Registers the core modules with the Modules class. */ public function filter_dash_modules( $modules ) { foreach ( $this->reports as $rpt => $data ) { array_push( $modules, $data['module'] ); } return $modules; } /** * Add actions to the plugin page * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id **/ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id === $this->plugin_id() ) { $actions[] = _t( 'Configure', $this->class_name ); $actions[] = _t( 'Reset Configuration', $this->class_name ); } return $actions; } /** * Respond to the user selecting an action on the plugin page * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook **/ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id === $this->plugin_id() ) { switch ( $action ) { case _t( 'Configure', $this->class_name ): $ui = new FormUI( $this->class_name ); $user_id = $ui->append( 'text', 'user_id', 'option:' . $this->class_name . '__user_id', _t( 'GA username', $this->class_name ) ); $user_pw = $ui->append( 'password', 'user_pw', 'option:' . $this->class_name . '__user_pw', _t( 'GA password', $this->class_name ) ); $user_pw->value = base64_decode( Options::get( $this->class_name . '__user_pw' ) ); $cache_expiry = $ui->append( 'text', 'cache_expiry', 'option:' . $this->class_name . '__cache_expiry', _t( 'Cache Expiry (in seconds)', $this->class_name ) ); $cache_expiry->add_validator( 'validate_uint' ); $cache_expiry->add_validator( 'validate_required' ); if ( $this->plugin_configured( $this->config ) ) { $ga = new Google_Analytics( $this->config['user_id'], base64_decode( $this->config['user_pw'] ) ); // get an array with profiles (profileId => profileName) $gprofs = $ga->get_profiles(); $profile = $ui->append( 'select', 'profile', 'option:' . $this->class_name . '__profile', _t( 'Profile' ) ); $profile->options = $gprofs; } // When the form is successfully completed, call $this->updated_config() $ui->append( 'submit', 'save', _t( 'Save', $this->class_name ) ); $ui->set_option( 'success_message', _t( 'Options saved', $this->class_name ) ); $ui->on_success( array( $this, 'updated_config' ) ); $ui->out(); break; case _t( 'Reset Configuration', $this->class_name ): foreach ( $this->default_options as $name => $value ) { Options::set( $this->class_name . '__' . $name, $value ); } break; } } } public function updated_config( $ui ) { $b64_pw = base64_encode( $ui->user_pw->value ); $ui->save(); Options::set( $this->class_name . '__user_pw', $b64_pw ); foreach ( $this->reports as $rpt => $data ) { $cache = $this->class_name . '__' . $rpt; Cache::expire( $cache ); } return false; } public function validate_uint( $value ) { if ( ! ctype_digit( $value ) || strstr( $value, '.' ) || $value < 0 ) { return array( _t( 'This field must be a positive integer.', $this->class_name ) ); } return array(); } public function plugin_configured( $params = array() ) { if ( empty( $params['user_id'] ) || empty( $params['user_pw'] ) || empty( $params['cache_expiry'] ) ) { return false; } return true; } /** * Load in all available reports * @return array array of available report files **/ private function load_available_reports() { $valid_reports = array(); $reports = array(); $templates = array(); $searchdirs = array( dirname( __FILE__ ) . '/default', dirname( __FILE__ ) . '/custom' ); $dirs = array(); foreach ( $searchdirs as $searchdir ) { if ( file_exists( $searchdir ) ) { $dirs = array_merge( $dirs, Utils::glob( $searchdir . '*', GLOB_ONLYDIR | GLOB_MARK ) ); } } // Load in the available reports and templates foreach ( $dirs as $dir ) { $reportfiles = Utils::glob( $dir . '*.xml' ); $templatefiles = Utils::glob( $dir . '*.php' ); if ( ! empty ( $reportfiles ) ) { $reportfiles = array_combine( // Use the basename of the file as the index to use the named report from the last directory in $dirs array_map( 'basename', $reportfiles ), // massage the filenames so that this works on Windows array_map( create_function( '$s', 'return str_replace(\'\\\\\', \'/\', $s);' ), $reportfiles ) ); $reports = array_merge( $reports, $reportfiles ); } if ( ! empty ( $templatefiles ) ) { $templatefiles = array_combine( // Use the basename of the file as the index to use the named report from the last directory in $dirs array_map( 'basename', $templatefiles ), // massage the filenames so that this works on Windows array_map( create_function( '$s', 'return str_replace(\'\\\\\', \'/\', $s);' ), $templatefiles ) ); $templates = array_merge( $templates, $templatefiles ); } } // Now go through and generate our valid_reports() foreach ( $reports as $rptKey => $rptVal ) { $tmpKey = array_search( str_replace( '.xml', '.php', $rptVal ), $templates ); if ( $tmpKey ) { $key = basename( $rptVal, ".xml" ); $valid_reports[$key] = array( 'xml' => $rptVal, 'template' => $templates[$tmpKey] ); } } ksort( $valid_reports ); return $valid_reports; } /** * validate_reports() * Reads in the xml from each available report * If valid, will load it to the $this->reports array **/ private function validate_reports( $reports ) { // Charts that require js options to be built $jCharts = array( "piechart", "geomap", "linechart", "areachart" ); // All support chart types $sCharts = array_merge( (array) "none", $jCharts ); foreach ( $reports as $rpt => $data ) { $report = array(); $xml = simplexml_load_file( $data['xml'] ); if ( $xml ) { // load in the single options $display = (string) $xml->name; $opts = (string) $xml->opts; $ctype = strtolower( (string) $xml->type ); $sort = (string) $xml->sort; // Make sure that the display name has been set if ( $display === "" ) return; // Set a few others based off of base option. $module = 'GA ' . $display; $slug = Utils::slugify( $module, '_' ); $template = $data['template']; // Make sure this is a supported chart type if ( ! in_array( $ctype, $sCharts ) ) return; // Make sure we have a valid sort type if ( ! in_array( $sort, array( "none", "numeric", "key" ) ) ) { $sort = ""; } // Check our dataRefs $dataRefs = array(); foreach ( $xml->xpath('dataReference') as $dataRef ) { if ( $dataRef['order'] ) { // if we have order, use that as the key $key = (int) $dataRef['order']; } else { // create them as we find them. $key = count( $dataRefs ) + 1; } $dimensions = (string) $dataRef->dimensions; $metrics = (string) $dataRef->metrics; $sort = (string) $dataRef->sort; /** * @todo maybe add some additional checks here to make sure that we have a correct * set of options. For now if they are an incorrect combination, it will break * all of the charts as JS will kick up an error and not run the rest of them. * We're just checking that the sort isn't blank right now. */ if ( $sort ) { // Default sort to metrics if it's not specified $sort = $metrics; } // Store them in a temp array $dataRefs[ $key ] = array( 'd' => $dimensions, 'm' => $metrics, 's' => $sort ); } // Get limit information for our data $lMax = intval( (string) $xml->limit->max ); if ( $lMax > 0 ) { $rlTotal = intval( (string) $xml->limit->totalDropped ); $lTotal = ( $rlTotal === 1 ) ? true : false; } // Get information for JS on js chart types if ( in_array( $ctype, $jCharts ) ) { if ( $opts === "" ) { // set the default js options $opts = 'height: 200'; } // Load and validate the dataTypes $dataTypes = array(); foreach( $xml->xpath( '//dataTypes/row' ) as $dataType ) { $dtype = (string) $dataType['type']; $dname = (string) $dataType; if ( $dtype === "" ) { // default type to number $dtype = 'number'; } if ( $dname === "" ) { // default name to column_x $dname = 'Column_' . (string) count( $dataTypes ); } // Store them in a temp array $dataTypes[] = array( 't' => $dtype, 'n' => $dname, ); } // Verify that we have count( $dataRefs) + 1 for our js dataTable. if ( ! count( $dataTypes ) == ( count( $dataRefs) + 1 ) ) return; } // Seems to be valid, so let's add it to our self::reports $this->reports[ $rpt ] = array( 'name' => $display, 'module' => $module, 'slug' => $slug, 'template' => $template, 'type' => $ctype, 'opts' => $opts, 'sort' => $sort, 'limit' => $lMax, 'ltotal' => $lTotal, 'dataRefs' => $dataRefs ); if ( in_array( $ctype, $jCharts ) ) { $this->reports[$rpt]['dataTypes'] = $dataTypes; } } } } /** * dynamic_dash_filter() * There's just got to be a better way of doing this.... **/ public function dynamic_dash_filter( $module, $module_id, $theme ) { // Pull a little magic sauce out of the params $searchVal = (string)$module['name']; // $rpt is set to the key of our reports array... $rpt = $this->funcs["$searchVal"]; // call to load our data here. have that func do the cache checking. //$this->load_report_data( $rpt ); $module['title'] = ( $this->reports["$rpt"]['name'] ); if ( $this->plugin_configured( $this->config ) ) { // call to load our data here. $data = $this->load_report_data( $rpt ); $data_total = 0; $dkeys = array_keys( $data ); $sort = $this->reports[$rpt]['sort']; /** * @todo fix sort to actually support different types. * For now we default to ksort the array. * if sort is set, we arsort it. */ foreach ( $dkeys as $dk ) { foreach ( $data[$dk] as $k => $v ) { $data_total += $v; } ksort( $data[$dk] ); } if ( $this->reports[$rpt]['limit'] != 0 ) { foreach ( $dkeys as $dk ) { if ( $sort ) { arsort( $data[$dk] ); } // Generate the totals for the other items that we're dropping $ototals = 0; $tmpArr = array_slice( $data[$dk], $this->reports[$rpt]['limit'] ); foreach ( $tmpArr as $key => $val ) $ototals += $val; // Actually drop the other items for limit array_splice( $data[$dk], $this->reports[$rpt]['limit'] ); if ( ( $this->reports[$rpt]['type'] != "none" ) && $this->reports[$rpt]['ltotal'] ) { // Add the (others) total to the array $data[$dk]["(others)"] = $ototals; } } } // Set some template variables $theme->slug = $this->reports["$rpt"]['slug']; $theme->data = $data; $theme->data_total = $data_total; $theme->js_opts = $this->reports["$rpt"]['opts']; $theme->js_data = $this->create_js_data( $rpt, $data ); $theme->js_draw = $this->create_js_draw( $rpt ); $module['content'] = $theme->fetch( $this->reports["$rpt"]['slug'] ); } else { $module['content'] = '<div class="message pct90"><p><b>Plugin is not configured!</b></p></div>'; } return $module; } /** * create_js_data() * Generates a js string for a named report * @return string javascript string for chart data. **/ private function create_js_data( $report, $data ) { if ( $this->reports[$report]['type'] === 'none' ) return ''; // init the DataTable() $slug = $this->reports[$report]['slug']; $js = "var $slug = new google.visualization.DataTable();"; // Add our column headers $dataTypes = $this->reports[$report]['dataTypes']; foreach ( $dataTypes as $dataType ) { $dtype = $dataType['t']; $dname = $dataType['n']; $js .= "$slug.addColumn('$dtype', '$dname');"; } $js .= "$slug.addRows(["; // Add our column data $colcount = count( $data ); // we should always have $data[1] $colkeys = array_keys( $data[1] ); $combined = array(); // Load all of our arrays into one single by key foreach ( $colkeys as $key ) { $tmp = array(); for ( $i = 1; $i <= $colcount; $i++ ) { $tmp[] = $data[$i][$key]; } $combined[$key] = $tmp; } foreach ( $combined as $key => $val ) { if ( preg_match( '/\d\s\d/', $key ) ) { $key = str_replace( ' ', '/', $key ); } $js .= "['$key', "; $cnt = 1; foreach ( $val as $v ) { if ( is_numeric( $v ) ) { $js .= intval( $v ); } else { $js .= "'$v'"; } if ( $cnt == count( $val ) ) { $js .= "],"; } else { $js .= ", "; $cnt++; } } } $js .= "]);"; return $js; } private function create_js_draw( $report ) { if ( $this->reports[$report]['type'] === 'none' ) return ''; $slug = $this->reports[$report]['slug']; $type = $this->reports[$report]['type']; $js = "do$type( $slug, opts, 'div_$slug');"; return $js; } /** * load_report_data() * Loads GA report data for a named report * @return array data from GA **/ private function load_report_data( $report ) { $cache_name = $this->class_name . '__' . $report; if ( Cache::has( $cache_name ) ) { // Read from the cache return Cache::get( $cache_name ); } else { // Time to fetch it. try { // Call out to get the data here. $gObj = new Google_Analytics( $this->config['user_id'], base64_decode( $this->config['user_pw'] ) ); // get an array with profiles (profileId => profileName) $prof = $gObj->get_profiles(); $profkeys = array_keys( $prof ); if ( $this->config['profile'] != '' ) { $gObj->set_profile( $this->config['profile'] ); } else { // set the profile to the first account. $gObj->set_profile( $profkeys[0] ); } $startDate = date('Y-m-d', strtotime("-1 month") ); $stopDate = date('Y-m-d'); $gObj->set_date_range( $startDate, $stopDate ); $gadata = array(); $refcount = count( $this->reports[$report]['dataRefs'] ); // We may have multiple data references, so we need to fetch them all. $dataref = $this->reports[$report]['dataRefs']; // loop through in order. for ( $i = 1; $i <= $refcount; $i++ ) { $gadata[$i] = $gObj->getData( $dataref[$i]['d'], $dataref[$i]['m'], $dataref[$i]['s'] ); } // Store the cache Cache::set( $cache_name, $gadata, $this->config['cache_expiry'] ); return $gadata; } catch ( Exception $e ) { return $e->getMessage(); } } } } // class ga_dashboards ?><file_sep> <div id="footer"> <span id="generator-link"><?php _e('%s is powered by', array(Options::out('title'))); ?> <a href="http://habariproject.org/" title="Habari">Habari <?php echo Version::HABARI_VERSION; ?></a> and <a href="http://fireyy.com/archives/oldprice-theme-for-habari-180" title="oldprice theme for Habari">oldprice</a></span> </div><!-- #footer --> </div><!-- #wrapper .hfeed --> <div id="wrapper_footer">footer</div> <?php $theme->footer(); ?> <?php // Uncomment this to view your DB profiling info // include 'db_profiling.php'; ?> </body> </html> <file_sep><?php $theme->display('header');?> <?php if (isset( $_GET['action'] ) and User::identify()->can( 'manage_shelves' ) ) { switch( $_GET[ 'action' ] ) { case "delete": Shelves::delete_shelf( $_GET[ 'shelf' ] ); break; case "edit": // actually, probably don't need to even do this. break; default: // shouldn't come to this. } // ok, token checked, but is it overkill? // Utils::debug( $_GET ); } ?> <div class="container"> <?php echo $form; ?> </div> <div class="container plugins activeplugins"> <?php // this should be in the plugin, not on this page. $all_shelves = array(); $all_shelves = Vocabulary::get( 'shelves' )->get_tree(); // Utils::debug( $all_shelves ); if ( count( $all_shelves) > 0 ) { $right = array(); foreach ( $all_shelves as $shelf ) { while ( count($right) > 0 && $right[count($right) - 1] < $shelf->mptt_right ) { array_pop($right); } $pad = count($right)*30; $titlelink = sprintf( '<a href="%s" title="%s">%s</a>', URL::get( 'admin', array( 'page' => 'posts', 'search' => Options::get( 'shelves__single', _t( 'shelf', 'shelves' ) ) . ':' . $shelf->term ) ), _t( "Manage content categorized '%s'", array($shelf->term_display), 'shelves' ), $shelf->term_display ); $dogs_eat_cats = _t('Contains %d posts.', array( Posts::get(array ('vocabulary'=> array( 'shelves:term' => $shelf->term ), 'count' => 'term' ) ) ), 'shelves' ); // debugging $titlelink .= "<h4>{$shelf->mptt_left} :: {$shelf->mptt_right}</h4>"; $dropbutton = '<ul class="dropbutton"><li><a href="'. URL::get( 'admin', array( 'page' => 'shelves', 'action' => 'edit', 'shelf' => $shelf->term ) ) . '" title="' . _t( "Rename or move '{$shelf->term_display}'" ) . '">' . _t( "Edit" ) . '</a></li><li><a href="' . URL::get( 'admin', array( 'page' => 'shelves', 'action' => 'delete', 'shelf' => $shelf->term ) ) . '" title="' . _t( "Delete '{$shelf->term_display}'" ) . '">' . _t( "Delete" ) . '</a></li></ul>'; echo "\n<div class='item plugin clear' style='border-left: {$pad}px solid #e9e9e9; border-color:#e9e9e9;'><div class='head'>"; echo "\n$titlelink $dropbutton\n</div><p>$dogs_eat_cats</p></div>"; $right[] = $shelf->mptt_right; } } else { _e( "<h2>No %s have been created yet</h2>", array( Options::get( 'shelves__plural', _t( 'shelves', 'shelves' ) ) ) ); } ?></div> <?php $theme->display('footer'); ?> <file_sep><div id="post-<?php echo $content->id; ?>" class="entry <?php echo $content->statusname; ?>"> <div class="entry-head"> <h2 class="entry-title"><a href="<?php echo $content->permalink; ?>" title="<?php echo $content->title; ?>"><?php echo $content->title_out; ?></a></h2> <div class="entry-meta"> <span class="chronodata published"><?php echo $content->pubdate_ago; ?></span> &middot; <span class="commentslink"><a href="<?php echo $content->permalink; ?>#comments" title="<?php _e('Comments on this post', 'resurrection'); ?>"><?php printf(_n( '%d Comment', '%d Comments', $content->comments->approved->count, 'resurrection' ), $content->comments->approved->count); ?></a></span> <?php if ( is_object($user) && $user->can('edit_post') ) : ?> &middot; <span class="entry-edit"><a href="<?php echo $content->editlink; ?>" title="<?php _e('Edit post', 'resurrection'); ?>"><?php _e('Edit', 'resurrection'); ?></a></span> <?php endif; ?> <?php if ( is_array( $content->tags ) ) : ?> &middot; <span class="entry-tags"><?php echo $content->tags_out; ?></span> <?php endif; ?> </div> </div> <div class="entry-content"> <?php echo $content->content_out; ?> </div> </div><file_sep><?php include 'header.php'; ?> <!-- entry.single --> <div id="content"> <?php include 'entry.php'; ?> <p class="postfeedback"> <?php include_once( 'comments.php' ); ?></p> </div> <!-- #content --> <?php include 'sidebar.php'; ?> <!-- /entry.single --> <?php include 'footer.php'; ?> <file_sep><?php class PopularPosts extends Plugin { /** * Add the necessary template * **/ public function action_init() { $this->add_template( 'popular_posts', dirname(__FILE__) . '/popular_posts.php' ); $this->add_template( 'block.popular_posts', dirname(__FILE__) . '/block.popular_posts.php' ); } /** * Add to the list of possible block types. * **/ public function filter_block_list( $block_list ) { $block_list[ 'popular_posts' ] = _t( 'Popular Posts', 'popular_posts' ); return $block_list; } /** * Create a configuration form for this plugin * **/ public function configure() { $form = new FormUI( 'popular_posts' ); $form->append( 'checkbox', 'loggedintoo', 'popular_posts__loggedintoo', _t( 'Track views of logged-in users too', 'popular_posts' ) ); $form->append( 'submit', 'save', 'Save' ); $form->out(); } /** * Create a configuration form for the block **/ public function action_block_form_popular_posts( $form, $block ) { $content = $form->append( 'text', 'quantity', $block, _t( 'Posts to show:', 'popular_posts' ) ); $form->append( 'submit', 'save', _t( 'Save', 'popular_posts' ) ); } /** * Log the entry page view, when appropriate. * */ public function action_add_template_vars( $theme, $handler_vars ) { // If there is only one post if ( $theme->post instanceof Post && count( $theme->posts ) == 1 ) { // Only track users that aren't logged in, unless specifically overridden if ( !User::identify()->loggedin || Options::get( 'popular_posts__loggedintoo' ) ) { $set = Session::get_set( 'popular_posts', false ); $post = $theme->post; if ( !in_array( $post->id, $set ) ){ $views = $post->info->views; if ( $views == null ) { $views = 0; } $views += 1; $post->info->views = $views; $post->info->commit(); Session::add_to_set( 'popular_posts', $post->id ); } } } } /** * Display a template with the popular entries */ public function theme_popular_posts($theme, $limit = 5) { $theme->popular_posts = Posts::get( array( 'content_type' => 'entry', 'has:info' => 'views', 'orderby' => 'CAST(hipi1.value AS UNSIGNED) DESC', // As the postinfo value column is TEXT, ABS() forces the sorting to be numeric 'limit' => $limit ) ); return $theme->display( 'popular_posts' ); } /** * Populate a block with the popular entries **/ public function action_block_content_popular_posts( $block, $theme ) { if ( ! $limit = $block->quantity ) { $limit = 5; }; $block->popular_posts = Posts::get( array( 'content_type' => 'entry', 'has:info' => 'views', 'orderby' => 'CAST(hipi1.value as UNSIGNED) DESC', // As the postinfo value column is TEXT, ABS() forces the sorting to be numeric 'limit' => $limit ) ); } } ?> <file_sep><?php /** * Handler class for the Jambo contact form plugin for Habari * * @package jambo */ class JamboHandler extends ActionHandler { public function act_send() { $email = array(); $email['sent']= false; $email['valid']= true; $email['send_to']= Jambo::get( 'send_to' ); $email['subject_prefix']= Jambo::get( 'subject_prefix' ); $email['name']= $this->handler_vars['name']; $email['email']= $this->handler_vars['email']; $email['subject']= $this->handler_vars['subject']; $email['message']= $this->handler_vars['message'];+ $email['osa']= $this->handler_vars['osa']; $email['osa_time']= $this->handler_vars['osa_time']; $email['headers']= "MIME-Version: 1.0\r\n" . "From: {$email['name']} <{$email['email']}>\r\n" . "Content-Type: text/plain; charset=\"utf-8\"\r\n"; $email = Plugins::filter( 'jambo_email', $email, $this->handler_vars ); if ( $email['valid'] ) { $email['sent']= mail( $email['send_to'], $email['subject_prefix'] . $email['subject'], $email['message'], $email['headers'] ); $this->remember_contactor( $email ); } foreach ( $email as $key => $value ) { Session::add_to_set( 'jambo_email', $value, $key ); } Utils::redirect( $_SERVER['HTTP_REFERER'] . '#jambo' ); } // set a cookie like in comments. private function remember_contactor( $email ) { $cookie = 'comment_' . Options::get('GUID'); if ( ( ! User::identify()->loggedin ) && ( ! isset( $_COOKIE[$cookie] ) ) && ( ! empty( $email['name'] ) || ! empty( $email['email'] ) ) ) { $cookie_content = $email['name'] . '#' . $email['email'] . '#' . ''; $site_url = Site::get_path('base'); if ( empty( $site_url ) ) { $site_url = rtrim( $_SERVER['SCRIPT_NAME'], 'index.php' ); } else { $site_url = '/' . $site_url . '/'; } setcookie( $cookie, $cookie_content, time() + 31536000, $site_url ); } } } ?> <file_sep><?php include 'header.php'; ?> <div id="content_wrap"> <div id="content"> <?php if ($posts) { ?> <?php foreach ( $posts as $post ) { ?> <div class="post_wrap"> <h2><a href="<?php echo $post->permalink; ?>" rel="bookmark" title="<?php echo $post->title; ?>"><?php echo $post->title_out; ?></a></h2> <p class="post_details"><?php echo $post->pubdate_out; ?>. Published by <?php echo $post->author->displayname; ?> <?php if ( is_array( $post->tags ) ) :?>under <?php echo $post->tags_out;?><?php endif; ?>. <a href="<?php echo $post->permalink; ?>#comments" title="Comments to this post"><?php echo $post->comments->approved->count; ?> <?php echo _n( 'comment', 'comments', $post->comments->approved->count ); ?></a>. <?php if ( $user ) { ?> <span class="entry-edit"> | <a href="<?php echo $post->editlink; ?>" title="Edit post">Edit</a> |</span> <?php } ?></p> <?php echo $post->content_out; ?> </div> <?php } ?> <div id="more_entries"> <h2><?php $theme->next_page_link('&laquo; Older Entries'); ?> &nbsp; <?php $theme->prev_page_link('Recent Entries &raquo;'); ?></h2> </div> <?php }else{ ?> <h2>Search results</h2> <p>No matches. Please try again, or use the navigation menus to find what you search for.</p> <?php } ?> </div> <?php include 'sidebar.php'; ?> </div> <?php include 'footer.php'; ?><file_sep><?php class GetClicky extends Plugin { public function action_plugin_activation( $file ) { if ( realpath( $file ) == __FILE__ ) { Modules::add( 'GetClicky' ); Options::set( 'getclicky__cachetime', '300' ); Options::set( 'getclicky__loggedin', 1 ); } } public function action_plugin_deactivation( $file ) { if ( realpath( $file ) == __FILE__ ) { Options::delete('getclicky__siteid'); Options::delete('getclicky__sitekey'); Options::delete('getclicky__sitedb'); Options::delete('getclicky__loggedin'); Options::delete('getclicky__cachetime'); $this->clearCache(); Modules::remove_by_name( 'GetClicky' ); } } function action_update_check() { Update::add( 'GetClicky Analytics', '5F271634-89B7-11DD-BE47-289255D89593', $this->info->version ); } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t('Configure'); $actions[]= _t('Clear Cache'); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure') : $ui = new FormUI( strtolower( get_class( $this ) ) ); $ui->append( 'text', 'siteid', 'getclicky__siteid', _t('Site ID:') ); $ui->append( 'text', 'sitekey', 'getclicky__sitekey', _t('Site Key:') ); $ui->append( 'text', 'sitedb', 'getclicky__sitedb', _t('Site DB:') ); $ui->append( 'checkbox', 'loggedin', 'getclicky__loggedin', _t('Don\'t track this user?:') ); $ui->append( 'text', 'cachetime', 'getclicky__cachetime', _t('Cache Dashboard statistics for (seconds):') ); $ui->append('submit', 'save', _t( 'Save' ) ); $ui->set_option('success_message', _t('GetClicky Settings Saved')); $ui->out(); break; case _t('Clear Cache') : $this->clearCache(); break; } } } public function filter_dash_modules( $modules ) { $modules[]= 'GetClicky'; $this->add_template( 'dash_getclicky', dirname( __FILE__ ) . '/dash_getclicky.php' ); return $modules; } public function filter_dash_module_getclicky( $module, $module_id, $theme ) { $siteid = Options::get('getclicky__siteid'); $sitekey = Options::get('getclicky__sitekey'); $cachetime = Options::get('getclicky__cachetime'); $theme->site_rank = $this->fetchSingleStat('site-rank', $siteid, $sitekey, $cachetime); $theme->current_visitors = $this->fetchSingleStat('visitors-online', $siteid, $sitekey, $cachetime); $theme->unique_visitors = $this->fetchSingleStat('visitors-unique', $siteid, $sitekey, $cachetime); $theme->todays_actions = $this->fetchSingleStat('actions', $siteid, $sitekey, $cachetime); $theme->actions_average = $this->fetchSingleStat('actions-average', $siteid, $sitekey, $cachetime); $theme->time_total = $this->fetchSingleStat('time-total-pretty', $siteid, $sitekey, $cachetime); $theme->time_average = $this->fetchSingleStat('time-average-pretty', $siteid, $sitekey, $cachetime); $theme->siteid = $siteid; $module['content']= $theme->fetch( 'dash_getclicky' ); return $module; } function theme_footer() { if ( URL::get_matched_rule()->entire_match == 'user/login') { // Login page; don't dipslay return; } if ( User::identify()->loggedin ) { // Only track the logged in user if we were told to if ( Options::get('getclicky__loggedin') ) { return; } } $siteid = Options::get('getclicky__siteid'); $sitedb = Options::get('getclicky__sitedb'); echo <<<ENDAD <a title="Clicky Web Analytics" href="http://getclicky.com/{$siteid}"> <img alt="Clicky Web Analytics" src="http://static.getclicky.com/media/links/badge.gif" border="0" /> </a> <script src="http://static.getclicky.com/{$siteid}.js" type="text/javascript"></script> <noscript> <p> <img alt="Clicky" src="http://static.getclicky.com/{$siteid}-{$sitedb}.gif" /> </p> </noscript> ENDAD; } function fetchSingleStat($type, $siteid, $sitekey, $cachetime) { $value = "N/A"; if ( Cache::has( 'feedburner_stat_'.$type ) ) { $value = Cache::get( 'feedburner_stat_'.$type ); } else { $url = 'http://api.getclicky.com/stats/api3?site_id='.$siteid.'&sitekey='.$sitekey.'&type='.$type.'&output=json'; $request = new RemoteRequest($url); if (!$request->execute()) { throw new XMLRPCException( 16 ); } $data = json_decode($request->get_response_body()); if (isset($data[0]->dates[0]->items[0]->value)) { $value = $data[0]->dates[0]->items[0]->value; } Cache::set( 'feedburner_stat_'.$type, $value, $cachetime ); } return $value; } function clearCache() { Cache::expire('feedburner_stat_site-rank'); Cache::expire('feedburner_stat_visitors-online'); Cache::expire('feedburner_stat_visitors-unique'); Cache::expire('feedburner_stat_actions'); Cache::expire('feedburner_stat_actions-average'); Cache::expire('feedburner_stat_time-total-pretty'); Cache::expire('feedburner_stat_time-average-pretty'); echo '<p>' . _t( 'Cache has been cleared.' ) . '</p>'; return true; } } ?> <file_sep><?php /** * Brightkite Location plugin for Habari 0.6+ * Shows the current checked in location with google map. * * Usage: <?php $theme->bk_location(); ?> * **/ class Brightkite extends Plugin { const VERSION = '0.1.2'; private $config = array(); private $class_name = ''; private static function default_options() { return array ( 'user_id' => '', 'google_api_key' => '', 'map_image_size' => '200x200', 'cache_expiry' => 1800 ); } /** * Required plugin information * @return array The array of information **/ public function info() { return array( 'name' => 'Brightkite', 'url' => 'http://www.ciscomonkey.net/', 'author' => '<NAME>', 'authorurl' => 'http://www.ciscomonkey.net', 'version' => self::VERSION, 'description' => _t('Display your latest checkedin info on your blog.', $this->class_name), 'license' => 'Apache License 2.0', ); } /** * Add actions to the plugin page * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id **/ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id === $this->plugin_id() ) { $actions[] = _t( 'Configure', $this->class_name ); } return $actions; } /** * Respond to the user selecting an action on the plugin page * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook **/ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id === $this->plugin_id() ) { switch ( $action ) { case _t( 'Configure', $this->class_name ): $ui = new FormUI( $this->class_name ); $user_id = $ui->append( 'text', 'user_id', 'option:' . $this->class_name . '__user_id', _t( 'Brightkite Username', $this->class_name ) ); $user_id->add_validator( 'validate_bk_username' ); $user_id->add_validator( 'validate_required' ); $google_api_key = $ui->append( 'text', 'google_api_key', 'option:' . $this->class_name . '__google_api_key', _t( 'Google Maps API Key', $this->class_name ) ); $map_image_size = $ui->append( 'text', 'map_image_size', 'option:' . $this->class_name . '__map_image_size', _t( 'Size of map image', $this->class_name ) ); $map_image_size->add_validator( 'validate_regex', '/\d+x\d+/' ); $map_image_size->add_validator( 'validate_required' ); $cache_expiry = $ui->append( 'text', 'cache_expiry', 'option:' . $this->class_name . '__cache_expiry', _t( 'Cache Expiry (in seconds)', $this->class_name ) ); $cache_expiry->add_validator( 'validate_uint' ); $cache_expiry->add_validator( 'validate_required' ); // When the form is successfully completed, call $this->updated_config() $ui->append( 'submit', 'save', _t( 'Save', $this->class_name ) ); $ui->set_option( 'success_message', _t( 'Options saved', $this->class_name ) ); $ui->out(); break; } } } public function validate_bk_username( $username ) { if ( ! ctype_alnum( $username ) ) { return array( _t( 'Your Brightkite username is not valid.', $this->class_name ) ); } return array(); } public function validate_uint( $value ) { if ( ! ctype_digit( $value ) || strstr( $value, '.' ) || $value < 0 ) { return array( _t( 'This field must be a positive integer.', $this->class_name ) ); } return array(); } public function plugin_configured( $params = array() ) { if ( empty( $params['user_id'] ) || empty( $params['cache_expiry'] ) || empty( $params['map_image_size'] ) ) { return false; } return true; } /** * On plugin activation, set the default options **/ public function action_plugin_activation( $file ) { if ( realpath( $file ) === __FILE__ ) { $this->class_name = strtolower( get_class( $this ) ); foreach ( self::default_options() as $name => $value ) { $current_value = Options::get( $this->class_name . '__' . $name ); if ( is_null( $current_value ) ) { Options::set( $this->class_name . '__' . $name, $value ); } } } } /** * On plugin init **/ public function action_init() { $this->class_name = strtolower( get_class( $this ) ); foreach ( self::default_options() as $name => $value ) { $this->config[$name] = Options::get( $this->class_name . '__' . $name ); } $this->add_template( 'brightkite', dirname( __FILE__ ) . '/brightkite.php' ); } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Brightkite', '263F0954-4B2B-11DE-B433-958C55D89593', $this->info->version ); } /** * Get the brightkite feed for our user_id **/ private function load_bk_info ( $params = array() ) { $cache_name = $this->class_name . '__' . md5( serialize( $params ) ); if ( Cache::has( $cache_name ) ) { // Read from the cache return Cache::get( $cache_name ); } else { // Time to fetch it. $url = 'http://brightkite.com/people/' . $params['user_id'] . '.json'; try { $call = new RemoteRequest( $url ); $call->set_timeout( 5 ); $result = $call->execute(); if ( Error::is_error( $result ) ) { throw Error::raise( _t( 'Unable to contact Brightkite.', $this->class_name ) ); } $response = $call->get_response_body(); // Decode the JSON $bkdata = json_decode( $response, true ); if ( ! is_array( $bkdata ) ) { // Response is not JSON throw Error::raise( _t( 'Response is not correct, maybe Brightkite server is down or API changed.', $this->class_name ) ); } // Do cache Cache::set( $cache_name, $bkdata, $params['cache_expiry'] ); return $bkdata; } catch ( Exception $e ) { return $e->getMessage(); } } } /** * Add bk info to the available template vars * @param Theme $theme the theme that will display the template **/ public function theme_bk_location( $theme, $params = array() ) { $params = array_merge( $this->config, $params ); if ( $this->plugin_configured( $params ) ) { $theme->bkinfo = $this->load_bk_info( $params ); $theme->gmapkey = $this->config['google_api_key']; $theme->mapsize = $this->config['map_image_size']; } else { $theme->bkinfo = _t( 'Brightkite Plugin is not configured properly.', $this->class_name ); } return $theme->fetch( 'brightkite' ); } } ?><file_sep><?php $theme->display('header'); ?> <!-- 404 --> <div id="content"> <div class="error"> <h1><?php _e('Error!', 'binadamu'); ?></h1> <p><?php _e('The requested post was not found.', 'binadamu'); ?></p> </div> </div> <hr /> <!-- /404 --> <?php $theme->display('sidebar'); ?> <?php $theme->display('footer'); ?> <file_sep><?php if ( $post->comments->moderated->count ) {?> <h2 id="comments"><?php echo $post->comments->moderated->count; ?> comments</h2> <?php foreach ( $post->comments->moderated as $comment ) { ?> <div class="comments_wrap" id="comment-<?php echo $comment->id; ?>"> <div class="left"> <img src="<?php //$theme->gravatar('X', '35'); ?>http://www.gravatar.com/avatar.php?gravatar_id=<?php echo md5( $comment->email ); ?>&size=35" alt="<?php _e('Gravatar'); ?>" /> </div> <div class="right"> <h4><b><a href="<?php echo $comment->url; ?>" rel="external"><?php echo $comment->name; ?></a></b>&nbsp; on <?php echo $comment->date_out; ?></h4> <?php echo $comment->content_out; ?> <?php if ( $comment->status == Comment::STATUS_UNAPPROVED ) { echo '<p><em>Your comment is awaiting moderation.</em></p>'; } ?> </div> </div> <?php }} ?> <h2 class="lc">Leave a Comment</h2> <?php if ( Session::has_errors() ) { Session::messages_out(); } ?> <form action="<?php URL::out( 'submit_feedback', array( 'id' => $post->id ) ); ?>" method="post" id="commentform"> <div> <label for="name">Username :<br /> <input type="text" name="name" id="author" value="<?php echo $commenter_name; ?>" size="27" tabindex="1" /></label> <label for="email">Email :<br /> <input type="text" name="email" id="email" value="<?php echo $commenter_email; ?>" size="27" tabindex="2" /></label> <label for="url">Web Site :<br /> <input type="text" name="url" id="url" value="<?php echo $commenter_url; ?>" size="27" tabindex="3" /></label> <label for="comment">Comment :<br /></label> <textarea name="content" id="comment" cols="50" rows="8" tabindex="4"><?php echo $commenter_content; ?></textarea> <input name="submit" type="submit" id="submit" tabindex="5" value="Submit" /> </div> </form> <file_sep><?php class PagelessHandler extends ActionHandler { public $theme = null; private $default_fields = array( 'slug' => '' ); /** * Constructor for the default theme handler. Here, we * automatically load the active theme for the installation, * and create a new Theme instance. */ public function __construct() { $this->theme = Themes::create(); } public function act_display_pageless() { $filters = new SuperGlobal($this->default_fields); $filters = $filters->merge($this->handler_vars); $post = Post::get(array('slug' => $filters['slug'])); if ($post instanceof Post) { // Default params $params = array( 'where' => "(pubdate < '{$post->pubdate->sql}' OR (pubdate = '{$post->pubdate->sql}' AND id < {$post->id})) AND content_type = {$post->content_type} AND status = {$post->status}", 'limit' => Options::get('pageless__num_item'), 'orderby' => 'pubdate DESC, id DESC' ); // Additional filters, in other word, handling act_display if (isset($filters['type'])) { if ($filters['type'] === 'tag') { $params['tag_slug'] = $filters['param']; } else if ($filters['type'] === 'date') { $date = explode('/', $filters['param']); $params_count = count($date); switch ($params_count) { case 3: $params['day'] = $date[2]; case 2: $params['month'] = $date[1]; case 1: $params['year'] = $date[0]; default: break; } } else if ($filters['type'] === 'search') { $params['criteria'] = $filters['param']; } } // Get $posts -> Assign $posts to theme -> Display template $posts = Posts::get($params); $this->theme->assign('posts', $posts); $this->theme->display('pageless'); } } } ?><file_sep><?php class RemoteRequestSucks { public static function head( $url ) { $headers = get_headers($url, 1); return self::get_status($headers); } /** * get original status */ protected static function get_status( $headers ) { if ( preg_match('|^HTTP/1\.[01] ([1-5][0-9][0-9]) ?(.*)|', $headers[0], $m) ) { $headers['status'] = $m[1]; $headers['status_name'] = $m[2]; } return $headers; } } <file_sep><div id="footer"> <p>Powered By <a href="http://www.habariproject.org">Habari</a> </p> </div> <div class="pusher"></div> </div> <?php $theme->footer(); ?> </body> </html> <file_sep><?php /** * Redirect anonymous users to the login form. * */ class LockOut extends Plugin { /** * Add update beacon support **/ public function action_update_check() { Update::add( $this->info->name, $this->info->guid, $this->info->version ); } /** * Redirect to theme's login page and fall back on standard one. **/ public function action_template_header() { if ( ! User::identify()->loggedin ) { Utils::redirect( URL::get( 'auth', array( 'page' => 'login' ) ) ); } } } ?> <file_sep><?php if($content->mobile): ?> <a href="<?php echo $content->mobile_off; ?>">Use the standard site.</a> <?php else: ?> <a href="<?php echo $content->mobile_on; ?>">Use the mobile site.</a> <?php endif; ?> <?php // Utils::debug($_template_list, $_template); ?><file_sep><!-- sidebar --> <div id="navigation" class="span-4 last"> <p>Navigation</p> <ul> <li><a href="<?php Site::out_url( 'habari' ); ?>" title="<?php Options::out( 'title' ); ?>"><?php echo $home_tab; ?></a></li> <?php foreach ( $pages as $tab ) { ?> <li><a href="<?php echo $tab->permalink; ?>" title="<?php echo $tab->title; ?>"><?php echo $tab->title; ?></a></li> <?php } ?> </ul> <p>Meta</p> <ul> <?php if ( $user ) { ?> <li><a href="<?php Site::out_url( 'admin' ); ?>" title="Admin area">Admin</a></li> <?php } else { ?> <li><a href="<?php Site::out_url( 'admin' ); ?>" title="Login">Login</a></li> <?php } ?> <li><a href="<?php URL::out( 'atom_feed_comments' ); ?>">Comments Feed</a></li> <li><a href="<?php URL::out( 'atom_feed', array( 'index' => '1' ) ); ?>">Entries Feed</a></li> </ul> </div> <!-- /sidebar --><file_sep><?php /** * TweetSuite Plugin */ class TweetSuite extends Plugin { private $class_name = ''; /** * Required plugin information * @return array The array of information **/ public function info() { return array( 'name' => 'TweetSuite', 'version' => '0.1', 'url' => 'http://habariproject.org/', 'author' => '<NAME>', 'authorurl' => 'http://blog.bcse.info/', 'license' => 'Apache License 2.0', 'description' => 'Display Tweetbacks. STILL VERY BUGGY!', 'copyright' => '2009' ); } /** * Add update beacon support **/ public function action_update_check() { Update::add('TweetSuite', '5d8eb2b0-e609-11dd-ba2f-0800200c9a66', $this->info->version); } public function theme_after_act_display_post(Theme $theme) { $post = $theme->post; $cache_name = $this->class_name . '__' . $post->slug; if (!Cache::has($cache_name)) { $this->update_tweetbacks($theme->post); Cache::set($cache_name, TRUE, 3600); // Update Tweetbacks once an hour } } private function update_tweetbacks(Post $post) { // Get the lastest tweetback in database $tweetbacks = $post->comments->tweetbacks; if ($tweetbacks->count > 0) { $tweet_url = explode('/', $tweetbacks[0]->url); $since_id = end($tweet_url); } else { $since_id = 0; } // Get short urls $aliases = array_filter((array)ShortURL::get($post)); //$aliases[] = $post->permalink; // Do not include original permalink, because Twitter Search has character limit, too. // Construct request URL $url = 'http://search.twitter.com/search.json?'; $url .= http_build_query(array( 'ors' => implode(' ', $aliases), // Post permalink and short-urls 'rpp' => 50, 'since_id' => $since_id // This makes Twiiter only return unread tweets. ), '', '&'); // Get JSON content $call = new RemoteRequest($url); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { throw Error::raise(_t('Unable to contact Twitter.', $this->class_name)); } $response = $call->get_response_body(); // Decode JSON $obj = json_decode($response); if (isset($obj->results) && is_array($obj->results)) { $obj = $obj->results; } else { throw Error::raise(_t('Response is not correct, Twitter server may be down or API is changed.', $this->class_name)); } // Store new tweetbacks into database foreach ($obj as $tweet) { Comment::create(array( 'post_id' => $post->id, 'name' => $tweet->from_user, 'url' => sprintf('http://twitter.com/%1$s/status/%2$d', $tweet->from_user, $tweet->id), 'content' => $tweet->text, 'status' => Comment::STATUS_APPROVED, 'date' => HabariDateTime::date_create($tweet->created_at), 'type' => Comment::TWEETBACK )); } } /** * $theme->show_tweetbacks(); * @param Theme $theme The theme that will display the template **/ public function theme_show_tweetbacks($theme, $params = array()) { return $theme->fetch('tweetbacks'); } /** * On plugin activation, set the default options */ public function action_plugin_activation($file) { if (realpath($file) == __FILE__) { $this->class_name = strtolower(get_class($this)); foreach ($this->default_options as $name => $value) { $current_value = Options::get($this->class_name . '__' . $name); if (is_null($current_value)) { Options::set($this->class_name . '__' . $name, $value); } } } } /** * On plugin init, add the template included with this plugin to the available templates in the theme */ public function action_init() { $this->class_name = strtolower(get_class($this)); $this->load_text_domain($this->class_name); $this->add_template('tweetbacks', dirname(__FILE__) . '/tweetbacks.php'); } public function filter_comment_profile_url($user, $comment) { return 'http://twitter.com/' . $comment->name; } public function filter_comment_content($content, $comment) { if ($comment->type == Comment::TWEETBACK) { // Linkify URIs $content = preg_replace( '#(?<uri>' . '(?<scheme>[a-z][a-z0-9-.+]+)://' . '(?:(?<username>[a-z0-9-_.!~*\'()%]+)(?::(?<password>[a-z0-9-_.!~*\'()%;&=+$,]+))?@)?' . '(?<host>(?:(?:(?:[a-z0-9]+|[a-z0-9][a-z0-9\-]+[a-z0-9]+)\.)+(?:[a-z]|[a-z][a-z0-9\-]+[a-z0-9])+|[0-9]{1,3}(?:\.[0-9]{1,3}){3})\.?)' . '(?::(?<port>\d{2,5}))?' . '(?<path>(?:/[a-z0-9\'\-!$%&()*,.:;@_~+=]+|[a-z0-9\'\-!$%&()*,.:;?@_~+=][a-z0-9\'\-!$%&()*,./:;?@_~+=]+)+)?' . '(?<query>\?[a-z0-9\'\-!$%&()*,./:;?@[]_{}~+=]+)?' . '(?<fragment>\#[a-z0-9\'\-!$%&()*,./:;?@_~+=]+)?' . ')#i', '<a href="${1}">${5}${7}</a>', $content); // Linkify Users $content = preg_replace('|\B@([a-z0-9_]+)\b|i', '@<a href="http://twitter.com/${1}">${1}</a>', $content); } return $content; } } /** * ShortURL Class */ class ShortURL { /** * Generate short urls and store in post info */ public static function get(Post $post) { $shorten_url_services = array( 'bitly' => NULL, 'metamark' => NULL, 'orztw' => NULL, // 'snipurl' => NULL, // I have no idea why this alway failed. 'tinyurl' => NULL, // 'trimurl' => NULL, // tr.im always returns different shorten url, therefore it's useless to generate it beforehand. 'tweetburner' => NULL, 'zima' => NULL ); $ret = $post->info->short_url; foreach ($shorten_url_services as $service => $url) { if (!isset($ret[$service]) || !is_string($ret[$service])) { $ret[$service] = self::strip_protocol(self::$service($post->permalink)); } } $post->info->short_url = $ret; $post->info->commit(); return $ret; } public static function strip_protocol($url) { $url = trim($url, '/'); $url = str_replace('http://www.', '', $url); $url = str_replace('http://', '', $url); return $url; } public static function bitly($url) { $call = new RemoteRequest('http://api.bit.ly/shorten'); $call->set_params(array( 'version' => '2.0.1', 'login' => 'bcse', 'apiKey' => '<KEY>', 'longUrl' => $url )); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { return FALSE; } $response = $call->get_response_body(); $obj = json_decode($response); if (is_object($obj) && $obj->statusCode === 'OK') { return current($obj->results)->shortUrl; } return FALSE; } public static function metamark($url) { $call = new RemoteRequest('http://metamark.net/api/rest/simple?long_url=' . urlencode($url), 'POST'); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { return FALSE; } return trim($call->get_response_body()); } public static function orztw($url) { $call = new RemoteRequest('http://0rz.tw/createget.php?url=' . urlencode($url)); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { return FALSE; } $response = $call->get_response_body(); if (preg_match('@value="(http://0rz.tw/[\d\w-_]+)"@i', $response, $matches)) { return $matches[1]; } return FALSE; } public static function snipurl($url) { $call = new RemoteRequest('http://snipurl.com/site/getsnip', 'POST'); $call->set_params(array( 'sniplink' => $url, 'snipuser' => 'bcse', 'snipapi' => '9fa84accb6cee0451a91feaf37e961ad' )); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { Utils::debug($call, $result); return FALSE; } $response = $call->get_response_body(); Utils::debug($response); $obj = new SimpleXMLElement($response); if ($obj instanceof SimpleXMLElement && isset($obj->id)) { return $obj->id; } return FALSE; } public static function tinyurl($url) { $call = new RemoteRequest('http://tinyurl.com/create.php?url=' . urlencode($url)); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { return FALSE; } $response = $call->get_response_body(); if (preg_match('@<b>(http://tinyurl.com/[\d\w-_]+)</b>@i', $response, $matches)) { return $matches[1]; } return FALSE; } public static function trimurl($url) { $call = new RemoteRequest('http://tr.im/api/trim_url.json?url=' . urlencode($url)); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { return FALSE; } $response = $call->get_response_body(); $obj = json_decode($response); if (is_object($obj) && $obj->status->code === '200') { return $obj->url; } return FALSE; } public static function tweetburner($url) { $call = new RemoteRequest('http://tweetburner.com/links?link[url]=' . urlencode($url), 'POST'); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { return FALSE; } return trim($call->get_response_body()); } public static function zima($url) { $call = new RemoteRequest('http://zi.ma/'); $call->set_params(array( 'module' => 'ShortURL', 'file' => 'Add', 'mode' => 'API', 'url' => $url )); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { return FALSE; } return trim($call->get_response_body()); } } ?> <file_sep><?php /** * DiggBar Blocker Plugin * * Inspired by http://daringfireball.net/2009/04/how_to_block_the_diggbar **/ class DiggbarBlocker extends Plugin { /** * Required plugin information * @return array The array of information **/ public function info() { return array( 'name' => 'DiggBar Blocker', 'version' => '0.2', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Prevents DiggBar from framing your site', 'copyright' => '2009' ); } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'DiggbarBlocker', '737c4ad6-0de4-4f7c-950c-1d4f70303139', $this->info->version ); } /** * Add help text to plugin configuration page **/ public function help() { $help = _t( "This plugin Prevents DiggBar from framing your site." ); return $help; } /** * Add actions to the plugin page for this plugin * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id **/ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = 'Configure'; } return $actions; } /** * Respond to the user selecting an action on the plugin page * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook **/ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { if ( $action == _t( 'Configure' ) ) { $ui = new FormUI( strtolower( get_class( $this ) ) ); $reload_fieldset = $ui->append( 'fieldset', 'reload', _t( 'No Message' ) ); $reload_page = $reload_fieldset->append( 'checkbox', 'reload', 'option:diggbarblocker__reload', _t( 'Instead of displaying a message, reload the page without the bar' ) ); $message_fieldset = $ui->append( 'fieldset', 'message_settings', _t( 'Message Settings' ) ); $message = $message_fieldset->append( 'textarea', 'message', 'option:diggbarblocker__message', _t( 'If the box above is not checked, display this to Diggbar-using visitors:' ) ); $message->rows = 2; $message->class[] = 'resizable'; $link = $message_fieldset->append( 'checkbox', 'addlink', 'option:diggbarblocker__addlink', _t( 'Add a link to the target page.' ) ); $ui->append( 'submit', 'save', _t('Save') ); $ui->out(); } } } /** * Set default text & link behavior **/ public function action_plugin_activation( $file ) { if ( Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__) ) { if ( Options::get( 'diggbarblocker__message' ) == null ) { Options::set( 'diggbarblocker__message', _t('This site does not support use of the DiggBar.') ); } if ( Options::get( 'diggbarblocker__add_link' ) == null ) { Options::set( 'diggbarblocker__addlink', 1 ); } } } /** * Return either a message for the Diggbar user, or just reload the page. * @return string buffer of either the message displayed, or reload headers. **/ public function filter_final_output( $buffer ) { if ( preg_match( '#http://digg.com/\w{1,8}/*(\?.*)?$#', $_SERVER[ 'HTTP_REFERER' ]) ) { if ( Options::get( 'diggbarblocker__reload' ) ) { $buffer = '<SCRIPT TYPE="text/JavaScript"> if (window != top) { top.location.replace( self.location.href ); } </SCRIPT>'; } else { $buffer = '<p>' . Options::get( 'diggbarblocker__message' ) .'</p>' . ( Options::get( 'diggbarblocker__addlink' ) ? _t( '<p>Open <a title="Open in a new window" target="_top" href="') . $_SERVER[ 'SCRIPT_URI' ] . '">' . $_SERVER[ 'SCRIPT_URI' ] . _t('</a> in a new tab or window to view it.</p>') : ''); } } return $buffer; } } ?> <file_sep><ul class="items"> <?php foreach ( $data[1] as $k => $v ) { ?> <li class="item clear"> <span class="message pct75 minor"><?php echo $k; ?></span> <span class="date pct15 minor"><?php echo $v; ?> views</span> <span class="comments pct10"><?php echo number_format( (($v / $data_total) * 100), 2); ?>%</span> </li> <?php } ?> </ul> <file_sep><div id="comments" class="entry column span-24"> <div class="left column span-6 first"> <h2></h2> </div> <div class="center comments column span-13"> <ol id="commentlist"> <?php if ( $post->comments->comments->approved->count ) { foreach ( $post->comments->comments->approved as $comment ) { ?> <li id="comment-<?php echo $comment->id; ?>" class="comment"> <span class="commentauthor"> <strong><?php echo $comment->name; ?></strong><br> <a href="<?php echo $comment->url; ?>" rel="external">Stroll on over and visit <?php echo $comment->name; ?></a> <br> <a href="#comment-<?php echo $comment->id; ?>" title="Time of this comment" class="commentdate"><?php echo $comment->date_out; ?></a> </span> <div class="commentcontent"> <?php echo $comment->content_out; ?> </div> </li> <?php } } else { ?> <li><?php _e('There are currently no comments, why don\'t you leave one?'); ?></li> <?php } ?> </ol> <?php if( $post->comments->pingbacks->count ) : ?> <h2>Pingbacks &amp; Trackbacks</h2> <div id="pings"> <ol id="pinglist"> <?php foreach ( $post->comments->pingbacks->approved as $pingback ) : ?> <li id="ping-<?php echo $pingback->id; ?>"> <a href="<?php echo $pingback->url; ?>" title=""><?php echo $pingback->name; ?></a> &raquo; <?php echo $pingback->content; ?> </li> <?php endforeach; ?> </ol> </div> <?php endif; ?> <?php if ( ! $post->info->comments_disabled ) { ?> <div class="comments"> <h2 id="respond" class="reply">Leave a Reply</h2> <?php $class= ''; $cookie= 'comment_' . Options::get( 'GUID' ); $commenter_name= ''; $commenter_email= ''; $commenter_url= ''; if ( $user ) { $commenter_name= $user->username; $commenter_email= $user->email; $commenter_url= Site::get_url('habari'); } elseif ( isset( $_COOKIE[$cookie] ) ) { list( $commenter_name, $commenter_email, $commenter_url )= explode( '#', $_COOKIE[$cookie] ); } elseif ( isset( $_SESSION['comment'] ) ) { $details= Session::get_set('comment'); $commenter_name= $details['name']; $commenter_email= $details['email']; $commenter_url= $details['url']; } if ( Session::has_errors() ) { Session::messages_out(); } ?> <br> <form action="<?php URL::out( 'submit_feedback', array( 'id' => $post->id ) ); ?>" method="post" id="commentform"> <div id="comment-personaldetails"> <p> <input type="text" name="name" id="name" value="<?php echo $commenter_name; ?>" size="22" tabindex="1"> <label for="name"><small><strong>Name</strong></small></label> </p> <p> <input type="text" name="email" id="email" value="<?php echo $commenter_email; ?>" size="22" tabindex="2"> <label for="email"><small><strong>Mail</strong> (will not be published)</small></label> </p> <p> <input type="text" name="url" id="url" value="<?php echo $commenter_url; ?>" size="22" tabindex="3"> <label for="url"><small><strong>Website</strong></small></label> </p> </div> <p> <textarea name="content" id="content" cols="55" rows="10" tabindex="4"> <?php if ( isset( $details['content'] ) ) { echo $details['content']; } ?> </textarea> </p> <p><input type="submit" value="Add your comment" id="submit"></p> </form> </div> <?php } ?> </div> <div class="right column span-5 last"> <h2><a name="#comments">Comments</a></h2> </div> </div><file_sep><?php /** * ArcticIceTheme is a custom Theme class for the Arctic Ice theme. * */ /** * A custom theme for Arctic Ice output */ class ArcticIceTheme extends Theme { public function action_init_theme( $theme ) { // Apply Format::autop() to post content... Format::apply( 'autop', 'post_content_out' ); // Apply Format::autop() to comment content... Format::apply( 'autop', 'comment_content_out' ); // Apply Format::tag_and_list() to post tags... Format::apply( 'tag_and_list', 'post_tags_out' ); // Only uses the <!--more--> tag, with the 'more' as the link to full post Format::apply_with_hook_params( 'more', 'post_content_out', 'more' ); // Creates an excerpt option. echo $post->content_excerpt; Format::apply( 'autop', 'post_content_excerpt'); Format::apply_with_hook_params( 'more', 'post_content_excerpt', ' Read more...', 60, 1 ); // Apply Format::nice_date() to post date... Format::apply( 'nice_date', 'post_pubdate_out', 'F j, Y' ); Format::apply( 'nice_date', 'post_pubdate_datetime', 'c'); // Apply Format::nice_time() to post date... //Format::apply( 'nice_time', 'post_pubdate_out', 'g:ia' ); // Apply Format::nice_date() to comment date Format::apply( 'nice_date', 'comment_date_out', 'F j, Y g:ia'); } /** * Configuration form for the ArcticIceTheme **/ public function action_theme_ui( $theme ) { $ui = new FormUI( __CLASS__ ); $slugs = $ui->append( 'textarea', 'slugs', __CLASS__.'__slugs', _t( 'Terms to exclude from pages:' ) ); $slugs->rows = 8; $slugs->class[] = 'resizable'; $ui->append( 'submit', 'save', _t( 'Save' ) ); $ui->set_option( 'success_message', _t( 'Options saved' ) ); $ui->out(); // $ui->append( 'text', 'tags_count', __CLASS__.'__tags_count', _t( 'Tag Cloud Count:' ), 'optionscontrol_text' ); // $ui->tags_count->helptext = _t( 'Set to the number of tags to display on the default "cloud".' ); } /** * Add additional template variables to the template output. * * This function gets executed *after* regular data is assigned to the * template. So the values here, unless checked, will overwrite any existing * values. */ public function add_template_vars() { parent::add_template_vars(); $opts = Options::get_group( __CLASS__ ); $terms = array(); if( isset( $opts['slugs'] ) ) { $slugs = explode( '\r\n', $opts['slugs'] ); foreach( $slugs as $slug ) { $terms[] = Tags::get_by_slug( $slug ); } } if( !$this->template_engine->assigned( 'pages' ) ) { // $this->assign( 'pages', Posts::get( array( 'content_type' => 'page', 'status' => 'published', 'vocabulary' => array( 'not' => array( Tags::get_by_slug( 'site-policy' ) ) ), 'nolimit' => 1 ) ) ); // $this->assign( 'pages', Posts::get( array( 'content_type' => 'page', 'status' => 'published', 'vocabulary' => array( 'tags:not:term' => 'site-policy' ), 'nolimit' => 1 ) ) ); $this->assign( 'pages', Posts::get( array( 'content_type' => 'page', 'status' => 'published', 'vocabulary' => array( 'not' => $terms ), 'nolimit' => 1 ) ) ); } } public function action_template_header( $theme ) { // Add the stylesheets to the stack for output Stack::add( 'template_stylesheet', array( Site::get_url( 'theme') . '/style.css', 'screen') ); Stack::add( 'template_stylesheet', array( Site::get_url( 'theme') . '/custom.css', 'screen') ); Stack::add( 'template_stylesheet', array( Site::get_url( 'theme') . '/print.css', 'print') ); } public function theme_title( $theme ) { $out = ''; if( $theme->request->display_entry || $theme->request->display_page && isset( $theme->post ) ) { $out = $theme->post->title . ' - '; } else if( $theme->request->display_entries_by_tag && isset( $theme->posts ) ) { $out = $theme->tag . ' - '; } $out .= Options::get( 'title' ); return $out; } public function theme_next_post_link( $theme ) { $next_link = ''; if( isset( $theme->post ) ) { $next_post = $theme->post->ascend(); if( ( $next_post instanceOf Post ) ) { $next_link = '<a href="' . $next_post->permalink. '" title="' . $next_post->title .'" >' . '&laquo; ' .$next_post->title . '</a>'; } } return $next_link; } public function theme_prev_post_link( $theme ) { $prev_link = ''; if( isset( $theme->post ) ) { $prev_post = $theme->post->descend(); if( ( $prev_post instanceOf Post) ) { $prev_link= '<a href="' . $prev_post->permalink. '" title="' . $prev_post->title .'" >' . $prev_post->title . ' &raquo;' . '</a>'; } } return $prev_link; } public function theme_commenter_link( $comment ) { $link = ''; if( strlen( $comment->url ) && $comment->url != 'http://' ) { $link = '<a href="' . $comment->url . '" >' . $comment->name . '</a>'; } return $link; } public function theme_feed_site( $theme ) { return URL::get( 'atom_feed', array( 'index' => '1' ) ); } public function theme_comment_form( $theme ) { $theme->post->comment_form()->out(); } public function theme_all_entries( $theme ) { $out = ''; $posts = Posts::get( array( 'content_type' => 'entry', 'status' => 'published', 'nolimit' => 1 ) ); foreach( $posts as $post ) { $out .= "<p><a href=\"{$post->permalink}\" rel=\"bookmark\" title=\"{$post->title}\">{$post->title}</a> ( {$post->comments->approved->count} )</p>"; } return $out; } public function action_form_comment( $form, $post, $context ) { $form->cf_content->cols = 57; $form->cf_commenter->size = 50; $form->cf_email->size = 50; $form->cf_url->size = 50; } } ?> <file_sep><?php class Chicklet extends Plugin { public function info() { return array( 'name' => 'Chicklet', 'author' => 'Habari Community', 'description' => 'Fetches the statistics for your Feedburner feed.', 'url' => 'http://habariproject.org', 'version' => '0.1', 'license' => 'Apache License 2.0' ); } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t('Configure'); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure') : $ui = new FormUI( strtolower( get_class( $this ) ) ); $customvalue = $ui->append( 'text', 'feedname', 'chicklet__feedname', _t('Feed Address:') ); $customvalue = $ui->append( 'submit', 'submit', _t('Save') ); $ui->out(); break; } } } function action_add_template_vars( $theme ) { $count = $this->fetch(); $theme->subscribers = $count; } public function fetch() { if(Cache::get('chickler_subscribercount') == NULL) { $url = "http://api.feedburner.com/awareness/1.0/GetFeedData?uri=" . Options::get('chicklet__feedname') ; $remote = RemoteRequest::get_contents($url); $xml = new SimpleXMLElement($remote); $count = intval($xml->feed->entry['circulation']); Cache::set('chickler_subscribercount', $count); } else { $count = Cache::get('chickler_subscribercount'); } return $count; } } ?><file_sep>CREATE TABLE {dir_plugin_versions} ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, post_id INT UNSIGNED NOT NULL, url VARCHAR(255) NOT NULL, version VARCHAR(255) NOT NULL, md5 VARCHAR(255) NOT NULL, status VARCHAR(255) NOT NULL, habari_version VARCHAR(255) NOT NULL, requires VARCHAR(255), provides VARCHAR(255), recommends VARCHAR(255), description TEXT, source_link VARCHAR(255), author VARCHAR(255) NOT NULL, author_url VARCHAR(255) NOT NULL, license VARCHAR(255) NOT NULL, screenshot VARCHAR(255), instructions TEXT, UNIQUE KEY id (id) ); CREATE TABLE {dir_theme_versions} ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, post_id INT UNSIGNED NOT NULL, url VARCHAR(255) NOT NULL, version VARCHAR(255) NOT NULL, md5 VARCHAR(255) NOT NULL, status VARCHAR(255) NOT NULL, habari_version VARCHAR(255) NOT NULL, requires VARCHAR(255), provides VARCHAR(255), recommends VARCHAR(255), description TEXT, source_link VARCHAR(255), author VARCHAR(255) NOT NULL, author_url VARCHAR(255) NOT NULL, license VARCHAR(255) NOT NULL, screenshot VARCHAR(255), instructions TEXT, UNIQUE KEY id (id) ); <file_sep><?php $theme->display('header');?> <div class="create"> <?php echo $form; ?> </div> <div id="crontab" class="container settings"> <div style="float:right">Current Time: <?php HabariDateTime::date_create('now')->out(); ?></div> <h2><?php _e('Current Crontab Entries', 'crontabmanager'); ?></h2> <?php foreach($crons as $cron): ?> <div class="item plugin clear" id="title"> <div class="head"> <b><?php echo $cron->name; ?></b> <span class="dim"><?php _e('calls', 'crontabmanager'); ?></span> <?php echo is_callable($cron->callback) ? ( is_array($cron->callback) ? "{$cron->callback[0]}::{$cron->callback[1]}()" : "{$cron->callback}()" ) : "Plugins::filter_{$cron->callback}"; ?> <ul class="dropbutton"> <li><a href="<?php URL::out('admin', array('page'=>'cronjob', 'cron_id'=>$cron->cron_id)); ?>"><?php _e('Edit', 'crontabmanager'); ?></a></li> <li><a href="<?php URL::out('admin', array('page'=>'crontab', 'action'=>'run', 'cron_id'=>$cron->cron_id)); ?>"><?php _e('Run Now', 'crontabmanager'); ?></a></li> <li><a href="<?php URL::out('admin', array('page'=>'crontab', 'action'=>'delete', 'cron_id'=>$cron->cron_id)); ?>"><?php _e('Delete', 'crontabmanager'); ?></a></li> </ul> </div> <div class="description pct50"> <p><?php _e('Result:', 'crontabmanager'); ?> <b><?php echo $cron->result ? ucfirst($cron->result) : _t('Not Run', 'crontabmanager'); ?></b></p> <?php echo $cron->description; ?> </div> <?php if($i = $cron->increment % 86400 == 0){ $inc = sprintf(_n('Day', '%s Days', $i, 'crontabmanager'), $i); } else { $inc = _t('%s Seconds', array($cron->increment), 'crontabmanager'); } ?> <ul class="description pct50"> <li><?php _e('Runs Every', 'crontabmanager'); ?> <?php echo $inc; ?></li> <li><?php _e('Last Run:', 'crontabmanager'); ?> <?php echo $cron->last_run ? $cron->last_run->get() : 'Not Run'; ?></li> <li><?php _e('Next Run:', 'crontabmanager'); ?> <?php $cron->next_run->out(); ?></li> <li><?php _e('Starts On:', 'crontabmanager'); ?> <?php $cron->start_time->out(); ?></li> <li><?php _e('Ends On:', 'crontabmanager'); ?> <?php echo $cron->end_time ? $cron->end_time->get() : 'Never'; ?></li> </ul> </div> <?php endforeach; ?> </div> <?php $theme->display('footer');?> <file_sep><!-- comments --> <?php // Do not delete these lines if ( ! defined('HABARI_PATH' ) ) { die( _t('Please do not load this page directly. Thanks!') ); } ?> <div id="comments"> <?php if ( ! $post->info->comments_disabled || $post->comments->moderated->count ) { ?> <div id="comments-list" class="comments"> <h3 class="comments-count"><span><?php echo $post->comments->moderated->count; ?> <?php _e('Responses to %s', array($post->title)); ?></span></h3> <div class="metalinks"> <span class="commentsrsslink"><a href="<?php echo $post->comment_feed_link; ?>"><?php _e('Feed for this Entry'); ?></a></span> </div> <ol id="commentlist"> <?php if ( $post->comments->moderated->count ) { $count = 0; foreach ( $post->comments->moderated as $comment ) { $count++; if ( 0 == ( $count % 2 ) ) { $class = ''; } else { $class = 'alt'; } if ( $comment->email == $post->author->email ) { $class = 'comment-author-admin'; } if ( $comment->status == Comment::STATUS_UNAPPROVED ) { $class = 'unapproved'; } ?> <li id="comment-<?php echo $comment->id; ?>" class="comment <?php echo $class; ?>"> <?php if ( Plugins::is_loaded('Gravatar') ) { ?> <img src="<?php echo $comment->gravatar; ?>" class="gravatar" alt="gravatar" /> <?php } else { ?> <img src="http://www.gravatar.com/avatar.php?gravatar_id=<?php echo md5( $comment->email ); ?>&amp;size=48&amp;rating=G" alt="gravatar" class="gravatar" /> <?php } ?> <?php $date1 = strtotime( $comment->date ); $date2 = $comment->date; ?> <div class="comment-info"> <span class="comment-author vcard"><a href="<?php echo $comment->url; ?>" rel="external"><?php echo $comment->name; ?></a></span> <?php _e('at'); ?> <span class="comment-meta"><a href="#comment-<?php echo $comment->id; ?>" title="<?php _e('Time of this Comment'); ?>"><?php if($date1==""){ echo $comment->date->out('F j, Y g:ia'); } else { echo $comment->date; } ?></a></span> </div> <div class="comment-content"> <?php echo $comment->content_out; ?> <?php if ( $comment->status == Comment::STATUS_UNAPPROVED ) : ?> <em class="unapproved"><?php _e('Your comment is awaiting moderation'); ?></em><?php endif; ?> </div> </li> <?php } } ?> </ol> </div> <?php } else if ( $post->info->comments_disabled ) { ?> <p class="nocomment"><?php _e('Comments are closed for this post.'); ?></p> <?php } else { ?> <p class="nocomment"><?php _e('There are currently no comments.'); ?></p> <?php } if ( ! $post->info->comments_disabled ) { include_once( 'commentform.php' ); } ?> </div><!-- #comments --> <file_sep><?php /* Diff (C) <NAME> 2007 <http://www.paulbutler.org/> May be used and distributed under the zlib/libpng license. modified from http://www.paulbutler.org/projects/simplediff/simplediff.phps */ class RevisionDiff { public static function format_diff( $old, $new ) { $old = str_replace( "\r", '', trim( $old ) ); $new = str_replace( "\r", '', trim( $new ) ); $old_lines = explode( "\n", $old ); $new_lines = explode( "\n", $new ); $diff = self::diff( $old_lines, $new_lines ); $html = '<table class="diff" style="width: 100%;">'; $diff_count = count( $diff ); for ( $i = 0; $i < $diff_count; $i++ ) { if ( is_array( $diff[$i] ) && ( !empty( $diff[$i]['d'] ) || !empty( $diff[$i]['i'] ) ) ) { $del_count = count( $diff[$i]['d'] ); $ins_count = count( $diff[$i]['i'] ); if ( isset( $diff[$i - 1] ) && is_string( $diff[$i - 1] ) ) { $html.= '<tr><td colspan="4" style="width: 100%;">' . ( $i - 1 ) . ' Line</td></tr>'; $html.= '<tr><td style="width: 5%;"></td><td style="width: 45%; background-color: #efefef;">' . $diff[$i - 1] . '</td><td style="width: 5%;"></td><td style="width: 45%; background-color: #efefef;">' . $diff[$i - 1] . '</td></tr>'; } else { $html.= '<tr><td colspan="4" style="width: 100%;">' . $i . ' Line</td></tr>'; } $html.= '<tr>'; // Replace if ( $del_count != 0 && $ins_count != 0 ) { $html.= '<td style="width: 5%; text-align: right;">-</td><td style="width: 45%; background-color: #ffffbb;">'; for ( $j = 0; $j < $del_count; $j++ ) { $html.= $diff[$i]['d'][$j] . '<br />'; } $html.= '</td><td style="width: 5%; text-align: right;">+</td><td style="width: 45%; background-color: #eeffee;">'; for ( $j = 0; $j < $ins_count; $j++ ) { $html.= $diff[$i]['i'][$j] . '<br />'; } $html.= '</td>'; } // Delete elseif ( $del_count != 0 ) { $html.= '<td style="width: 5%; text-align: right;">-</td><td style="width: 45%; background-color: #ffffbb;">'; for ( $j = 0; $j < $del_count; $j++ ) { $html.= $diff[$i]['d'][$j] . '<br />'; } $html.= '</td><td colspan="2" class="pct35"></td>'; } // Insert elseif ( $ins_count != 0 ) { $html.= '<td colspan="2" style="width: 50%;"></td><td style="width: 5%; text-align: right;">+</td><td style="width: 45%; background-color: #eeffee;">'; for ( $j = 0; $j < $ins_count; $j++ ) { $html.= $diff[$i]['i'][$j] . '<br />'; } $html.= '</td>'; } $html.= '</tr>'; if ( isset( $diff[$i + 1] ) && is_string( $diff[$i + 1] ) ) { $html.= '<tr><td style="width: 5%;"></td><td style="width: 45%; background-color: #efefef;">' . $diff[$i + 1] . '</td><td style="width: 5%;"></td><td style="width: 45%; background-color: #efefef;">' . $diff[$i + 1] . '</td></tr>'; } } } $html.= '</table>'; return $html; } /** * Diff Lines * * @access public */ public static function diff( $old_lines, $new_lines ) { $maxlen = 0; foreach ($old_lines as $oindex => $ovalue ) { $nkeys = array_keys( $new_lines, $ovalue ); foreach ($nkeys as $nindex) { $matrix[$oindex][$nindex]= isset( $matrix[$oindex - 1][$nindex - 1] ) ? $matrix[$oindex - 1][$nindex - 1] + 1 : 1; if ( $matrix[$oindex][$nindex] > $maxlen ){ $maxlen = $matrix[$oindex][$nindex]; $omax = $oindex + 1 - $maxlen; $nmax = $nindex + 1 - $maxlen; } } } if ( $maxlen == 0 ) return array( array( 'd' => $old_lines, 'i' => $new_lines ) ); return array_merge( self::diff( array_slice( $old_lines, 0, $omax ), array_slice( $new_lines, 0, $nmax ) ), array_slice( $new_lines, $nmax, $maxlen ), self::diff( array_slice( $old_lines, $omax + $maxlen ), array_slice( $new_lines, $nmax + $maxlen ) ) ); } } ?><file_sep><?php class PrePublish extends Plugin { public function action_publish_post( $post ) { if ( Post::status_name( $post->status ) == 'scheduled' ) { $post->status = Post::status( 'published' ); } } } ?> <file_sep><ul id="deliciousfeed"> <?php if ( !isset( $content->error ) ): ?> <?php foreach ( $content->bookmarks as $post ): ?> <li class="delicious-post"><a href="<? echo $post->url; ?>" title="<?php echo Utils::htmlspecialchars( $post->desc ); ?>"><?php echo Utils::htmlspecialchars( $post->title ); ?></a></li> <?php endforeach; ?> <?php else: ?> <li class="delicious-error"><?php echo $content->error; ?></li> <?php endif; ?> </ul><file_sep><?php $theme->display('header'); ?> <div class="container"> <h2><?php _e( 'Manage Blogroll', 'blogroll' ); ?></h2> <p> <?php _e( 'Below you can view and edit blogroll links. You can also import links from an OPML file.', 'blogroll' ); ?> <?php printf( _t( 'Or you can <a href="%s">publish a new Blogroll link</a>.', 'blogroll' ), URL::get( 'admin', 'page=publish&content_type=link' ) ); ?> </p> </div> <?php $form->out(); ?> <?php $this->display('footer'); ?><file_sep>/** * @author <NAME> */ jQuery(document).ready(function($){ //make sure it doesn't affect the home page if ( $('#post_details').length > 0 ){ //get the show details link $('#post_details_link a').removeAttr('href').click(fwpbShowDetails); //get the show photos link $('#post_content_link a').removeAttr('href').click(fwpbShowPhoto); } function fwpbShowDetails(){ //find wa bits what need hiding and hide them $('#post_content').hide(); $('#post_details_link').hide(); //find wa bits what need showing and show them $('#post_content_link').show(); $('#post_details').show(); } function fwpbShowPhoto(){ //find wa bits what need hiding and hide them $('#post_content_link').hide(); $('#post_details').hide(); //find wa bits what need showing and show them $('#post_content').show(); $('#post_details_link').show(); } });<file_sep><?php class EmailHeaders { public $headers_raw = array(); public $headers = array(); public function __construct($headers) { $this->headers_raw = $headers; $this->parse_headers($headers); } public function get($header) { if (array_key_exists($header, $this->headers)) { return $this->headers[$header]; } else { return false; } } public function all() { $head = ''; foreach ($this->headers as $h => $v) { if (is_array($v)) { $head .= $this->implode($h, $v); } elseif ($h) { $head .= "$h: $v\n"; } else { $head .= "$v\n"; } } return $head; } private function implode($header, $value) { $head = ''; foreach ($value as $v) { if (is_array($v)) { $head .= $this->implode('', $v); } else { $head .= "$header: $v\n"; } } return $head; } public function set($header, $value) { $this->headers[$header] = $value; return $this->headers[$header]; } public function remove($header) { unset($this->headers[$header]); } private function parse_headers($headers) { $last_head = ''; $lines = explode("\n", $headers); foreach ($lines as $line) { if (preg_match("/^([a-zA-Z0-9\-_]+): (.*)/", $line, $m)) { $this->add_header(strtolower($m[1]), $m[2]); $last_head = strtolower($m[1]); } else { // it's a multi-line header if (is_array($this->headers[$last_head])) { $this->headers[$last_head][count($this->headers[$last_head])-1] .= " $line"; } else { $this->headers[$last_head] .= " $line"; } } } } public function add_header($header, $value) { if (array_key_exists($header, $this->headers)) { if (!is_array($this->headers[$header])) { $this->headers[$header] = array($this->headers[$header]); } $this->headers[$header][] = $value; } else { $this->headers[$header] = $value; } } } <file_sep><div id="googlead"> <?php echo $content->code ?> </div> <file_sep><?php class FeedBurner extends Plugin { /** * Feed groups used in the dashboard statistics module * The key is the title of the statistic, * the value is an array of Feedburner feeds based on the array above ($feedburner_feeds) * * You shouldn't have to edit this, that's why it is not in the FormUI (options) */ private static $feed_groups = array( 'entries' => array( 'introspection', 'collection' ), 'comments' => array( 'comments' ), ); /** * Required Plugin Informations */ public function info() { return array( 'name' => 'FeedBurner', 'version' => '1.6', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Feedburner plugin for Habari', 'copyright' => '2007' ); } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'FeedBurner', '856031d0-3c7f-11dd-ae16-0800200c9a66', $this->info->version ); } /** * Saves default (example) data */ public function action_plugin_activation( $file ) { if ( realpath( $file ) == __FILE__ ) { Modules::add( 'Feedburner' ); if ( !Options::get( 'feedburner__installed' ) ) { Options::set( 'feedburner__introspection', 'HabariProject' ); Options::set( 'feedburner__collection', 'HabariProject' ); Options::set( 'feedburner__comments', 'HabariProject/comments' ); self::reset_exclusions(); Options::set( 'feedburner__installed', true ); } } } public function action_plugin_deactivation( $file ) { if ( realpath( $file ) == __FILE__ ) { Modules::remove_by_name( 'Feedburner' ); } } public function filter_dash_modules( $modules ) { $modules[]= 'Feedburner'; $this->add_template( 'dash_feedburner', dirname( __FILE__ ) . '/dash_feedburner.php' ); return $modules; } /** * Reset exclusions list to default * Adds FeedBurner, FeedValidator.org and Validome.org */ public function reset_exclusions() { Options::set( 'feedburner__exclude_agents', array( 'FeedBurner/1.0 (http://www.FeedBurner.com)', // FeedBurner.com 'FeedValidator/1.3', // FeedValidator.org ) ); Options::set( 'feedburner__exclude_ips', array( '172.16.31.10', // Validome.org ) ); return true; } /** * When the AtomHandler is created, check what action called it * If the action is set in our URL list, intercept and redirect to Feedburner */ public function action_init_atom() { $action = Controller::get_action(); $feed_uri = Options::get( 'feedburner__' . $action ); $exclude_ips = Options::get( 'feedburner__exlude_ips' ); $exclude_agents = Options::get( 'feedburner__exclude_agents' ); if ( $feed_uri != '' ) { if ( !in_array( $_SERVER['REMOTE_ADDR'], ( array ) $exclude_ips ) ) { if ( isset( $_SERVER['HTTP_USER_AGENT'] ) && !in_array( $_SERVER['HTTP_USER_AGENT'], ( array ) $exclude_agents ) ) { ob_clean(); header( 'Location: http://feedproxy.google.com/' . $feed_uri, TRUE, 302 ); die(); } } } } public function filter_dash_module_feedburner( $module, $module_id, $theme ) { $theme->feedburner_stats = $this->theme_feedburner_stats(); $module['content']= $theme->fetch( 'dash_feedburner' ); return $module; } public function theme_feedburner_stats() { if ( Cache::has( 'feedburner_stats' ) ) { $stats = Cache::get( 'feedburner_stats' ); } else { $stats = $this->get_stats(); Cache::set( 'feedburner_stats', $stats ); } return $stats; } private function get_stats() { $stats = array(); foreach ( self::$feed_groups as $type => $feeds ) { $readers = array(); $reach = array(); $reader_str = "FeedBurner Readers ({$type})"; $reach_str = "FeedBurner Reach ({$type})"; foreach ( $feeds as $feed ) { if ( $feed_url = Options::get( 'feedburner__' . $feed ) ) { $awareness_api = 'https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=' . $feed_url; $request = new RemoteRequest( $awareness_api ); if ( Error::is_error( $request->execute() ) ) { EventLog::log('Unable to fetch FeedBurner stats for feed ' . $feed_url, 'error'); continue; } $xml = simplexml_load_string( $request->get_response_body() ); if ( $xml['stat'] == 'fail' ) { $stat_str = "{$xml->err['msg']} ({$type})"; $stats[$stat_str]= ''; } else { $readers[$feed_url]= ( string ) $xml->feed->entry['circulation']; $reach[$feed_url]= ( string ) $xml->feed->entry['reach']; $stats[$reader_str]= array_sum( $readers ); $stats[$reach_str]= array_sum( $reach ); } } } } return $stats; } /** * Add our menu to the FormUI for plugins. * * @param array $actions Array of menu items for this plugin. * @param string $plugin_id A unique plugin ID, it needs to match ours. * @return array Original array with our added menu. */ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id ) { $actions[]= 'Configure'; $actions[]= 'Reset Exclusions'; } return $actions; } /** * Handle calls from FormUI actions. * Show the form to manage the plugin's options. * * @param string $plugin_id A unique plugin ID, it needs to match ours. * @param string $action The menu item the user clicked. */ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id ) { switch ( $action ) { case 'Configure': $fb = new FormUI( 'feedburner' ); $fb_assignments = $fb->append( 'fieldset', 'feed_assignments', 'Feed Assignments' ); $fb_introspection = $fb_assignments->append( 'text', 'introspection', 'feedburner__introspection', 'Introspection:' ); $fb_collection = $fb_assignments->append( 'text', 'collection', 'feedburner__collection', 'Collection:' ); $fb_comments = $fb_assignments->append( 'text', 'comments', 'feedburner__comments', 'Comments:' ); $fb_exclusions = $fb->append( 'fieldset', 'exclusions', 'Exclusions' ); $fb_exclusions_text = $fb_exclusions->append( 'static', 'exclusions', '<p>Exclusions will not be redirected to the Feedburner service.<br><strong>Do not remove default exclusions, else the plugin will break.</strong>' ); $fb_agents = $fb_exclusions->append( 'textmulti', 'exclude_agents', 'feedburner__exclude_agents', 'Agents to exclude', Options::get( 'feedburner__exclude_agents' ) ); $fb_ips = $fb_exclusions->append( 'textmulti', 'exclude_ips', 'feedburner__exclude_ips', 'IPs to exclude', Options::get( 'feedburner__exclude_ips' ) ); $fb->append( 'submit', 'save', _t( 'Save' ) ); $fb->set_option( 'success_message', _t( 'Configuration saved' ) ); $fb->out(); break; case 'Reset Exclusions': if ( self::reset_exclusions() ) { $fb = new FormUI( 'feedburner' ); $fb->append( 'static', 'reset_exclusions', 'feedburner__reset_exclusions', '<p>The exclusions lists have been reset to the defaults.</p>' ); $fb->set_option( 'save_button', false ); $fb->out(); } else { $fb = new FormUI( 'feedburner' ); $fb->append( 'static', 'reset_exclusions', 'feedburner__reset_exclusions', '<p>An error occurred while trying to reset the exclusions lists, please try again or report the problem.</p>' ); $fb->set_option( 'save_button', false ); $fb->out(); } break; } } } } ?> <file_sep><?php class CustomQuery extends Plugin { const VERSION = '0.2'; public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t('Configure', 'customquery'); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure', 'customquery') : $ui = new FormUI( 'customquery' ); foreach ( RewriteRules::get_active()->getArrayCopy() as $rule ) { if ( strpos( $rule->name, 'display_' ) === 0 and ( $rule->name <> 'display_404' )) { $ui->append( 'text', $rule->name,'customquery__'. $rule->name, 'Number of Posts for ' . $rule->name ); } } $ui->append( 'submit', 'save', _t('Save') ); $ui->out(); break; } } } public function action_update_check() { Update::add( 'Custom Query', '1fe407a0-729e-11dd-ad8b-0800200c9a66', $this->info->version ); } public function filter_template_where_filters( $where_filters ) { if ( Options::get( 'customquery__' . URL::get_matched_rule()->name ) ) { $where_filters['limit']= Options::get( 'customquery__' . URL::get_matched_rule()->name ); } return $where_filters; } } ?> <file_sep><?php class prettyPrettyAdmin extends Plugin { public function info() { return array ( 'name' => 'Pretty, Pretty Admin', 'version' => '1', 'author' => '<NAME>', 'description' => 'Adds color to the admin area. License: Do what you want with this plugin. I\'d appreciate a link but you don\'t have to.' ); } public function action_admin_header( $theme ) { Stack::remove('admin_stylesheet', 'admin'); Stack::add('admin_stylesheet', array($this->get_url(true) . 'admin.css', 'screen')); } } ?><file_sep><?php class SimpleCategories extends Plugin { private static $vocabulary = 'categories'; private static $content_type = 'entry'; protected $_vocabulary; public function __get( $name ) { switch ( $name ) { case 'vocabulary': if ( !isset( $this->_vocabulary ) ) { $this->_vocabulary = Vocabulary::get( self::$vocabulary ); } return $this->_vocabulary; } } /** * Add the category vocabulary and create the admin token * **/ public function action_plugin_activation( $file ) { $params = array( 'name' => self::$vocabulary, 'description' => 'A vocabulary for describing Categories', 'features' => array( 'multiple', 'hierarchical' ) ); Vocabulary::create( $params ); // create default access token ACL::create_token( 'manage_categories', _t( 'Manage categories' ), 'Administration', false ); $group = UserGroup::get_by_name( 'admin' ); $group->grant( 'manage_categories' ); } /** * Remove the admin token * **/ public function action_plugin_deactivation( $file ) { // delete default access token ACL::destroy_token( 'manage_categories' ); } /** * Register admin template **/ public function action_init() { $this->add_template( 'categories', dirname( $this->get_file() ) . '/categories_admin.php' ); } /** * Check token to restrict access to the page **/ public function filter_admin_access_tokens( array $require_any, $page ) { switch ( $page ) { case 'categories': $require_any = array( 'manage_categories' => true ); break; } return $require_any; } /** * Display the page **/ public function action_admin_theme_get_categories( AdminHandler $handler, Theme $theme ) { $category_term = false; $parent_term = false; $parent_term_display = _t( 'None', 'simplecategories' ); if( isset( $_GET['action'] ) ) { switch( $_GET['action'] ) { case 'delete': $term = $_GET['category']; $this->delete_category( $term ); break; case 'edit': $term = $_GET['category']; $category_term = $this->vocabulary->get_term( (int)$term ); if ( $category_term ) { $parent_term = $category_term->parent(); if ( $parent_term ) { $parent_term_display = $parent_term->term_display; } } break; } } if ( isset( $GET['category'] ) ) { $term = $_GET['category']; $category_term = $this->vocabulary->get_term( (int)$term ); if ( $category_term ) { $parent_term = $category_term->parent(); if ( $parent_term ) { $parent_term_display = $parent_term->term_display; } } } $options = array( 0 => _t( '(none)', 'simplecategories') ) + $this->vocabulary->get_options(); $form = new FormUI( 'simplecategories' ); if ( $category_term ) { $category_id = $form->append( 'hidden', 'category_id' )->value = $category_term->id; // send this id, for seeing what has changed $fieldset = $form->append( 'fieldset', '', sprintf( _t( 'Edit Category: <b>%1$s</b>' , 'simplecategories' ), $category_term->term_display ) ); } else { $fieldset = $form->append( 'fieldset', '', _t( 'Create a new Category', 'simplecategories' ) ); } $category = $fieldset->append( 'text', 'category', 'null:null', _t( 'Category', 'simplecategories' ), 'formcontrol_text' ); $category->value = !$category_term ? '' : $category_term->term_display; $category->add_validator( 'validate_required' ); $category->class = 'pct30'; $parent = $fieldset->append( 'select', 'parent', 'null:null', _t( 'Parent: <b>%1$s</b> Change Parent to:', array($parent_term_display), 'simplecategories'), $options, 'optionscontrol_select' ); $parent->value = ( !$parent_term ? '': $parent_term->id ); // select the current parent $parent->class = 'pct50'; $save_button = $fieldset->append( 'submit', 'save', _t( 'Save', 'simplecategories' ) ); $save_button->class = 'pct20 last'; // $cancelbtn = $form->append( 'button', 'btn', _t( 'Cancel', 'simplecategories' ) ); // $cancelbtn->id = 'btn'; // $cancelbtn->onclick = 'habari_ajax.get("' . URL::get( 'admin', 'page=categories' ) . '")' ; $cancelbtn = $form->append( 'static', 'btn', '<p id="btn" ><a class="button dashboardinfo" href="' . URL::get( 'admin', 'page=categories' ) . '">' . _t( 'Cancel', 'simplecategories' ) . "</a></p>\n" ); if ( $category_term ) { //editing an existing category $form->on_success( array( $this, 'formui_edit_submit' ) ); } else { //new category $form->on_success( array( $this, 'formui_create_submit' ) ); } $theme->form = $form; $theme->all_categories = $this->vocabulary->get_tree(); $theme->display( 'categories' ); // End everything exit; } public function formui_create_submit( FormUI $form ) { // time to create the new term. $parent = $this->vocabulary->get_term( (int)$form->parent->value ); $new_term = $form->category->value; if ( $parent ) { $this->vocabulary->add_term( $new_term, $parent ); } else { $this->vocabulary->add_term( $new_term ); } // redirect to the page to update the form Utils::redirect( URL::get( 'admin', array( 'page'=>'categories' ) ), true ); } public function formui_edit_submit( FormUI $form ) { if( isset( $form->category ) && ( $form->category->value <> '' ) ) { if( isset( $form->category_id ) ) { $current_term = $this->vocabulary->get_term( (int)$form->category_id->value ); // If there's a changed parent, change the parent. $cur_parent = $current_term->parent(); $new_parent = $this->vocabulary->get_term( (int)$form->parent->value ); if ( $new_parent ) { $this->vocabulary->move_term( $current_term, $new_parent ); } else { $this->vocabulary->move_term( $current_term ); } if ( $form->category->value !== $current_term->term_display ) { // SimpleCategories::rename( $form->category->value, $current_term->term_display ); $this->vocabulary->merge( $form->category->value, array( $current_term->term_display ) ); // If the category has been renamed, modify the term} } } } // redirect to the page to update the form Utils::redirect( URL::get( 'admin', array( 'page'=>'categories' ) ), true ); } /** * Cover both post and get requests for the page **/ public function alias() { return array( 'action_admin_theme_get_categories'=> 'action_admin_theme_post_categories' ); } /** * Add menu item above 'dashboard' **/ public function filter_adminhandler_post_loadplugins_main_menu( array $menu ) { $item_menu = array( 'categories' => array( 'url' => URL::get( 'admin', 'page=categories' ), 'title' => _t( 'Manage blog categories' ), 'text' => _t( 'Categories' ), 'hotkey' => 'W', 'selected' => false, 'access' => array( 'manage_categories' => true ) ) ); $slice_point = array_search( 'dashboard', array_keys( $menu ) ); // Element will be inserted before "groups" $pre_slice = array_slice( $menu, 0, $slice_point ); $post_slice = array_slice( $menu, $slice_point ); $menu = array_merge( $pre_slice, $item_menu, $post_slice ); return $menu; } /** * Add categories to the publish form **/ public function action_form_publish ( $form, $post ) { if ( $form->content_type->value == Post::type( self::$content_type ) ) { $parent_term = null; $descendants = null; $form->append( 'text', 'categories', 'null:null', _t( 'Categories, separated by, commas' ), 'admincontrol_text' ); $form->categories->class = 'check-change'; $form->categories->tabindex = $form->tags->tabindex + 1; $form->move_after( $form->categories, $form->tags ); $form->save->tabindex = $form->save->tabindex + 1; // If this is an existing post, see if it has categories already if ( 0 != $post->id ) { $form->categories->value = implode( ', ', array_values( $this->get_categories( $post ) ) ); } } } /** * Process categories when the publish form is received * **/ public function action_publish_post( $post, $form ) { if ( $post->content_type == Post::type( self::$content_type ) ) { $categories = array(); // $categories = $this->parse_categories( $form->categories->value ); $categories = Terms::parse( $form->categories->value, 'Term', $this->vocabulary ); $this->vocabulary->set_object_terms( 'post', $post->id, $categories ); } } /** * Add a category rewrite rule * @param Array $rules Current rewrite rules **/ public function filter_default_rewrite_rules( $rules ) { $rule = array( 'name' => 'display_entries_by_category', // 'parse_regex' => '%^category/(?P<category_slug>[^/]*)(?:/page/(?P<page>\d+))?/?$%i', 'parse_regex' => '%^category/(?P<category_slug>.*)(?:/page/(?P<page>\d+))?/?$%i', 'build_str' => 'category/{$category_slug}(/page/{$page})', 'handler' => 'UserThemeHandler', 'action' => 'display_entries_by_category', 'priority' => 5, 'description' => 'Return posts matching specified category.', ); $rules[] = $rule; return $rules; } /** * function filter_template_where_filters * Limit the Posts::get call to categories * (uses tag_slug because that's really term under the hood) **/ public function filter_template_where_filters( $filters ) { $vars = Controller::get_handler_vars(); if( isset( $vars['category_slug'] ) ) { $labels = explode( '/', $vars['category_slug'] ); $level = count( $labels ) - 1; $term = $this->get_term( $labels, $level ); // $term = $this->vocabulary->get_term( $vars['category_slug'] ); if ( $term instanceof Term ) { $terms = (array)$term->descendants(); array_push( $terms, $term ); $filters['vocabulary'] = array_merge( $filters['vocabulary'], array( 'any' => $terms ) ); } } return $filters; } /** * function filter_theme_act_display_entries_by_category * Helper function: Display the posts for a category. Probably should be more generic eventually. * Does not appear to work currently. */ public function filter_theme_act_display_entries_by_category( $handled, $theme ) { $paramarray = array(); $paramarray[ 'fallback' ] = array( 'category.{$category}', 'category', 'multiple', ); // Makes sure home displays only entries ... maybe not necessary. Probably not, in fact. $default_filters = array( 'content_type' => Post::type( 'entry' ), ); $paramarray[ 'user_filters' ] = $default_filters; $theme->act_display( $paramarray ); return true; } /** * function get_categories * Gets the categories for the post * @return array The categories array for this post */ private function get_categories( $post ) { $categories = array(); $result = $this->vocabulary->get_object_terms( 'post', $post->id ); if( $result ) { foreach( $result as $t ) { $categories[ $t->term ] = $t->term_display; } } return $categories; } /** * function filter_post_get * Allow post->categories * @return array The categories array for this post **/ public function filter_post_get( $out, $name, $post ) { if( $name != 'categories' ) { return $out; } $categories = array(); $result = $this->vocabulary->get_object_terms( 'post', $post->id ); if( $result ) { foreach( $result as $t ) { $categories[$t->term] = $t->term_display; } } return $categories; } /** * function delete_category * Deletes an existing category and all relations to it. **/ private function delete_category( $category ) { // should there be a Plugins::act( 'category_delete_before' ...? $term = $this->vocabulary->get_term( (int)$category ); if ( !$term ) { return false; // no match for category } $result = $this->vocabulary->delete_term( $term ); if ( $result ) { EventLog::log( sprintf( _t( 'Category \'%1$s\' deleted.' ), $category ), 'info', 'content', 'simplecategories' ); } // should there be a Plugins::act( 'category_delete_after' ...? return $result; } /** * Renames a category * If the master category exists, the categories will be merged with it. * If not, it will be created first. * * Adapted from Tags::rename() * * @param mixed tag The category text, slug or id to be renamed * @param mixed master The category to which it should be renamed, or the slug, text or id of it **/ public static function rename( $master, $category, $object_type = 'post' ) { $vocabulary = Vocabulary::get( self::$vocabulary ); $type_id = Vocabulary::object_type_id( $object_type ); // get the term to be renamed $term = $vocabulary->get_term( $category ); // get the master term $master_term = $vocabulary->get_term( $master ); // check if it already exists if ( !isset( $master_term->term ) ) { // it didn't exist, so we assume it's text and create it $term->term_display = $master; $term->term = $master; $term->update(); // that's it, we're done. EventLog::log( _t( 'Category %s has been renamed to %s.', array( $category, $master ), 'simplecategories' ), 'info', 'category', 'simplecategories' ); } else { if ( ! $master_term->is_descendant_of( $term ) ) { $posts = array(); $posts = Posts::get( array( 'vocabulary' => array( 'any' => array( $term ), 'not' => array( $master_term ) ), 'nolimit' => true, ) ); // categorize all the $category Posts as $master foreach ( $posts as $post ) { // $vocabulary->set_object_terms( 'post', $post->id, $master ); $master_term->associate( 'post', $post->id ); } // move the old $term's children over to $master_term foreach ( $term->children() as $child ) { // is this needed? // $child = $vocabulary->get_term( $child->id ); $vocabulary->move_term( $child, $master_term ); } // delete the old $term and all its associations self::delete_category( $term->id ); EventLog::log( _t( 'Category %s has been merged into %s.', array( $category, $master ), 'simplecategories' ), 'info', 'category', 'simplecategories' ); } else { Session::notice( _t( 'Cannot merge %1$s into %2$s, since %2$s is a descendant of %1$s', array( $term, $master, ), 'shelves' ) ); } } } protected function get_term( $labels, $level ) { $root_term = false; $root = $labels[0]; $roots = $this->vocabulary->get_root_terms(); foreach( $roots as $term ) { if ( $root == $term->term ) { $root_term = $term; break; } } for( $i = 1; $i <= $level; $i++ ) { $term = $labels[$i]; $roots = $root_term->children( $root_term ); foreach( $roots as $cur ) { if ( $cur->term == $term ) { $root_term = $cur; break; } } } return $root_term; } public function filter_posts_search_to_get( $arguments, $flag, $value, $match, $search_string ) { if ( 'category' == $flag ) { $arguments['vocabulary'][$this->vocabulary->name . ':term_display'][] = $value; } return $arguments; } } class SimpleCategoriesFormat extends Format { /** * function category_and_list * Formatting function (should be in Format class?) * Turns an array of category names into an HTML-linked list with commas and an "and". * @param array $array An array of category names * @param string $between Text to put between each element * @param string $between_last Text to put between the next to last element and the last element * @return string HTML links with specified separators. **/ public static function category_and_list( $array, $between = ', ', $between_last = NULL ) { if ( ! is_array( $array ) ) { $array = array ( $array ); } if ( $between_last === NULL ) { $between_last = _t( ' and ', 'simplecategories' ); } $array = array_map( 'SimpleCategoriesFormat::link_cat', $array, array_keys( $array ) ); $last = array_pop( $array ); $out = implode( $between, $array ); $out .= ( $out == '' ) ? $last : $between_last . $last; return $out; } public static function link_cat( $a, $b ) { return '<a href="' . URL::get( "display_entries_by_category", array( "category_slug" => $b ) ) . "\" rel=\"category\">$a</a>"; } } ?> <file_sep><?php class Throttle extends Plugin { const MAX_LOAD = 1.0; const KILL_LOAD = 3.0; private $load = null; private function current_load() { static $load; if(!isset($load)) { $uptime = `uptime`; $loads = substr($uptime, strrpos($uptime, ':') + 1); preg_match('/[0-9]+\.[0-9]+/', $loads, $match); $load = floatval($match[0]); } return $load; } public function action_init() { //Utils::debug(self::current_load()); } public function filter_default_rewrite_rules($rules) { if($this->current_load() > self::KILL_LOAD) { foreach($rules as $key => $rule) { if(strpos($rule['build_str'], 'admin') !== false) { $rules[$key]['handler'] = 'UserThemeHandler'; $rules[$key]['action'] = 'display_throttle'; } } if(Options::get('throttle') == '') { EventLog::log(sprintf(_t('Kill - Load is %s'), $this->current_load())); Options::set('throttle', 'kill'); } } elseif($this->current_load() > self::MAX_LOAD) { foreach($rules as $key => $rule) { if($rule['name'] == 'search') { unset($rules[$key]); } } $rules[] = array( 'name' => 'search', 'parse_regex' => '%^search(?:/(?P<criteria>[^/]+))?(?:/page/(?P<page>\d+))?/?$%i', 'build_str' => 'search(/{$criteria})(/page/{$page})', 'handler' => 'UserThemeHandler', 'action' => 'display_throttle', 'priority' => 8, 'description' => 'Searches posts' ); if(Options::get('throttle') == '') { EventLog::log(sprintf(_t('Restrict - Load is %s'), $this->current_load())); Options::set('throttle', 'restrict'); } } else { if(Options::get('throttle') != '') { EventLog::log(sprintf(_t('Normal - Load is %s'), $this->current_load())); Options::set('throttle', ''); } } return $rules; } } ?> <file_sep><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title><?php Options::out( 'title' ); ?></title> <meta http-equiv="Content-Type" content="text/html"> <meta name="generator" content="Habari"> <link rel="edit" type="application/atom+xml" title="<?php Options::out( 'title' ); ?>" href="<?php URL::out( 'atompub_servicedocument' ); ?>"> <link rel="alternate" type="application/atom+xml" title="Atom 1.0" href="<?php echo $feed_alternate; ?>"> <link rel="EditURI" type="application/rsd+xml" title="RSD" href="<?php URL::out( 'rsd' ); ?>"> <link rel="stylesheet" type="text/css" media="screen" href="<?php Site::out_url( 'theme' ); ?>/style.css"> <?php $theme->header() ?> </head> <body> <div id="wrapper"> <div class="pusher"></div> <div id="header"> <div class="nav_title"> <h1><a href="<?php Site::out_url( 'habari' ); ?>"><?php Options::out( 'title' ); ?></a></h1> </div> <div class="navigation"> <ul id="miniflex"> <?php // Menu tabs foreach ( $nav_pages as $tab ) { $link = ucfirst($tab->slug); echo "<li><a href=\"{$tab->permalink}\" title=\"{$tab->title}\"> {$link}</a></li>"; } if ( $loggedin ): ?> <li class="admintab"><a href="<?php Site::out_url( 'admin' ); ?>" title="Admin area"> Site Admin</a></li> <?php endif; ?> </ul> </div> </div> <div id="content"> <file_sep><?php class SubPagesPlugin extends Plugin { /** * Add the subpage vocabulary * **/ public function action_plugin_activation($file) { if ( Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__) ) { $params = array( 'name' => 'subpages', 'description' => 'A vocabulary for describing hierarchical relationships between pages', 'feature_mask' => Vocabulary::feature_mask(true, false, false, false) ); $subpages = new Vocabulary($params); $subpages->insert(); } } /** * Add the necessary template * **/ function action_init() { $this->add_template( 'subpages', dirname(__FILE__) . '/subpages.php' ); } /** * Add the page parent control to the publish page * * @param FormUI $form The publish page form * @param Post $post The post being edited **/ public function action_form_publish ( $form, $post ) { if ( $form->content_type->value == Post::type( 'page' ) ) { $parent_term = null; $descendants = null; $subpage_vocab = Vocabulary::get('subpages'); // If there's an existing page, see if it has a related term, parent, and descendants if ( null != $post->slug ) { $page_term = $subpage_vocab->get_term($post->slug); if ( null != $page_term ) { $parent_term = $page_term->parent(); $descendants = $page_term->descendants(); } } // If there are pages, work out which ones can be a parent to this page $pages = (array)Posts::get(array('content_type'=>'page', 'status'=>'published', 'nolimit'=>true)); if ( 0 != count($pages) ) { // Descendants of the current page can't be its parent if ( null != $descendants ) { /* TODO Why doesn't this work ? $pages = array_udiff($pages, $descendants, create_function( '$a, $b', 'return $a->slug != $b->term;' ) ); */ for ( $i=0;$i<count($pages);$i++ ) { foreach ( $descendants as $descendant ) { if ( $pages[$i]->slug == $descendant->term ) { unset($pages[$i]); break; } } } } // Create an array of slug => title, appropriate for passing to a select control $candidates = array('none' => 'No parent'); foreach ( $pages as $page ) { if ( $page->slug != $post->slug ) { $candidates[$page->slug] = $page->title; } } // Add a parent selector to the page settings $parent_select = $form->settings->append( 'text', 'parent', 'null:null', _t( 'Parent: '), 'tabcontrol_select' ); $parent_select->value = $parent_term == null ? 'none' : $parent_term->term; $parent_select->options = $candidates; } } } /** * Handle update of parent * @param Post $post The post being updated * @param FormUI $form. The form from the publish page **/ public function action_publish_post( $post, $form ) { if ( $post->content_type == Post::type( 'page' ) ) { $subpage_vocab = Vocabulary::get('subpages'); $parent_term = null; $page_term = $subpage_vocab->get_term($post->slug); if ( null != $page_term ) { $parent_term = $page_term->parent(); } $form_parent = $form->settings->parent->value; // If the parent has been changed, delete this page from its children if ( null != $parent_term && $form_parent != $parent_term->term ) { $subpage_vocab->delete_term($page_term->term); // TODO If the parent no longer has descendants, delete it. // TODO What to do if the term has descendants, and we change the parent ? // There probably should be a flag passed to delete_term() that says // whether to delete them or add them as children of the parent } // If a new term has been set, add it to the subpages vocabulary if ( 'none' != $form_parent ) { // Make sure the parent term exists. $parent_term = $subpage_vocab->get_term($form_parent); if ( null == $parent_term ) { // There's no term for the parent, add it as a top-level term $parent_term = $subpage_vocab->add_term( $form_parent ); } $page_term = $subpage_vocab->add_term( $post->slug, $parent_term ); } } } public function help() { return <<< END_HELP <p>To output subpages in a page, insert this code where you want them linked from:</p> <blockquote><code>&lt;?php \$theme-&gt;subpages(); ?&gt;</code></blockquote> <p>The default theme inserts a link to each subpage. If you want to alter this, you should copy the <tt>subpages.php</tt> template included with this plugin to your current theme directory and make changes to it there.</p> END_HELP; } /** * Change the page rewrite rule to validate ancestors * @param Array $rules Current rewrite rules **/ public function filter_rewrite_rules( $rules ) { foreach ( $rules as $rule ) { if ( 'display_page' == $rule->name ) { $rule->parse_regex = '%^(?P<parentage>.*/)(?P<slug>[^/]+)(?:/page/(?P<page>\d+))?/?$%i'; $rule->description = 'Return page matching specified slug and page hierarchy'; $rule->parameters = serialize( array( 'require_match' => array('SubPagesPlugin', 'rewrite_match_subpage') ) ); break; } } return $rules; } /** * Validate ancestors for this page * @param RewriteRule $rule The matched rewrite rule * @param string The URL stub requested * @param array $params Some stuff **/ public static function rewrite_match_subpage( $rule, $stub, $params ) { // TODO Is there any way to get these apart from rematching ? // They're not set until there's a handler, and that isn't set yet. $slugs = explode('/', $stub); $args = array( 'content_type' => 'page' ); // Check we can get a page for each part of the slug hierarchy $args['slug'] = $slugs; $posts = Posts::get($args); if ( count($posts) != count($slugs) ) { return false; } // Check the stub matches the expected stub return $stub == self::subpage_stub(array_pop($slugs)); } /** * Rewrite a post's permalink if it's a subpage * @param Array $rules Current rewrite rules **/ public function filter_post_permalink( $permalink, $post ) { if ( $post->content_type == Post::type( 'page' ) ) { $subpage_vocab = Vocabulary::get('subpages'); $page_term = $subpage_vocab->get_term($post->slug); if ( null != $page_term ) { $permalink = Site::get_url('habari') . '/' . self::subpage_stub( $page_term ); } } return $permalink; } /** * Enable update notices to be sent using the Habari beacon **/ public function action_update_check() { Update::add( 'SubPages', 'c6a39795-d5cb-4042-b05b-9666825b1bb4', $this->info->version ); } public function theme_subpages($theme, $post) { if ( $post->content_type == Post::type( 'page' ) ) { $subpages = null; $subpage_vocab = Vocabulary::get('subpages'); $page_term = $subpage_vocab->get_term($post->slug); if ( null != $page_term ) { // TODO this should be get_objects etc $slugs = array(); $children = $page_term->children(); foreach ( $children as $child ) { $slugs[] = $child->term; } if ( count($slugs) > 0 ) { $theme->subpages = Posts::get(array('slug' => $slugs)); return $theme->display('subpages'); } } } } private static function subpage_stub( $term ) { if ( is_string($term) ) { $term = Vocabulary::get('subpages')->get_term($term); } if ( null == $term ) { return false; } $ancestors = $term->ancestors(); $stub_parts = array(); foreach ( $ancestors as $ancestor ) { $stub_parts[] = $ancestor->term; } $stub_parts[] = $term->term; return implode('/', $stub_parts); } } ?> <file_sep><?php /** * Custom Content Types Plugin Class * **/ class CustomCTypes extends Plugin { /** * Add the Custom Content Types page to the admin menu * * @param array $menus The main admin menu * @return array The altered admin menu */ function filter_adminhandler_post_loadplugins_main_menu( $menus ) { $menus['content_types'] = array( 'url' => URL::get( 'admin', 'page=admin_cctypes' ), 'title' => _t( 'Manage custom content types' ), 'text' => _t( 'Custom Content Types' ), 'access'=>array('manage_plugins'=>true, 'manage_plugins_config' => true), 'selected' => FALSE ); return $menus; } /** * Restrict access to this admin page by token * * @param array $require_any An array of tokens, of which any will grant access * @param string $page The admin page name * @param string $type The content type of the page * @return array An array of tokens, of which any will grant access */ function filter_admin_access_tokens( $require_any, $page, $type ) { if($page == 'admin_cctypes') { $require_any = array('manage_plugins'=>true, 'manage_plugins_config'=>true); } return $require_any; } /** * On plugin init, add the admin_cctypes template to the admin theme */ function action_init() { $this->add_template('admin_cctypes', dirname(__FILE__) . '/cctypes.php'); $this->add_template('admin_cctype_publish', dirname(__FILE__) . '/cctype_publish.php'); } /** * Respond to get requests on the admin_cctypes template * * @param AdminHandler $handler The admin handler object * @param Theme $theme The admin theme object */ function action_admin_theme_get_admin_cctypes( $handler, $theme ) { $posttypes = Post::list_active_post_types(); unset($posttypes['any']); $posttypes = array_flip($posttypes); $theme->posttypes = $posttypes; if($edit_type = Controller::get_var('edit_type')) { $theme->edit_type = $edit_type; $theme->edit_type_name = $posttypes[$edit_type]; } } /** * Respond to post requests on the admin_cctypes template * * @param AdminHandler $handler The admin handler object * @param Theme $theme The admin theme object */ function action_admin_theme_post_admin_cctypes( $handler, $theme ) { $action = Controller::get_var('cct_action'); switch($action) { case 'addtype': Post::add_new_type($_POST['newtype']); $typeid = Post::type($_POST['newtype']); $handled = Options::get('cctypes_types'); if(!is_array($handled)) { $handled = array(); } $handled[$typeid] = $typeid; array_unique($handled); Options::set('cctypes_types', $handled); Session::notice(_t('Added post type "'.$_POST['newtype'].'".')); break; case 'deletetype': $typename = Post::type_name($_POST['deltype']); Post::deactivate_post_type($_POST['deltype']); $handled = Options::get('cctypes_types'); if(isset($handled[$_POST['deltype']])) { unset($handled[$_POST['deltype']]); } Options::set('cctypes_types', $handled); Session::notice(_t('Deactivated post type "'.$typename.'".')); } Utils::redirect(); } /** * Produce a URL that links to an editing page for a specific content type * * @param Theme $theme The admin theme object * @param integer $type_id The type id of the post type to edit * @return string The URL of the editing page for the requested post type. */ function theme_admin_edit_ctype_url($theme, $type_id) { return URL::get('admin', array('page' => 'admin_cctypes', 'edit_type' => $type_id)); } /** * Display a custom publish page for handled content types * * @param AdminHandler $handler The admin handler object * @param Theme $theme The admin theme object */ function action_admin_theme_get_publish( $handler, $theme ) { $handled = Options::get('cctypes_types'); if ( isset( $handler->handler_vars['id'] ) ) { $post = Post::get( array( 'id' => $handler->handler_vars['id'], 'status' => Post::status( 'any' ) ) ); $ctype = Post::type_name($post->content_type); } else if ( isset( $handler->handler_vars['content_type'] ) ) { $ctype = $handler->handler_vars['content_type']; } if(isset($ctype) && in_array($ctype, $handled)) { $template_name = 'admin_publish_' . $ctype; if($theme->template_exists( $template_name )) { $theme->display( $template_name ); exit; } } } /** * Handle posting of custom content types * * @param AdminHandler $handler The admin handler object * @param Theme $theme The admin theme object * @todo Get a list of fields that this plugin handles for this content type and map the data out of the form into the info fields */ function action_publish_post( $post, $form ) { $handled = Options::get('cctypes_types'); if(isset($handled[$post->content_type])) { // Utils::debug($form); // Put custom data fields into $post->info here } } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Custom Content Types', 'ed4d6659-cf5d-4772-bd78-9c1d164b4354', $this->info->version ); } } ?> <file_sep><?php /* This variable is for alternating comment background */ $oddcomment = 'alt'; ?> <!-- You can start editing here. --> <?php if ( $comments_number= $post->comments->approved->count ): ?> <h3 id="comments"> <?php if ( $comments_number == 0 ) { echo "No Responses to \"{$post->title}\""; } elseif ($comments_number == 1) { echo "One Response to \"{$post->title}\""; } else { echo "{$comments_number} Responses to \"{$post->title}\""; } ?> </h3> <ol class="commentlist"> <?php foreach ( $post->comments->approved as $comment ): ?> <li class="<?php echo $oddcomment; ?>" id="comment-<?php echo $comment->id; ?>"> <cite><a href="<?php echo $comment->url; ?>" rel="external"><?php echo $comment->name; ?></a></cite> Says: <?php if ($comment->comment_approved == '0') { _e('<em>Your comment is awaiting moderation.</em>'); } ?> <br /> <small class="commentmetadata"> <a href="#comment-<?php echo $comment->id; ?>" title=""><?php echo $comment->date_out; ?></a> </small> <?php echo $comment->content_out; ?> </li> <?php /* Changes every other comment to a different class */ $oddcomment == 'alt' ? $oddcomment = '' : $oddcomment = 'alt'; ?> <?php endforeach; /* end for each comment */ ?> </ol> <?php else: // no approved comments if ( $post->info->comments_disabled ) { _e('<p class="nocomments">Comments are closed.</p>'); } else { // comments are closed _e('<p>There are currently no comments.</p>'); } endif; ?> <?php if ( !$post->info->comment_disabled ): $commenter= User::commenter(); ?> <h3 id="respond">Leave a Reply</h3> <form action="<?php URL::out('submit_feedback', array('id'=>$post->id) ); ?>" method="post" id="commentform"> <p> <input type="text" name="name" id="author" value="<?php echo $commenter['name']; ?>" size="22" tabindex="1" /> <label for="name"><small>Name</small></label> </p> <p> <input type="text" name="email" id="email" value="<?php echo $commenter['email']; ?>" size="22" tabindex="2" /> <label for="email"><small>Mail (will not be published) </small></label> </p> <p> <input type="text" name="url" id="url" value="<?php echo $commenter['url']; ?>" size="22" tabindex="3" /> <label for="url"><small>Website</small></label> </p> <p> <textarea name="content" id="content" cols="100%" rows="10" tabindex="4"></textarea> </p> <p> <input name="submit" type="submit" id="submit" tabindex="5" value="Submit Comment" /> </p> </form> <?php endif; ?> <file_sep> <!-- Brightkite plugin for habari --> <!-- To customize this template, copy it to your currently active theme directory and edit it --> <!-- $Id$ --> <div class="item"> <h3 class="subs">Last Seen</h3> <ul> <?php if ( is_array( $content->bkinfo ) ) { $updated = date( "M j, Y g:i A T", strtotime( $content->bkinfo['last_checked_in'] ) ); $place = $content->bkinfo['place']; $lat = $place['latitude']; $long = $place['longitude']; $address = $place['display_location']; $placeurl = 'http://brightkite.com/places/' . $place['id']; $name = $place['name']; // Google map $mapimg = "http://maps.google.com/staticmap?center=$lat,$long&zoom=12&sensor=false&markers=$lat,$long"; $mapimg .= "&size=" . $content->mapsize; $mapimg .= "&key=" . $content->gmapkey; ?> <li class="bkname">I was at <a href="<?php echo $placeurl; ?>"><?php echo $name; ?></a></li> <li class="bkaddress"><?php echo $address; ?></li> <li class="bkmap"><img alt="<?php echo $name; ?>" src="<?php echo $mapimg; ?>" /></li> <li class="bkupdate">Last updated: <?php echo $updated; ?></li> <?php } else { //Exceptions echo '<li>' . $content->bkinfo . '</li>'; } ?> </ul> </div><file_sep><?php class Dateyurl extends Plugin { public function action_init() { $format = Options::get( 'dateyurl__format' ); // for backwards compatibility. the first time, set the option if ( $format == null ) { Options::set( 'dateyurl__format', 'date' ); $format = 'date'; } if ( $format == 'date' ) { // /{year}/{month}/{day}/{slug} $parse_regex= '%(?P<year>\d{4})/(?P<mon0>\d{2})/(?P<mday0>\d{2})/(?P<slug>[^/]+)(?:/page/(?P<page>\d+))?/?$%i'; $build_str= '{$year}/{$mon0}/{$mday0}/{$slug}(/page/{$page})'; } if ( $format == 'month' ) { // /{year}/{month}/{slug} $parse_regex= '%(?P<year>\d{4})/(?P<mon0>\d{2})/(?P<slug>[^/]+)(?:/page/(?P<page>\d+))?/?$%i'; $build_str= '{$year}/{$mon0}/{$slug}(/page/{$page})'; } // For backwards compatability. the first time, set the rules $rules = Options::get( 'dateyurl__rules' ); // for backwards compatibility. the first time, set the option if ( $rules == null ) { $rules= array('display_entry'); Options::set( 'dateyurl__rules', $rules ); } foreach( $rules as $rule_name) { $rule = RewriteRules::by_name($rule_name); $rule = $rule[0]; $rule->parse_regex= $parse_regex; $rule->build_str= $build_str; } } public function action_update_check() { Update::add( 'DateYURL', '376A1864-98A1-11DD-A1CC-365A55D89593', $this->info->version ); } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t( 'Configure' ); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { if ( $action == _t( 'Configure' ) ) { $class_name = strtolower( get_class( $this ) ); $form = new FormUI( $class_name ); $form->append( 'select', 'format', 'dateyurl__format', _t( 'URL Format' ), array( 'date' => '/{year}/{month}/{day}/{slug}', 'month' => '/{year}/{month}/{slug}' ) ); $form->append( 'textmulti', 'rules', 'dateyurl__rules', _t( 'Rules to Change' ) ); $form->append( 'submit', 'save', _t( 'Save' ) ); $form->on_success( array( $this, 'updated_config' ) ); $form->out(); } } } public function updated_config( $form ) { $form->save(); } public function action_plugin_activation( $file ) { if ( Plugins::id_from_file( $file ) == Plugins::id_from_file( __FILE__ ) ) { if ( Options::get( 'dateyurl__format' ) == null ) { Options::set( 'dateyurl__format', 'date' ); } } } } ?><file_sep><!-- Sidebar menu div --> <div id="menu"> <?php Plugins::act( 'theme_sidebar_top' ); ?> <ul> <?php if ($this->request->display_search) { ; ?> <li id="search"> <?php _e('Search results for \'%s', array( htmlspecialchars( $criteria ) ) ); ?>'</li> <?php } ?> <?php if (Plugins::is_loaded('TagCloud')) { ?> <li id="colophon"> <?php $theme->colophon(); ?> </li> <?php } ?> <li><?php _e('Recent comments'); ?> <ul id="recentcomments"> <?php foreach($recent_comments as $comment): ?> <li><a href="<?php echo $comment->url ?>"><?php echo $comment->name ?></a> <?php _e('on'); ?> <a href="<?php echo $comment->post->permalink; ?>"><?php echo $comment->post->title; ?></a></li> <?php endforeach; ?> </ul> </li> <li><?php _e('Monthly archives'); ?> <ul id="monthlyarchives"> <?php $theme->monthly_archives(5, 'N'); ?> <li> <a href="<?php Site::out_url( 'habari' ); ?>/archives">More...</a></li> </ul> </li> <li><?php _e('More posts'); ?> <ul id="moreposts"> <?php foreach($more_posts as $post): ?> <?php echo '<li>'; echo '<a href="' . $post->permalink .'">' . $post->title_out . '</a>'; echo '</li>'; ?> <?php endforeach; ?> </ul> </li> <?php if (Plugins::is_loaded('PopularPosts')) { ?> <div id="PopularPosts"> <?php $theme->popular_posts(); ?> </div> <?php } ?> <?php if (Plugins::is_loaded('TagCloud')) { ?> <li><?php _e('Tag cloud'); ?> <ul id="tagcloud"> <?php $theme->tag_cloud(); ?> </ul></li> <?php } ?> <?php if (Plugins::is_loaded('fluffytag')) { ?> <li><?php _e('Tag cloud'); ?> <ul id="tagcloud"> <?php $theme->fluffytag(); ?> </ul></li> <?php } ?> <?php if (Plugins::is_loaded('blogroll')) { ?> <div id="blogroll"> <?php $theme->show_blogroll(); ?> </div> <?php } ?> <?php if (Plugins::is_loaded('deliciousfeed')) { ?> <li><?php _e('Delicious'); ?> <ul id="delicious"> <?php $theme->deliciousfeed(); ?> </ul></li> <?php } ?> <?php if (Plugins::is_loaded('audioscrobbler')) { ?> <li><?php _e('Last.fm'); ?> <ul id="lastfm"> <?php $theme->audioscrobbler(); ?> </ul></li> <?php } ?> <?php if (Plugins::is_loaded('lastrecent')) { ?> <li><?php _e('Last.fm'); ?> <ul id="lastfm"> <?php $theme->lastrecent(); ?> </ul></li> <?php } ?> <?php if (Plugins::is_loaded('flickrfeed')) { ?> <li><?php _e('Flickr'); ?> <ul id="flickr"> <?php $theme->flickrfeed(); ?> </ul></li> <?php } ?> <?php if (Plugins::is_loaded('twitter')) { ?> <li><?php _e('Twitter'); ?> <ul id="twitter"> <?php $theme->twitter(); ?> </ul></li> <?php } ?> <?php if (Plugins::is_loaded('Brightkite')) { ?> <div id="brightkite"> <?php $theme->bk_location(); ?> </div> <?php } ?> <li class="user"><?php _e('User'); ?><ul> <?php $theme->display ( 'loginform' ); ?> </ul></li> <?php $theme->switcher(); ?> <?php $theme->area('sidebar'); ?> </ul> <?php Plugins::act( 'theme_sidebar_bottom' ); ?> </div> <file_sep><?php class CpgExif { private static $exifDbMap = array( "make", "model", "lens", "size", "width", "height", "fnumber", "exposure", "iso", "dateTimeOriginal", "focalLength", "keywords", "focalLengthIn35mmFilm", "artist", "copyright", "description" ); public static function getDbMap() { return self::$exifDbMap; } function getImageData($src) { $data = array(); $data['src'] = $src; if (function_exists(exif_read_data)) { $exif = @exif_read_data($src, 0, true); if (isset($exif)) { $make = $exif['IFD0']['Make']; if (isset($make)) { $data['make'] = $make; } $model = $exif['IFD0']['Model']; if (isset($model)) { $data['model'] = $model; } $lens = $exif['XMP']['Lens']; if (isset($lens)) { $data['lens'] = $lens; } $size = $exif['FILE']['FileSize']; if (isset($size)) { $data['size'] = $size; } $width = $exif['COMPUTED']['Width']; if (isset($width)) { $data['width'] = $width; } $height = $exif['COMPUTED']['Height']; if (isset($height)) { $data['height'] = $height; } $fnumbers = $exif['EXIF']['FNumber']; if (isset($fnumbers)) { $posslash = strpos($exif['EXIF']['FNumber'], "/"); $fval = substr($exif['EXIF']['FNumber'],0,$posslash)/substr($exif['EXIF']['FNumber'],$posslash+1,(strlen($exif['EXIF']['FNumber']))); $data['fnumber'] = $fval ; } $exptime = $exif['EXIF']['ExposureTime']; if (isset($exptime)) { $posslash = strpos($exptime, "/"); if ($posslash == "1") $data['exposure'] = substr($exptime,0,1)."/".substr($exptime,$posslash+1,(strlen($exptime)-2)); else if ($posslash == "2") $data['exposure'] = substr($exptime,0,1)."/".substr($exptime,$posslash+1,(strlen($exptime)-4)); else if ($posslash == "3") $data['exposure'] = substr($exptime,0,1)."/".substr($exptime,$posslash+1,(strlen($exptime)-6)); else $data['exposure'] = $exptime; } $iso = $exif['EXIF']['ISOSpeedRatings']; if (isset($iso)) { $data['iso'] = $iso; } $taken = $exif['EXIF']['DateTimeOriginal']; if (isset($taken)) { preg_match("/(\d+):(\d+):(\d+)\s+(\d+):(\d+):(\d+)/", $taken, $m); $data['taken'] = date('Y-m-d H:i:s', mktime($m[4], $m[5], $m[6], $m[2], $m[3], $m[1])); } $flengths = $exif['EXIF']['FocalLength']; if (isset($flengths)) { $posslash = strpos($exif['EXIF']['FocalLength'], "/"); if ($posslash) { $fval = substr($exif['EXIF']['FocalLength'],0,$posslash)/substr($exif['EXIF']['FocalLength'],$posslash+1,(strlen($exif['EXIF']['FocalLength']))); $data['flength'] = $fval; } else $data['flength'] = $flengths; } if (isset($exif['EXIF']['FocalLengthIn35mmFilm'])) { $data['flength35mm'] = $exif['EXIF']['FocalLengthIn35mmFilm']; } if (isset($exif['IFD0']['Artist'])) { $data['artist'] = $exif['IFD0']['Artist']; } if (isset($exif['IFD0']['Copyright'])) { $data['copyright'] = $exif['IFD0']['Copyright']; } } $source = file_get_contents($src); if (isset($source)) { $xmpdata_start = strpos($source,"<x:xmpmeta"); $xmpdata_end = strpos($source,"</x:xmpmeta>"); $xmplength = $xmpdata_end-$xmpdata_start; $xmpdata = substr($source,$xmpdata_start,$xmplength+12); unset($r); preg_match ("/<aux:Lens>.+<\/aux:Lens>/", $xmpdata, $r); $xmp_item = ""; $xmp_item = @$r[0]; if (isset($xmp_item)) { $data['lens'] = $xmp_item; } unset($source); } } return $data; } } ?><file_sep><?php /** * Create a block with arbitrary content. * */ class InlineBlock extends Plugin { /** * Output the content of the block, and nothing else. **/ public function action_block_content($block, $theme) { if(User::identify()->loggedin) { $block_id = 'inline_block_' . $block->id; $href = URL::get('admin', array('page' => 'configure_block', 'blockid' => $block->id, 'inline' => 1, 'iframe' => 'true', 'width' => 600, 'height' => 400, 'block' => $block_id) ); if($_GET['inline'] == 1) { $block->content = '<a class="editable-block-link" href="' . $href . '" onclick="$.prettyPhoto.open($(this).attr(\'href\'),\'Edit Content\',\'Hello!\');return false;">Edit</a>' . $block->content; } else { $block->content = '<div class="editable-inline-block" id="' . $block_id . '"><a class="editable-block-link" href="' . $href . '" onclick="$.prettyPhoto.open($(this).attr(\'href\'),\'Edit Content\',\'Edit the content, then click Save. Reload the page to see the changes.\');return false;">Edit</a>' . $block->content . '</div>'; } } return $block; } public function action_template_header($theme) { Stack::add('template_stylesheet', array($this->get_url() . '/inlineblock.css', 'screen')); } public function action_admin_header($theme) { if ( $theme->page == 'configure_block' && $_GET['inline'] == 1) { Plugins::act('add_jwysiwyg_admin'); Stack::add('admin_stylesheet', array('#block_admin { display: none; } textarea { height: 250px; width: 540px; }', 'screen')); } } public function action_admin_footer($theme) { if ( $theme->page == 'configure_block' && $_GET['inline'] == 1 ) { echo <<<JWYSIWYG <script type="text/javascript"> $(function() { $('#content textarea').wysiwyg({ resizeOptions: {}, controls : {html : {visible: true}} }); }); </script> JWYSIWYG; } } } ?> <file_sep>spamview = { init: function() { spamview.button = $('#deleteallspam, #deletealllogs'); spamview.body = $('body'); if(spamview.button.length > 0) { $.hotkeys.add('Ctrl+d', {propagate:true, disableInInput: true}, function(){ spamview.trash(); }); } // Started work on a chaining system... // $.hotkeys.add('s', {propagate:true, disableInInput: true}, function(){ // if(spamview.button.hasClass('active')) { // spamview.delete(); // } // }); spamview.button.click(function() { spamview.trash(); return false; }); // // spamview.button.focus(function() { // spamview.button.addClass('active'); // }); // // spamview.button.blur(function() { // spamview.button.removeClass('active'); // }); }, trash: function() { query = {}; if(spamview.body.hasClass('page-dashboard')) { query.page = 'dashboard'; query.target = 'spam'; } else if(spamview.body.hasClass('page-logs')) { query.page = 'logs'; query.target = 'logs'; } else { query.page = 'comments'; query.target = 'spam'; } $.ajax({ url: habari.url.habari + '/auth_ajax/deleteall', type: "POST", dataType: "json", data: query, success: function( json ) { if(query.page == 'dashboard') { dashboard.fetch(); } else { itemManage.fetch(); } jQuery.each( json.messages, function( index, value) { humanMsg.displayMsg( value ); } ); }, }); } }; $(document).ready(function() { spamview.init(); }); <file_sep>google.load("maps", "2"); google.setOnLoadCallback(function() { if (GBrowserIsCompatible()) { $('a[href^="http://maps.google"]').each(function() { var qpos = this.href.indexOf('?'); if (!qpos) return; var query = this.href.substring(qpos, this.href.length); var ll_r = query.match(/(\?|&amp;|&)ll=([\d\-\.]+),([\d\-\.]+)/); if (!ll_r || ll_r.length != 4) return; var lat = ll_r[2]; var lng = ll_r[3]; var zoom = 13; var zoom_r = query.match(/(\?|&amp;|&)z=(\d+)/); if (zoom_r) { zoom = zoom_r[2]; } var type = 'm'; var type_r = query.match(/(\?|&amp;|&)t=([mkh])/); if (type_r) { type = type_r[2]; } var layer = ''; var layer_r = query.match(/(\?|&amp;|&)layer=([c])/); if (layer_r) { layer = layer_r[2]; } var cbp = ''; var cbp_r = query.match(/(\?|&amp;|&)cbp=([\d\-\.,]+)/); if (cbp_r) { cbp = cbp_r[2].split(','); } var cblat = null; var cblng = null; var cbll_r = query.match(/(\?|&amp;|&)cbll=([\d\-\.]+),([\d\-\.]+)/); if (cbll_r) { cblat = cbll_r[2]; cblng = cbll_r[3]; } var width = 0; var height = 0; var _size_r = query.match(/(\?|&amp;|&)_size=(\d+)x(\d+)/); if (_size_r) { width = _size_r[2]; height = _size_r[3]; } var controls = ''; var _controls_r = query.match(/(\?|&amp;|&)_controls=(none)/); if (_controls_r) { controls = _controls_r[2]; } var markers = []; var _markers_r = query.match(/(\?|&amp;|&)_markers=([\d\-\.\,\|]+)/); if (_markers_r) { $.each(_markers_r[2].split('|'), function(k, marker) { marker = marker.split(','); markers.push(new google.maps.LatLng(marker[0], marker[1])); }); } canvas = $('<div class="googlemaps-canvas"></div>'); $(this).replaceWith(canvas); if (layer == 'c') { if (width == 0 || height == 0) { width = habari_googlemaps.streetview_width; height = habari_googlemaps.streetview_height; } canvas.width(width); canvas.height(height); var pov = { yaw: cbp[1], pitch: cbp[4], zoom: cbp[3] }; options = { latlng: new google.maps.LatLng(cblat, cblng), pov: pov }; pano = new google.maps.StreetviewPanorama(canvas.get(0), options); GEvent.addListener(pano, 'error', function(errorCode) { if (errorCode == google.maps.FLASH_UNAVAILABLE) { canvas.html("Error: Flash doesn't appear to be supported by your browser"); return; } }); } else { if (width == 0 || height == 0) { width = habari_googlemaps.map_width; height = habari_googlemaps.map_height; } map = new google.maps.Map2(canvas.get(0), {size: new GSize(width, height)}); if (controls != 'none') { map.addControl(new google.maps.MapTypeControl()); map.addControl(new google.maps.LargeMapControl()); } map.enableScrollWheelZoom(); map.enableContinuousZoom(); map.setCenter(new google.maps.LatLng(lat, lng), parseInt(zoom)); if (type == 'k') { map.setMapType(G_SATELLITE_MAP); } else if (type == 'h') { map.setMapType(G_HYBRID_MAP); } else { map.setMapType(G_NORMAL_MAP); } $.each(markers, function(k, marker) { map.addOverlay(new google.maps.Marker(marker)); }); } }); } }); $(document).unload(function() { GUnload(); }); <file_sep><?php class ViewBlog extends Plugin { const VERSION = '1.0'; public function filter_adminhandler_post_loadplugins_main_menu($mainmenus) { $mainmenus['view'] = array( 'url' => Site::get_url('habari'), 'title' => _t('View blog'), 'text' => _t('View Blog'), 'hotkey' => 'V', 'selected' => ''); return $mainmenus; } } ?> <file_sep><?php /** * BinadamuTheme is a custom Theme class. * * @package Habari */ // We must tell Habari to use BinadamuTheme as the custom theme class: define('THEME_CLASS', 'BinadamuTheme'); /** * A custom theme for Binadamu output */ class BinadamuTheme extends Theme { private $handler_vars = array(); /** * On theme initialization */ public function action_init_theme() { /** * Apply these filters to output */ if (!Plugins::is_loaded('HabariMarkdown')) { // Apply Format::autop() to post content... Format::apply('autop', 'post_content_out'); } // Truncate content excerpt at "<!--more-->"... Format::apply_with_hook_params('more', 'post_content_out'); // Apply Format::autop() to comment content... Format::apply('autop', 'comment_content_out'); // Apply Format::tag_and_list() to post tags... Format::apply('tag_and_list', 'post_tags_out'); $this->load_text_domain('binadamu'); } public function add_template_vars() { $this->assign('home_tab', 'Blog'); //Set to whatever you want your first tab text to be. if (!$this->assigned('pages')) { $this->assign('pages', Posts::get(array('content_type' => 'page', 'status' => Post::status('published'), 'nolimit' => 1))); } if (!$this->assigned('user')) { $this->assign('user', User::identify()); } if (!$this->assigned('recent_entries')) { $this->assign('recent_entries', Posts::get(array('limit' => 10, 'content_type' => 'entry', 'status' => Post::status('published'), 'orderby' => 'pubdate DESC'))); } $this->add_template( 'binadamu_submit', dirname(__FILE__) . '/formcontrol_submit.php' ); parent::add_template_vars(); } public function filter_theme_call_header($return, $theme) { if ($this->request->display_search) { echo '<meta name="robots" content="noindex,nofollow">'; } elseif ($this->request->display_entries_by_date || $this->request->display_entries_by_tag) { echo '<meta name="robots" content="noindex,follow">'; } return $return; } public function filter_post_tags_class($tags) { if (!$tags) return; $rt = array(); foreach ($tags as $t) $rt[] = 'tag-' . $t->term; return count($rt) > 0 ? implode(' ', $rt) : 'no-tags'; } public function theme_title($theme) { $title = ''; if (count($this->handler_vars) === 0) { $this->handler_vars = Controller::get_handler()->handler_vars; } if ($this->request->display_entries_by_date && count($this->handler_vars) > 0) { $date_string = ''; $date_string .= isset($this->handler_vars['year']) ? $this->handler_vars['year'] : '' ; $date_string .= isset($this->handler_vars['month']) ? '‒' . $this->handler_vars['month'] : '' ; $date_string .= isset($this->handler_vars['day']) ? '‒' . $this->handler_vars['day'] : '' ; $title = sprintf(_t('%1$s &raquo; Chronological Archives of %2$s', 'binadamu'), $date_string, Options::get('title')); } else if ($this->request->display_entries_by_tag && isset($this->handler_vars['tag'])) { $tag = (count($this->posts) > 0) ? Tags::get_by_slug($this->handler_vars['tag'])->term_display : $this->handler_vars['tag'] ; $title = sprintf(_t('%1$s &raquo; Taxonomic Archives of %2$s', 'binadamu'), htmlspecialchars($tag), Options::get('title')); } else if (($this->request->display_entry || $this->request->display_page || $this->request->display_post) && isset($this->posts)) { $title = sprintf(_t('%1$s ¶ %2$s', 'binadamu'), strip_tags($this->posts->title_out), Options::get('title')); } else if ($this->request->display_search && isset($this->handler_vars['criteria'])) { $title = sprintf(_t('%1$s &raquo; Search Results of %2$s', 'binadamu'), htmlspecialchars($this->handler_vars['criteria']), Options::get('title')); } else { $title = Options::get('title'); } if ($this->page > 1) { $title = sprintf(_t('%1$s &rsaquo; Page %2$s', 'binadamu'), $title, $this->page); } return $title; } public function theme_mutiple_h1($theme) { $h1 = ''; if (count($this->handler_vars) === 0) { $this->handler_vars = Controller::get_handler()->handler_vars; } if ($this->request->display_entries_by_date && count($this->handler_vars) > 0) { $date_string = ''; $date_string .= isset($this->handler_vars['year']) ? $this->handler_vars['year'] : '' ; $date_string .= isset($this->handler_vars['month']) ? '‒' . $this->handler_vars['month'] : '' ; $date_string .= isset($this->handler_vars['day']) ? '‒' . $this->handler_vars['day'] : '' ; $h1 = '<h1>' . sprintf(_t('Posts written in %s', 'binadamu'), $date_string) . '</h1>'; } else if ($this->request->display_entries_by_tag && isset($this->handler_vars['tag'])) { $tag = (count($this->posts) > 0) ? Tags::get_by_slug($this->handler_vars['tag'])->term_display : $this->handler_vars['tag'] ; $h1 = '<h1>' . sprintf(_t('Posts tagged with %s', 'binadamu'), htmlspecialchars($tag)) . '</h1>'; } else if ($this->request->display_search && isset($this->handler_vars['criteria'])) { $h1 = '<h1>' . sprintf(_t('Search results for “%s”', 'binadamu'), htmlspecialchars($this->handler_vars['criteria'])) . '</h1>'; } return $h1; } public function action_form_comment($form) { $form->append('static', 'cf_header', '<h2>' . _t('Leave a Reply', 'binadamu') . '</h2>'); $form->append('wrapper', 'cf_commenter_info'); $form->append('wrapper', 'cf_response'); $form->cf_commenter->move_into($form->cf_commenter_info); $form->cf_commenter->caption = _t('Name', 'binadamu'); $form->cf_email->move_into($form->cf_commenter_info); $form->cf_email->caption = _t('E-mail', 'binadamu'); $form->cf_url->move_into($form->cf_commenter_info); $form->cf_url->caption = _t('Website', 'binadamu'); $form->cf_content->move_into($form->cf_response); $form->cf_content->caption = _t('Your Comments', 'binadamu'); $form->cf_submit->move_into($form->cf_response); $form->cf_submit->caption = _t('Send', 'binadamu'); $form->cf_submit->template = 'binadamu_submit'; $form->append('static', 'cf_notice', '<p id="cf_notice">' . _t('Your comment may not display immediately due to spam filtering. Please wait for moderation.', 'binadamu') . '</p>'); } } ?> <file_sep><!-- To customize this template, copy it to your currently active theme directory and edit it --> <div id="audioscrobbler"> <h2><?php _e('Now Listening…', $this->class_name); ?></h2> <?php if ($track instanceof SimpleXMLElement) { printf('“<a href="%1$s">%2$s</a>” performed by %3$s', $track->url, $track->name, $track->artist); } else { echo $track; } ?> </div><file_sep><?php /** * alerts via XMPP on specified events with Habari * * @package xmpp-notify * @version $Id$ * @author rmullins <<EMAIL>> * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link http://www.ciscomonkey.net/habari-plugins/ **/ include_once "XMPPHP/XMPP.php"; class XMPPNotify extends Plugin { const VERSION = '0.1.4'; private $config = array(); private $class_name = ''; private $default_options = array ( 'server' => 'talk.google.com', 'port' => 5222, 'user' => 'user', 'pass' => '<PASSWORD>', 'host' => '', 'notify' => '<EMAIL>' ); private $error = ''; private $conn; /** * Required plugin infoormation * @return array The array of information **/ public function info() { return array( 'name' => 'XMPP Notify', 'version' => self::VERSION, 'url' => 'http://www.ciscomonkey.net/habari-plugins/', 'author' => '<NAME>', 'authorurl' => 'http://www.ciscomonkey.net/', 'license' => 'Apache License 2.0', 'description' => 'Implements XMPP Notification for Habari' ); } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'XMPPNotify', 'f76ceb5c-b4ce-11dd-9e4a-3b9f56d89593', $this->info->version ); } /** * Executes when the admin plugins page wants to know if plugins have configuration links to display. * * @param array $actions An array of existing actions for the specified plugin id. * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id **/ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { // Add a 'configure' action $actions[] = _t( 'Configure Jabber Server' ); // Add a 'test' action $actions[] = _t( 'Test Jabber Settings' ); } return $actions; } /** * Respond to the user selecting an action on the plugin page * * TODO: Add options for each type of notification to turn on/off * * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook **/ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch( $action ) { case _t( 'Configure Jabber Server' ): $ui = new FormUI( $this->class_name ); $server = $ui->append( 'text', 'server', 'option:' . $this->class_name . '__server', _t( 'Jabber server name :' ) ); $port = $ui->append( 'text', 'port', 'option:' . $this->class_name . '__port', _t( 'Jabber server port :' ) ); $user = $ui->append( 'text', 'user', 'option:' . $this->class_name . '__user', _t( 'Jabber username :' ) ); $pass = $ui->append( 'password', 'pass', 'option:' . $this->class_name . '__pass', _t( 'Jabber password :' ) ); $host = $ui->append( 'text', 'host', 'option:' . $this->class_name . '__host', _t( 'Jabber user host :' ) ); $notify = $ui->append( 'text', 'notify', 'option:' . $this->class_name . '__notify', _t( 'User to notify :' ) ); // When the form is sucessfully completed, call $this->updated_config() $ui->append( 'submit', 'save', _t( 'Save Server Settings' ) ); $ui->set_option('success_message', _t( 'Options saved.' ) ); $ui->out(); break; case _t( 'Test Jabber Settings' ): echo '<p>' . _t( $this->send_test_message() ) . '</p>'; break; } } } /** * On plugin activation, set the default Options **/ public function action_plugin_activation( $file ) { if ( realpath( $file ) == __FILE__ ) { $this->class_name = strtolower( get_class( $this ) ); foreach ( $this->default_options as $name => $value ) { $current_value = Options::get( $this->class_name . '__' . $name ); if ( is_null( $current_value ) ) { Options::set( $this->class_name . '__' . $name, $value ); } } } } /** * On plugin init, add anything we need here. adding templates, etc. **/ public function action_init() { $this->class_name = strtolower( get_class( $this ) ); } /** * Send a test message using our configuration. **/ private function send_test_message() { if ( $this->send_xmpp("This is a test message from your Habari blog!!") ) { return "Test message was sent."; } else { return "<b>ERROR SENDING MESSAGE</b><br />Error was: " . $this->error; } } /** * Send message via XMPP **/ private function send_xmpp( $msg ) { if ( $msg == "" ) { return false; } else { $this->conn = new XMPPHP_XMPP( Options::get( $this->class_name . '__server' ), Options::get( $this->class_name . '__port' ), Options::get( $this->class_name . '__user' ), Options::get( $this->class_name . '__pass' ), 'xmpphp', Options::get( $this->class_name . '__host' ) ); try { $this->conn->connect(); $this->conn->processUntil('session_start'); $this->conn->presence(); $this->conn->message( Options::get( $this->class_name . '__notify'), $msg ); $this->conn->disconnect(); return true; } catch( XMPPHP_Exception $e ) { $this->error = $e->getMessage(); return false; } } } /** * Send message after comments **/ public function action_comment_insert_after( $comment ) { // TODO: see if we can get moderation status. $this->send_xmpp("Comment added to your blog:\n Posted by " . $comment->name . "\n" . strip_tags($comment->content)); } /** * Send message after failed login **/ public function action_user_authenticate_failure( $cause ) { $this->send_xmpp("User authentication failure:\n$cause"); } /** * Filter all log entries **/ public function filter_insert_logentry( $log ) { if ( preg_match( '/^Login attempt \(via authentication plugin\) for non\-existent user/', $log->message ) ) { $this->send_xmpp("Failed Login Attempt:\n" . $log->message ); } } } // End of Class XMPPNotify ?><file_sep><?php /** * Maintenance Mode plugin * **/ class Maintenance extends Plugin { const OPTION_NAME = 'maint_mode'; /** * function info * Returns information about this plugin * @return array Plugin info array **/ function info() { return array ( 'name' => 'Maintenance Mode', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'version' => '0.3', 'description' => 'Redirects all requests to a maintenance mode page. The login page always remains available. Logged in users can see any page on the site even when in maintenance mode.', 'license' => 'Apache License 2.0', ); } public function action_plugin_activation( $file ) { if ( realpath( $file ) == __FILE__ ) { Options::set( self::OPTION_NAME . '__text' , _t( "We're down for maintenance. Please return later." ) ); Options::set( self::OPTION_NAME . '__in_maintenance', FALSE ); Options::set( self::OPTION_NAME . '__display_feeds', FALSE ); } } public function action_plugin_deactivation( $file ) { if ( realpath( $file ) == __FILE__ ) { Options::delete( self::OPTION_NAME . '__text' , _t( "We're down for maintenance. Please return later." ) ); Options::delete( self::OPTION_NAME . '__in_maintenance', FALSE ); Options::delete( self::OPTION_NAME . '__display_feeds', FALSE ); } } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t('Configure' ); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure' ) : $ui = new FormUI( 'maintenance_mode' ); // Add a text control for the maintenance mode text $ui->append( 'textarea', 'mm_text', self::OPTION_NAME . '__text', _t('Display Text: ' ) ); // Add checkbox to put in/out of maintenance mode $ui->append( 'checkbox', 'in_maintenance', self::OPTION_NAME . '__in_maintenance', _t( 'In Maintenance Mode' ) ); $ui->append( 'checkbox', 'display_feeds', self::OPTION_NAME . '__display_feeds', _t( 'Display Feeds When In Maintenance Mode' ) ); $ui->append( 'submit', 'save', _t( 'Save' ) ); $ui->on_success( array( $this, 'updated_config' ) ); $ui->out(); break; } } } public function updated_config( $ui ) { $msg = _t( "Maintenance Mode configuration updated" ); $msg .= "<br/>"; if($ui->in_maintenance->value === FALSE ) { $msg .= _t( "The site is not in maintenance mode" ); } else { $msg .= _t( "The site is in maintenance mode" ); } Session::notice( $msg ); $ui->save(); } public function filter_rewrite_request( $start_url ) { if( ! Options::get( self::OPTION_NAME . '__in_maintenance' ) ) { return $start_url; } if( Options::get( self::OPTION_NAME . '__display_feeds' ) ) { if( strpos( $start_url, 'atom' ) !== FALSE || strpos( $start_url, 'rss' ) !== FALSE || strpos( $start_url, 'rsd' ) !== FALSE ) { return $start_url; } } if( ! User::identify()->loggedin ) { if ( strpos( $start_url, 'user/login' ) === FALSE && strpos( $start_url, 'admin' ) === FALSE ) { $start_url = 'maintenance'; } } return $start_url; } public function filter_rewrite_rules( $rules ) { $rules[] = new RewriteRule ( array( 'name' => 'maintenance', 'parse_regex' => '%^maintenance%i', 'build_str' => 'maintenance', 'handler' => 'UserThemeHandler', 'action' => 'display_maintenance', 'priority' => 4, 'rule_class' => RewriteRule::RULE_PLUGIN, 'is_active' => ( User::identify()->loggedin ? 0 : 1 ), 'description' => 'Displays the maintenance mode page' ) ); return $rules; } public function filter_theme_act_display_maintenance( $handled, $theme ) { header("HTTP/1.1 503 Service Unavailable"); header('Retry-After: 900'); if ($theme->template_exists('maintenance')) { $theme->maintenance_text = Options::get( self::OPTION_NAME . '__text' ); $theme->display( 'maintenance' ); } else { $theme->display('header'); echo '<h2 id="maintenance_text">' . htmlspecialchars( Options::get( self::OPTION_NAME . '__text' ), ENT_COMPAT, 'UTF-8' ) . '</h2>'; $theme->display('footer'); die(); } return TRUE; } public function action_update_check() { Update::add( 'Maintenance Mode', '1F66810A-6CD5-11DD-BC10-8E2156D89593', $this->info->version ); } } ?> <file_sep><?php class Abbrev extends Plugin { const GUID = '490e4c1b-67b8-4c41-b290-07ae5967b785'; const PLUGIN_NAME = 'Abbrev'; const PLUGIN_TOKEN = '<PASSWORD>'; const VERSION = '0.1alpha'; private function qsafe($text, $addComma=false) { $text = sprintf('"%s"', HTMLentities(addslashes($text))); if ($addComma) { $text .= ', '; } return $text; } private function _getAbbrevs() { return DB::get_results('SELECT * FROM ' . DB::table('abbrev') . ' ORDER BY priority ASC, ' . 'LENGTH(abbrev) DESC, ' . 'abbrev ASC'); } // public function info() { // return array( // 'name' => self::PLUGIN_NAME, // 'version' => self::VERSION, // 'url' => 'http://habariproject.org/', // 'author' => '<NAME>', // 'authorurl' => 'http://Ken.Coar.Org/', // 'license' => 'Apache License 2.0', // 'description' => 'Extensible abbreviations' // ); // } public function action_admin_header($theme) { $vars = Controller::get_handler_vars(); if (($theme->page == 'plugins') && isset($vars['configure']) && ($this->plugin_id == $vars['configure'])) { Stack::add('admin_stylesheet', array($this->get_url() . '/abbrev.css', 'screen'), 'abbrev', array('admin')); Stack::add('template_header_javascript', $this->get_url() . '/abbrev.js', 'abbrev'); $abbrevs = $this->_getAbbrevs(); if ($n = count($abbrevs)) { $js_xid2def .= "\n \$(document).ready(function(){\n" . " function aDef(abbrev_p, definition_p, caseful_p, prefix_p, postfix_p) {\n" . " this.abbrev = abbrev_p;\n" . " this.definition = definition_p;\n" . " this.caseful = caseful_p;\n" . " this.prefix = prefix_p;\n" . " this.postfix = postfix_p;\n" . " }\n" . " aDefs = [];\n"; foreach ($abbrevs as $abbrev) { $prefix = "'" . $abbrev->prefix . "'"; $postfix = "'" . $abbrev->postfix . "'"; $prefix = str_replace('\\', '\\\\', $prefix); $prefix = str_replace('"', '\\"', $prefix); $postfix = str_replace('\\', '\\\\', $postfix); $postfix = str_replace('"', '\\"', $postfix); $js_xid2def .= ' aDefs[' . $abbrev->xid . '] = new aDef(' . $this->qsafe($abbrev->abbrev, true) . $this->qsafe($abbrev->definition, true) . ($abbrev->caseful ? 'true' : 'false') . ', ' . $this->qsafe($prefix, true) . $this->qsafe($postfix) . ");\n"; } $js_xid2def .= " \$('#mAbbrev select')" . ".change(function(){\n" . " aNum = \$(this).val();\n" . " \$('#mDefinition input').val($('<input value=\"' + aDefs[aNum].definition + '\"/>').val());\n" . " \$('#mCaseful input[type=\"checkbox\"]')" . ".attr('checked', aDefs[aNum].caseful);\n" . " \$('#mPreRegex input[type=\"text\"]')" . ".val($('<input value=\"' + aDefs[aNum].prefix + '\"/>').val());\n" . " \$('#mPostRegex input[type=\"text\"]')" . ".val($('<input value=\"' + aDefs[aNum].postfix + '\"/>').val())});\n" . " })\n"; Stack::add('admin_header_javascript', $js_xid2def, 'abbrev', 'admin'); } } } public function action_update_check() { Update::add(self::PLUGIN_NAME, self::GUID, $this->info->version); } /* * Admin-type methods */ public function action_plugin_activation($file) { DB::register_table('abbrev'); /* * Create the database table, or upgrade it */ $dbms = DB::get_driver_name(); $sql = 'CREATE TABLE ' . DB::table('abbrev') . ' ' . '('; if ($dbms == 'sqlite') { $sql .= 'xid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,'; } else if ($dbms == 'mysql') { $sql .= 'xid INT(9) NOT NULL AUTO_INCREMENT,' . 'UNIQUE KEY xid (xid),'; } else { $sql .= 'xid INT(9) NOT NULL AUTO_INCREMENT,' . 'UNIQUE KEY xid (xid),'; } $sql .= 'abbrev VARCHAR(255),' . 'caseful INTEGER DEFAULT 0,' . "prefix VARCHAR(16) DEFAULT '\\b'," . "postfix VARCHAR(16) DEFAULT '\\b'," . 'priority INTEGER DEFAULT 100,' . 'definition VARCHAR(255)' . ')'; if (! DB::dbdelta($sql)) { Utils::debug(DB::get_errors()); } if ($file == str_replace('\\', '/', $this->get_file())) { ACL::create_token(self::PLUGIN_TOKEN, _t('Allow use of Abbrev plugin'), 'Category', false); $group = UserGroup::get_by_name('admin'); $group->grant(self::PLUGIN_TOKEN); } } public function action_plugin_deactivation($file) { if ($file == str_replace('\\', '/', $this->get_file())) { ACL::destroy_token(self::PLUGIN_TOKEN); } } /* * Add a configuration panel for us. */ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()) { $actions[] = _t('Configure'); } return $actions; } /* * And here's the actual configuration panel itself. */ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id == $this->plugin_id()) { $abbrevs = $this->_getAbbrevs(); switch ($action) { case _t('Configure'): $ui = new FormUI(strtolower(get_class($this))); $ui->append('fieldset', 'setAdd', 'Add an abbreviation'); $setAdd = $ui->setAdd; $setAdd->class = 'abbrev-settings'; /* * Fields to add an abbreviation. */ $setAdd->append(new FormControlText('nAbbrev', null, _t('Abbreviation:'))); $setAdd->nAbbrev->value = ''; $setAdd->append(new FormControlText('nDefinition', null, _t('Definition:'))); $setAdd->nDefinition->value = ''; $setAdd->nDefinition->size = 50; $setAdd->append('checkbox', 'nCaseful', '1', 'Case-sensitive:'); $setAdd->append('fieldset', 'setAddAdvanced', 'Advanced options'); $setAdv = $setAdd->setAddAdvanced; $setAdv->append(new FormControlText('nPreRegex', null, _t('Left boundary regex:'))); $setAdv->nPreRegex->size = 8; $setAdv->nPreRegex->value = '\b'; $setAdv->append(new FormControlText('nPostRegex', null, _t('Right boundary regex:'))); $setAdv->nPostRegex->size = 8; $setAdv->nPostRegex->value = '\b'; /* * Only allow editing and deletion if we already have * some abbreviations defined. */ if ($n = count($abbrevs)) { $anames = array(); $adefs = array(); foreach ($abbrevs as $abbrev) { $anames[$abbrev->abbrev] = $abbrev->xid; $adefs[$abbrev->abbrev] = $abbrev->definition; } /* * First, the modification stuff. */ $ui->append('fieldset', 'setModify', 'Modify an abbreviation'); $setModify = $ui->setModify; $setModify->class = 'abbrev-settings'; $setModify->append(new FormControlSelect('mAbbrev', null, _t('Select abbreviation to modify'))); $setModify->mAbbrev->size = 1; $setModify->mAbbrev->options = array_flip($anames); $setModify->append(new FormControlText('mDefinition', null, _t('Definition:'))); $setModify->mDefinition->value = ''; $setModify->mDefinition->size = 50; $setModify->append('checkbox', 'mCaseful', '1', 'Case-sensitive:'); $setModify->append('fieldset', 'setModAdvanced', 'Advanced options'); $setAdv = $setModify->setModAdvanced; $setAdv->append(new FormControlText('mPreRegex', null, _t('Left boundary regex:'))); $setAdv->mPreRegex->size = 8; $setAdv->mPreRegex->value = ''; $setAdv->append(new FormControlText('mPostRegex', null, _t('Right boundary regex:'))); $setAdv->mPostRegex->size = 8; $setAdv->mPostRegex->value = ''; /* * Now the deletion stuff. */ $ui->append('fieldset', 'setDelete', 'Delete abbreviations'); $setDelete = $ui->setDelete; $setDelete->class = 'abbrev-settings'; foreach ($anames as $abbrev => $xid) { $setDelete->append('checkbox', 'abbrev_' . $xid, $xid, $abbrev); } } $ui->append('submit', 'save', 'Save'); $ui->on_success(array($this, 'handle_config_form')); $ui->out(); break; } } } public function handle_config_form($ui) { $abbrevs = $this->_getAbbrevs(); $abbrevById = array(); foreach ($abbrevs as $abbrev) { $abbrevById[$abbrev->xid] = $abbrev; } $setAdd = $ui->setAdd; $setAddAdv = $setAdd->setAddAdvanced; $setMod = $ui->setModify; $setModAdv = $setMod->setModAdvanced; $setDel = $ui->setDelete; if ($ui->nAbbrev->value) { $prefix = $setModAdv->nPreRegex->value; $prefix = html_entity_decode($prefix); $prefix = str_replace('\\', '\\\\', $prefix); $postfix = $setModAdv->nPostRegex->value; $postfix = html_entity_decode($postfix); $postfix = str_replace('\\', '\\\\', $postfix); DB::insert(DB::table('abbrev'), array('caseful' => $setAdd->nCaseful->value ? 1 : 0, 'abbrev' => $setAdd->nAbbrev->value, 'definition' => $setAdd->nDefinition->value, 'prefix' => $prefix, 'postfix' => $postfix)); } /* * Modify an abbreviation. */ $xid = $setMod->mAbbrev->value; $caseful = $setMod->mCaseful->value ? 1 : 0; $def = $setMod->mDefinition->value; $prefix = $setModAdv->mPreRegex->value; $prefix = str_replace('\\', '\\\\', $prefix); $postfix = $setModAdv->mPostRegex->value; $postfix = str_replace('\\', '\\\\', $postfix); $prefix = html_entity_decode($prefix); $postfix = html_entity_decode($postfix); if ($def && (($def != $abbrevById[$xid]->definition) || ($setMod->mCaseful->value != $abbrevById[$xid]->caseful) || ($prefix != $abbrevById[$xid]->prefix) || ($postfix != $abbrevById[$xid]->postfix))) { DB::update(DB::table('abbrev'), array('definition' => $def, 'caseful' => $caseful, 'prefix' => $prefix, 'postfix' => $postfix), array('xid' => $xid)); } /* * Delete some? */ $a_delboxes = $setDel->controls; foreach ($a_delboxes as $id => $formctl) { if ($formctl->value) { preg_match('/^abbrev_(\d+)$/', $id, $pieces); DB::delete(DB::table('abbrev'), array('xid' => $pieces[1])); } } $ui->save; return false; } public function action_init() { DB::register_table('abbrev'); Stack::add('template_stylesheet', array($this->get_url() . '/abbrev.css', 'screen'), 'abbrev'); } const MARKUP_MARKER_PRE = '<!-- saved_markup -->'; const MARKUP_MARKER_POST = '<!-- /saved_markup -->'; const REDELIMS = '#`~=%ез'; private static $REDELIMS; private static $REDELIM; private function chooseREdelim($text) { if (! isset(Abbrev::$REDELIMS)) { $d = preg_split('//', Abbrev::REDELIMS); Abbrev::$REDELIMS = array_slice($d, 1, count($d) - 2); } $delim = null; foreach (Abbrev::$REDELIMS as $tdelim) { if (! strstr($tdelim, $text)) { $delim = $tdelim; break; } } if (! isset($delim)) { throw new Exception("Can't find an unused delimiter " . 'for regular expressions!'); } return $delim; } /* * Save away and index a piece of markup. If the regex and text * arguments are specified, any group matched by the regex is used as * a plugin to the text to be saved, and the regex is also used * to find and replace the first occurrence in the text with * the save marker. */ private function save_markup($save_text, &$a_saved, $regex=null, $text=null) { if (isset($regex) && isset($text)) { preg_match($regex, $text, $minfo); $save_text = sprintf($save_text, $minfo[1]); } $a_saved[] = $save_text; $n = count($a_saved) - 1; if (isset($regex) && isset($text)) { $redelim = $this->chooseREdelim($text); $rtext = sprintf('%s%d%s', Abbrev::MARKUP_MARKER_PRE, $n, Abbrev::MARKUP_MARKER_POST); $nregex = $redelim . '\Q' . $minfo[0] . '\E' . $redelim; $msg = sprintf('<![CDATA[save=|%s| regex=|%s| nregex=|%s|]]>', $save_text, $regex, $nregex); $text = preg_replace($nregex, $rtext, $text); return $text; } return $n; } /* * Restore any saved strings. */ private function restore_markup(&$saved_markup, $text) { $redelim = $this->chooseREdelim($text); foreach ($saved_markup as $idx => $string) { $old = sprintf('%s\Q%s%d%s\E%s', $redelim, Abbrev::MARKUP_MARKER_PRE, $idx, Abbrev::MARKUP_MARKER_POST, $redelim); $text = preg_replace($old, $string, $text); } return $text; } private function sequester_abbrevs($content, &$saved_abbrevs) { $redelim = $this->chooseREdelim($content); $regex = $redelim . '(<abbr[^>]*>.*?</abbr>)' . $redelim . 'siS'; while (preg_match($regex, $content, $matched)) { $content = $this->save_markup($matched[1], $saved_abbrevs, $regex, $content); } return $content; } /* * Do the actual replacement of any abbreviations. Don't make any * changes to text inside tags! */ public function filter_post_content_out($content, $post) { $redelim = $this->chooseREdelim($content); /* * These should really be sorted longest-first so that a short * abbreviation doesn't break a longer one. */ $abbrevs = $this->_getAbbrevs(); $content = " $content "; $saved_markup = array(); /* * Excise any existing abbreviations so we don't double up. */ $content = $this->sequester_abbrevs($content, $saved_markup); /* * Likewise for any markup tags so we don't insert into the * middle of one. */ $regex = $redelim . '(<[^!][^>]*>)' . $redelim . 'siS'; while (preg_match($regex, $content, $matched)) { $content = $this->save_markup($matched[1], $saved_markup, $regex, $content); } foreach ($abbrevs as $abbrev) { /* * Check to see if the abbrev text occurs; use strstr() to * avoid the overhead of using PCRE for things that won't * be found. */ if ($abbrev->caseful) { /* * If it's case-sensitive, see if it occurs. */ if (! strstr($content, $abbrev->abbrev)) { continue; } else { $reflags = 's'; } } else { /* * Do the case-insensitive one. */ if (! stristr($content, $abbrev->abbrev)) { continue; } else { $reflags = 'si'; } } $pattern = sprintf('%s(?<=%s)(\Q%s\E)(?=%s)%s%s', $redelim, $abbrev->prefix, $abbrev->abbrev, $abbrev->postfix, $redelim, $reflags); if (preg_match($pattern, $content, $matched)) { $rtext = sprintf('<abbr title="%s">%s</abbr>', $abbrev->definition, $matched[1]); $content = $this->save_markup($rtext, $saved_markup, $pattern, $content); } } /* * Now restore any saved strings */ $content = $this->restore_markup($saved_markup, $content); $content = trim($content); return $content; } /* * Code for updating an abbreviation: * * DB::update( * DB::table('abbrev'), * $version_vals, * array('version' => $version_vals['version'], * 'post_id' => $post->id) * ); */ } /* * Local Variables: * mode: C * c-file-style: "bsd" * tab-width: 4 * indent-tabs-mode: nil * End: */ ?> <file_sep><?php class minification extends Plugin { private static $cache_name = 'minify'; private static $stack; public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t( 'Configure' ) : $ui = new FormUI( get_class( $this ) ); // Add a text control for the home page description and textmultis for the home page keywords $ui->append( 'text', 'cache_expire', 'option:' . 'minification__expire', _t( 'Time the cache should save the minified files (sec)' ) ); //$ui->append( 'checkbox', 'extream_cache', 'minification__extreme', _t( 'ONLY reminify if the filenames have change.' ) ); $ui->append( 'submit', 'save', _t( 'Save' ) ); $ui->out(); break; } } } public function action_template_header() { //Cache::expire( self::$cache_name . '_js' ); //Cache::expire( self::$cache_name . '_css' ); // try to disable output_compression (may not have an effect) ini_set('zlib.output_compression', '0'); $modified_js = Stack::get_sorted_stack('template_header_javascript'); foreach( $modified_js as $key => $value ) { Stack::remove('template_header_javascript', $key); } Stack::add('template_header_javascript', Site::get_url('user') . '/files/minified.js', 'Minified'); $modified_css = Stack::get_sorted_stack('template_stylesheet'); $css = array(); foreach( $modified_css as $key => $value ) { $css[] = $value[0]; Stack::remove('template_stylesheet', $key); } Stack::add('template_stylesheet', array( Site::get_url('user') . "/files/minified.css", 'screen'), 'style' ); /* * If we have the files or the cache havent expired don't create new files. */ if ( !file_exists(site::get_dir('user') . '/files/minified.css') || !file_exists(site::get_dir('user') . '/files/minified.js') || ( !Cache::has( self::$cache_name . '_js' ) || !Cache::has( self::$cache_name . '_css' ) ) ) { /* Taken from min/index.php */ define('MINIFY_MIN_DIR', dirname(__FILE__) . '/min/'); // load config require MINIFY_MIN_DIR . '/config.php'; // setup include path set_include_path($min_libPath . PATH_SEPARATOR . get_include_path()); require 'Minify.php'; Minify::$uploaderHoursBehind = $min_uploaderHoursBehind; Minify::setCache( isset($min_cachePath) ? $min_cachePath : '' ,$min_cacheFileLocking ); if ($min_documentRoot) { $_SERVER['DOCUMENT_ROOT'] = $min_documentRoot; } elseif (0 === stripos(PHP_OS, 'win')) { Minify::setDocRoot(); // IIS may need help } $min_serveOptions['minifierOptions']['text/css']['symlinks'] = $min_symlinks; // Using jsmin+ 1.3 $min_serveOptions['minifiers']['application/x-javascript'] = array('JSMinPlus', 'minify'); /* Javascript */ if ( !Cache::has( self::$cache_name . '_js' ) || !file_exists(site::get_dir('user') . '/files/minified.js') ) { $js_stack = array(); foreach( $modified_js as $js ) { $js_stack[] = Site::get_path('base') . str_replace(Site::get_url('habari') . '/', '', $js); } $options = array( 'files' => $js_stack, 'encodeOutput' => false, 'quiet' => true, ); $result = Minify::serve('Files', $options); file_put_contents( site::get_dir('user') . '/files/minified.js', $result['content']); Cache::set( self::$cache_name . '_js', 'true', Options::get( 'minification__expire' ) ); } /* CSS */ if ( !Cache::has( self::$cache_name . '_css' ) || !file_exists(site::get_dir('user') . '/files/minified.css') ) { $css_stack = array(); foreach( $css as $file ) { $css_stack[] = Site::get_path('base') . str_replace(Site::get_url('habari') . '/', '', $file); } $options = array( 'files' => $css_stack, 'encodeOutput' => false, 'quiet' => true, ); // handle request $result = Minify::serve('Files', $options); file_put_contents( site::get_dir('user') . '/files/minified.css', $result['content']); Cache::set( self::$cache_name . '_css', 'true', Options::get( 'minification__expire' ) ); } } } public function filter_final_output( $buffer ) { set_include_path(dirname(__FILE__). '/min/lib' . PATH_SEPARATOR . get_include_path()); require_once 'Minify/HTML.php'; return Minify_HTML::minify( $buffer ); } } ?> <file_sep> <li id="widget-deliciousfeed" class="widget"> <h3>Notepad</h3> <ul> <?php if (is_array($deliciousfeed)) { foreach ($deliciousfeed as $post) { printf('<li class="delicious-post"><a href="%1$s" title="%2$s">%3$s</a></li>', $post->url, $post->desc, $post->title); } } else // Exceptions { echo '<li class="delicious-error">' . $deliciousfeed . '</li>'; } ?> </ul> </li><file_sep><?php class GoogleAnalytics extends Plugin { function info() { return array( 'url' => 'http://iamgraham.net/plugins', 'name' => 'GoogleAnalytics', 'description' => 'Automaticly adds Google Analytics code to the bottom of your webpage.', 'license' => 'Apache License 2.0', 'author' => '<NAME>', 'authorurl' => 'http://iamgraham.net/', 'version' => '0.4' ); } public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()) { $actions[]= _t('Configure'); } return $actions; } public function action_plugin_ui($plugin_id, $action) { if ( $plugin_id == $this->plugin_id() ) { switch ($action) { case _t('Configure'): $form= new FormUI(strtolower(get_class($this))); $form->append('text', 'clientcode', 'googleanalytics__clientcode', _t('Analytics Client Code')); $form->append('submit', 'save', 'Save'); $form->out(); break; } } } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'GoogleAnalytics', '7e57a660-3bd1-11dd-ae16-0800200c9a66', $this->info->version ); } function theme_footer() { if ( URL::get_matched_rule()->entire_match == 'user/login') { // Login page; don't dipslay return; } if ( User::identify() ) { // User is logged in, don't want to record that, do we? return; } $clientcode= Options::get('googleanalytics__clientcode'); echo <<<ENDAD <script type='text/javascript'> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> var pageTracker = _gat._getTracker("{$clientcode}"); pageTracker._initData(); pageTracker._trackPageview(); </script> ENDAD; } } ?> <file_sep><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title><?php echo $page_title; ?></title> <?php $theme->header(); ?> </head> <body id="body" class="<?php $theme->body_class(); ?>"> <div id="<?php echo $yui_id; ?>" class="<?php echo $yui_class; ?> <?php echo $align_class; ?>"> <div id="hd"> <h1><a href="/"><?php echo $site_title; ?></a></h1> <?php $theme->area('nav'); ?> </div> <file_sep><?php /** * Main class to interact with Diigo API. * * @category PHP * @package diigosilo * @author <NAME> <<EMAIL>> * @copyright 2008 <NAME> * @license http://www.apache.org/licenses/LICENSE-2.0.txt Apache Software Licence 2.0 * @version 0.1 * @link http://www.pivwan.net/weblog/plugin-diigosilo */ class DiigoAPI { private $username; private $password; private $httpClient; const API_URI = "api2.diigo.com"; public function __construct($username,$password) { // Get credentials $this->username = $username; $this->password = $password; // Init httpClient $this->httpClient = new HttpClient(self::API_URI); $this->httpClient->setUserAgent("Diigo Silo for Habari/".DIIGO_PLUGIN_VERSION); $this->httpClient->setAuthorization($this->username,$this->password); if(defined('UNITTESTING')) $this->httpClient->setDebug(true); } public function getTags() { } public function getBookmarks() { $params = array('users' => $this->username ); if($this->httpClient->get("/bookmarks",$params)==true) { return $this->parseJSON($this->httpClient->getContent()); } else { throw new Exception("WGET:"+$this->httpClient->getError()); } } private function parseJSON($json) { if (!extension_loaded('json')) { include_once(dirname(__FILE__).'/JSON.class.php'); $json = new JSON; $objs = $json->unserialize($json); } else { $objs = json_decode($json); } return($objs); } } ?> <file_sep><?php /** * Twitter Litte Plugin * * Usage: <?php $theme->twitterlitte(); ?> * **/ class TwitterLitte extends Plugin { private $config = array(); private $class_name = ''; private static function default_options() { return array ( 'username' => '', 'limit' => 1, 'search' => '', 'cache' => 600 ); } /** * Required plugin information * @return array The array of information **/ public function info() { return array( 'name' => 'Twitter Litte', 'version' => '0.1', 'url' => 'http://code.google.com/p/bcse/wiki/TwitterLitte', 'author' => '<NAME>', 'authorurl' => 'http://blog.bcse.info/', 'license' => 'Apache License 2.0', 'description' => _t('Display your latest tweets on your blog.', $this->class_name), 'copyright' => '2008' ); } /** * Add update beacon support **/ public function action_update_check() { Update::add('Twitter Litte', '0c695810-c050-11dd-ad8b-0800200c9a66', $this->info->version); } /** * Add actions to the plugin page for this plugin * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id **/ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()) { $actions[] = _t('Configure', $this->class_name); } return $actions; } /** * Respond to the user selecting an action on the plugin page * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook **/ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id == $this->plugin_id()) { switch ($action) { case _t('Configure', $this->class_name) : $ui = new FormUI(strtolower(get_class($this))); // Username $ui->append('text', 'username', 'option:' . $this->class_name . '__username', _t('Twitter Username', $this->class_name)); $ui->username->add_validator(array($this, 'validate_username')); $ui->username->add_validator('validate_required'); // How many tweets to show? $ui->append('text', 'limit', 'option:' . $this->class_name . '__limit', _t('&#8470; of Tweets', $this->class_name)); $ui->limit->add_validator(array($this, 'validate_uint')); // Match specified string $ui->append('text', 'search', 'option:' . $this->class_name . '__search', _t('Filter by', $this->class_name)); // Cache $ui->append('text', 'cache', 'option:' . $this->class_name . '__cache', _t('Cache Expiry (in seconds)', $this->class_name)); $ui->cache->add_validator(array($this, 'validate_uint')); // Save $ui->append('submit', 'save', _t('Save', $this->class_name)); $ui->set_option('success_message', _t('Options saved', $this->class_name)); $ui->out(); break; } } } public function validate_username($username) { if (!ctype_alnum($username)) { return array(_t('Your Twitter username is not valid.', $this->class_name)); } return array(); } public function validate_uint($value) { if (!ctype_digit($value) || strstr($value, '.') || $value < 0) { return array(_t('This field must be positive integer.', $this->class_name)); } return array(); } /** * Add last Twitter status, time, and image to the available template vars * @param Theme $theme The theme that will display the template **/ public function theme_twitterlitte($theme, $params = array()) { $params = array_merge($this->config, $params); $cache_name = $this->class_name . '__' . md5(serialize($params)); if ($params['username'] != '') { if (Cache::has($cache_name)) { $theme->tweets = Cache::get($cache_name); } else { if ($params['search'] != '') { $url = 'http://search.twitter.com/search.json?'; $url .= http_build_query(array( 'from' => $params['username'], 'phrase' => $params['search'], 'rpp' => $params['limit'] ), '', '&'); } else { $url = 'http://twitter.com/statuses/user_timeline/' . $params['username'] . '.json'; } try { // Get JSON content via Twitter API $call = new RemoteRequest($url); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { throw Error::raise(_t('Unable to contact Twitter.', $this->class_name)); } $response = $call->get_response_body(); // Decode JSON $obj = json_decode($response); if (isset($obj->query)) { $obj = $obj->results; // Strip user designate tags foreach ($obj as &$o) { $o->text = str_replace($params['search'], '', $o->text); } } if (!is_array($obj)) { // Response is not JSON throw Error::raise(_t('Response is not correct, Twitter server may be down or API is changed.', $this->class_name)); } $serial = serialize($obj); // Convert stdClass to TwitterLitteTweet and TwitterLitteUser $serial = str_replace('s:4:"user";O:8:"stdClass":', 's:4:"user";O:16:"TwitterLitteUser":', $serial); $serial = str_replace('O:8:"stdClass":', 'O:17:"TwitterLitteTweet":', $serial); $tweets = unserialize($serial); // Pass $tweets to $theme $theme->tweets = array_slice($tweets, 0, $params['limit']); // Do cache Cache::set($cache_name, $theme->tweets, $params['cache']); } catch (Exception $e) { $theme->tweets = $e->getMessage(); } } } else { $theme->tweets = _t('Please set your username in the Twitter Litte plugin config.', $this->class_name); } return $theme->fetch('twitterlitte'); } /** * On plugin activation, set the default options */ public function action_plugin_activation($file) { if (realpath($file) == __FILE__) { $this->class_name = strtolower(get_class($this)); foreach (self::default_options() as $name => $value) { $current_value = Options::get($this->class_name . '__' . $name); if (is_null($current_value)) { Options::set($this->class_name . '__' . $name, $value); } } } } /** * On plugin init, add the template included with this plugin to the available templates in the theme */ public function action_init() { $this->class_name = strtolower(get_class($this)); foreach (self::default_options() as $name => $value) { $this->config[$name] = Options::get($this->class_name . '__' . $name); } $this->load_text_domain($this->class_name); $this->add_template('twitterlitte', dirname(__FILE__) . '/twitterlitte.php'); } } class TwitterLitteTweet { function __get($name) { switch ($name) { case 'url': return $this->user->profile_url . '/status/' . $this->id; break; case 'message_out': $message = $this->text; // Linkify URIs $message = preg_replace( '#(?<uri>' . '(?<scheme>[a-z][a-z0-9-.+]+)://' . '(?:(?<username>[a-z0-9-_.!~*\'()%]+)(?::(?<password>[a-z0-9-_.!~*\'()%;&=+$,]+))?@)?' . '(?<host>(?:(?:(?:[a-z0-9]+|[a-z0-9][a-z0-9\-]+[a-z0-9]+)\.)+(?:[a-z]|[a-z][a-z0-9\-]+[a-z0-9])+|[0-9]{1,3}(?:\.[0-9]{1,3}){3})\.?)' . '(?::(?<port>\d{2,5}))?' . '(?<path>(?:/[a-z0-9\'\-!$%&()*,.:;@_~+=]+|[a-z0-9\'\-!$%&()*,.:;?@_~+=][a-z0-9\'\-!$%&()*,./:;?@_~+=]+)+)?' . '(?<query>\?[a-z0-9\'\-!$%&()*,./:;?@[]_{}~+=]+)?' . '(?<fragment>\#[a-z0-9\'\-!$%&()*,./:;?@_~+=]+)?' . ')#i', '<a href="${1}">${5}${7}</a>', $message); // Linkify Users $message = preg_replace('|\B@([a-z0-9_]+)\b|i', '@<a href="http://twitter.com/${1}">${1}</a>', $message); return $message; break; case 'user': // Append 'user' when search if (isset($this->user)) { return $this->user; } else { return new TwitterLitteUser(array( 'profile_image_url' => $this->profile_image_url, 'screen_name' => $this->from_user, 'id' => $this->from_user_id )); } break; default: return NULL; break; } } } class TwitterLitteUser { function __construct($params = NULL) { if (is_array($params)) { foreach ($params as $k => $v) { $this->$k = $v; } } } public static function profile_url($username) { return 'http://twitter.com/' . $username; } function __get($name) { SWITCH ($name) { case 'profile_url': return self::profile_url($this->screen_name); break; default: return NULL; break; } } } ?> <file_sep>helpify = { init: function() { helpify.container = $('#create-content #help_container'); helpify.link = $('.head a.help', helpify.container); helpify.content = $('.content', helpify.container); if( helpify.container.length == 0 ) { return; } helpify.content.hide(); helpify.link.click( function() { if( helpify.container.hasClass('open') ) { helpify.contract(); } else { helpify.expand(); } return false; }); // helpify.expand(); }, expand: function() { helpify.container.addClass('open'); helpify.container.removeClass('transparent'); helpify.content.slideDown(); }, contract: function() { helpify.content.slideUp( 'fast', function() { helpify.container.removeClass('open'); helpify.container.addClass('transparent'); }); } } $(document).ready(function() { setTimeout("helpify.init()", 200); }); <file_sep>var tagSuggest = { suggestBox: null, init: function() { if($('.create').length == 0) { return; }; tagSuggest.suggestBox= $('<ol id="tagsuggestions"></ol>').insertAfter('#tags'); $('input, textarea').blur(function() { if($('#content').val().length > 5 ) { var content = $('#content').val(); tagSuggest.fetch(content); } }); if($('#content').val().length > 5 ) { tagSuggest.fetch($('#content').val()); } }, fetch: function(content) { spinner.start(); var query = {}; query['text'] = content; query['view'] = 'json'; $.ajax({ type: 'POST', url: habari.url.habari + '/ajax/tag_suggest', data: query, dataType: 'json', success: function(json){ spinner.stop(); var response = {}; if(json.count == 0) { tagSuggest.suggestBox.addClass('none'); tagSuggest.suggestBox.html(''); $('<li></li>').text(json.message).prependTo(tagSuggest.suggestBox); } else { tagSuggest.suggestBox.html(''); tagSuggest.suggestBox.removeClass('none'); for (var index in json.tags) { tag= json.tags[index]; $('<li></li>').text(tag).prependTo(tagSuggest.suggestBox); } } tagSuggest.clickable(); } }); }, clickable: function() { $('#tagsuggestions li').each(function() { var searchstr = '\\s*"?' + $( this ).text() + '"?\\s*'; if($('#tags').val().search(searchstr) != -1) { $(this).addClass('clicked'); } }); $('#tagsuggestions li').click(function() { // here we set the current text of #tags to current for later examination var current = $('#tags').val(); // create a regex that finds the clicked tag in the input field var replstr = new RegExp('\\s*"?' + $( this ).text() + '"?\\s*', "gi"); // check to see if the tag item we clicked has been clicked before... if( $( this ).hasClass('clicked') ) { // remove that tag from the input field $( '#tags' ).val( current.replace(replstr, '') ); // unhighlight that tag $(this).removeClass( 'clicked' ); } else { // if it hasn't been clicked, go ahead and add the clicked class $(this).addClass( 'clicked' ); // be sure that the option wasn't already in the input field if(!current.match(replstr) || $( '#tags.islabeled' ).size() > 0) { // check to see if current is the default text if( $( '#tags.islabeled' ).size() > 0 ) { // and if it is, replace it with whatever we clicked $( '#tags' ).removeClass('islabeled').val( $( this ).text() ); } else { // else if we already have tag content, just append the new tag if( $('#tags' ).val() != '' ) { $( '#tags' ).val( current + "," + $( this ).text() ); } else { $( '#tags' ).val( $( this ).text() ); } } } } // replace unneccessary commas $( '#tags' ).val( $( '#tags' ).val().replace(new RegExp('^\\s*,\\s*|\\s*,\\s*$', "gi"), '')); $( '#tags' ).val( $( '#tags' ).val().replace(new RegExp('\\s*,(\\s*,)+\\s*', "gi"), ',')); }); } } $(document).ready(function(){ tagSuggest.init(); });<file_sep> <li id="widget-recentcomments" class="widget widget_comments"> <h3><?php _e('Comments'); ?></h3> <ul> <?php $entries = DB::get_results( 'SELECT {posts}.* FROM {comments}, {posts} WHERE {comments}.status = ? AND {comments}.type = ? AND {posts}.id = post_id GROUP BY post_id ORDER BY {comments}.date DESC, post_id DESC LIMIT 6', array( Comment::STATUS_APPROVED, Comment::COMMENT ), 'Post' ); foreach( $entries as $entry ) { ?> <li> <a href="<?php echo $entry->permalink; ?>" rel="bookmark" class="comment-entry-title"><?php echo $entry->title; ?></a> <a href="<?php echo $entry->permalink; ?>#comments" class="comment-count" title="<?php printf( _n('%1$d comment', '%1$d comments', $entry->comments->approved->comments->count), $entry->comments->approved->comments->count ); ?>"><?php echo $entry->comments->approved->comments->count; ?></a> <div class="comment-authors"> <?php $comments = DB::get_results( 'SELECT * FROM {comments} WHERE post_id = ? AND status = ? AND type = ? ORDER BY date DESC LIMIT 5;', array( $entry->id, Comment::STATUS_APPROVED, Comment::COMMENT ), 'Comment' ); $tcount = 0; foreach ( $comments as $comment) { $tcount++; $comment_time = strtotime($comment->date); $time_span = round( ($_SERVER['REQUEST_TIME'] - $comment_time) / (30*24*60*60), 2 ); $time_span = $time_span > 0.8 ? 0.2 : 1 - $time_span; ?> <span><a href="<?php echo $comment->post->permalink; ?>#comment-<?php echo $comment->id; ?>" title="<?php printf(_t('Posted at %1$s'), date('g:m a \o\n F jS, Y', $comment_time)); ?>"><?php echo $comment->name; ?></a></span> <?php if ( $tcount != 5 ) echo ","; else echo "..."; ?> <?php } ?> </div> </li> <?php } ?> </ul> </li> <file_sep><!-- footer --> <div class="clear"></div> </div> <div id="footer"> <p>All Content &copy; <?php Options::out('title'); ?> 2008. Powered by <a href="http://www.habariproject.org/" title="Habari">Habari <?php printf(Version::HABARI_VERSION); ?></a> &mdash; <a href="http://chasecrawford.us/habari-theme-wings/" target="_blank">Wings</a> by <a href="http://chasecrawford.us/">Chase Crawford</a></p> </div> <?php $theme->footer(); ?> </div> </body> </html> <!-- /footer --> <file_sep><?php /* package types will be: - plugin - theme - system packages will depend on "hooks" and satisfy "hooks" need a clean_up() routine to clean tmp files serialize certain feilds and call update() to save. */ class HabariPackage extends QueryRecord { public $readme_doc; private $archive; public static function default_fields() { return array( 'id' => 0, 'name' => '', 'guid' => '', 'version' => '', 'description' => '', 'author' => '', 'author_url' => '', 'habari_version' => '', 'archive_md5' => '', 'archive_url' => '', 'type' => '', 'status' => '', 'requires' => '', 'provides' => '', 'recomends' => '', 'tags' => '', 'install_profile' => '' ); } public static function get( $guid ) { $package = DB::get_row( 'SELECT * FROM ' . DB::table('packages') . ' WHERE guid = ?', array( $guid ), 'HabariPackage' ); return $package; } public function __construct( $paramarray = array() ) { $this->fields = array_merge( self::default_fields(), $this->fields ); parent::__construct( Utils::get_params( $paramarray ) ); $this->exclude_fields( 'id' ); } public function install() { if ( ! $this->is_compatible() ) { throw new Exception( "{$this->name} {$this->version} is not compatible with Habari " . Version::get_habariversion() ); } $this->get_archive(); $this->build_install_profile(); $this->unpack_files(); $this->status = 'installed'; $this->trigger_hooks( 'install' ); $this->install_profile = serialize( $this->install_profile ); $this->update(); } public function remove() { $this->install_profile = unserialize( $this->install_profile ); $this->trigger_hooks( 'remove' ); $dirs = array(); foreach ( array_reverse($this->install_profile) as $file => $location ) { $location = HABARI_PATH . '/' . ltrim( $location, '/\\' ); if ( is_dir($location) ) { $dirs[]= $location; } elseif ( is_file( $location ) ) { if ( !@unlink( $location ) ) { Session::error( "could not remove file, $location" ); } @rmdir( dirname($location) ); // DANGER WILL ROBINSON!! } } foreach ( $dirs as $dir ) { rmdir( $dir ); } $this->install_profile = ''; $this->status = ''; $this->update(); } public function upgrade() { if ( ! $this->is_compatible() ) { throw new Exception( "{$this->name} {$this->version} is not compatible with Habari " . Version::get_habariversion() ); } $this->install_profile = unserialize( $this->install_profile ); $current_install_profile = $this->install_profile; $bad_perms = array_filter( array_map( create_function( '$a', 'return ! is_writable(HABARI_PATH . "/$a");'), $current_install_profile ) ); if ( $bad_perms ) { throw new Exception( "incorrect permission settings. Please make all files for {$this->name} writeable by the server, and try again." ); } // move the current version to tmp dir $tmp_dir = HabariPackages::tempdir(); $dirs = array(); foreach( $current_install_profile as $file => $location ) { if ( is_dir( HABARI_PATH . $location ) ) { $dirs[] = HABARI_PATH . $location; continue; } else { mkdir( dirname( $tmp_dir . $location ), 0777, true ); rename( HABARI_PATH . $location, $tmp_dir . $location ); } } foreach( $dirs as $dir ) { @rmdir( $dir ); } // try and install new version try { $this->get_archive(); $this->build_install_profile(); $this->unpack_files(); $this->status = 'installed'; $this->trigger_hooks( 'upgrade' ); $this->install_profile = serialize( $this->install_profile ); $this->update(); } // revert to old version if new install failed catch( Exception $e ) { foreach( $current_install_profile as $file => $location ) { rename( $tmp_dir . '/' . $location, HABARI_PATH . '/' . $location ); } /** * @todo this needs to be a recursive rmdir */ @rmdir( $tmp_dir ); throw new Exception( $e->getMessage() ); } /** * @todo this needs to be a recursive rmdir */ // clean up tmp files @rmdir( $tmp_dir ); } private function get_archive() { $this->archive = new PackageArchive( $this->archive_url ); $this->archive->fetch(); /* if ( $this->archive->md5 != $this->archive_md5 ) { throw new Exception( "Archive MD5 ({$this->archive->md5}) at {$this->archive_url} does not match the package MD5 ({$this->archive_md5}). Archive may be corrupt." ); } */ } private function unpack_files() { foreach ( $this->archive->get_file_list() as $file ) { if ( array_key_exists( $file, $this->install_profile ) ) { $this->archive->unpack( $file, HABARI_PATH . '/' . $this->install_profile[$file], 0777 ); } else { //log files that were not installed } } } private function build_install_profile() { if ( ! $this->archive->get_file_list() ) { throw new Exception( "Archive does not contain any files" ); } $install_profile = array(); foreach ( $this->archive->get_file_list() as $file ) { if ( basename($file) == 'README' ) { $this->readme_doc = $this->archive->read_file($file); } if ( strpos( $file, '__MACOSX' ) === 0 ) { // stoopid mac users! continue; } $install_profile[$file]= HabariPackages::type_location( $this->type ) . '/' . $file; } $this->install_profile = $install_profile; } /** * @todo there should be pre and post hooks */ private function trigger_hooks( $hook ) { $install_profile = $this->install_profile; switch ( $this->type ) { case 'plugin': foreach( $install_profile as $file => $install_location ) { if ( strpos( basename($file), '.plugin.php' ) !== false ) { $plugin_file = HABARI_PATH . $install_location; } } if ( isset( $plugin_file ) ) { switch ( $hook ) { case 'install': Plugins::activate_plugin( $plugin_file ); Plugins::act('plugin_install', $plugin_file); // For the plugin to install itself Plugins::act('plugin_installed', $plugin_file); // For other plugins to react to a plugin install Session::notice( "{$this->name} {$this->version} Activated." ); break; case 'remove': Plugins::act('plugin_remove', $plugin_file); // For the plugin to remove itself Plugins::act('plugin_removed', $plugin_file); // For other plugins to react to a plugin remove Plugins::deactivate_plugin( $plugin_file ); Session::notice( "{$this->name} {$this->version} Dectivated." ); break; case 'upgrade': Plugins::act('plugin_upgrade', $plugin_file); // For the plugin to upgrade itself Plugins::act('plugin_upgraded', $plugin_file); // For other plugins to react to a plugin upgrade Session::notice( "{$this->name} {$this->version} Upgraded." ); break; } } break; case 'theme': // there are no activation/deactivation hooks for themes break; case 'system': // there are no activation/deactivation hooks for system break; } } public function is_compatible() { return HabariPackages::is_compatible( $this->habari_version ); } /** * Saves a new package to the packages table */ public function insert() { return parent::insertRecord( DB::table('packages') ); } /** * Updates an existing package to the packages table */ public function update() { return parent::updateRecord( DB::table('packages'), array('id'=>$this->id) ); } /** * Deletes an existing package */ public function delete() { return parent::deleteRecord( DB::table('packages'), array('id'=>$this->id) ); } } ?> <file_sep></div> <?php // Uncomment this to view your DB profiling info // include 'db_profiling.php'; ?> </body> </html><file_sep><?php include 'header.php'; ?> <!-- home --> <div id="primary" class="twocol-stories"> <div class="inside"> <?php $first = true; foreach ( $top_posts as $post ): ?> <div class="story<?php if ($first) echo " first" ?>"> <h3> <a href="<?php echo $post->permalink ?>" rel="bookmark" title="Permanent Link to <?php echo $post->title; ?>"> <?php echo $post->title; ?> </a> </h3> <?php echo $post->content_excerpt; ?> <div class="details"> Posted at <?php echo $post->pubdate_out ?> | <a href="<?php echo $post->permalink; ?>" title="Comments on this post"> <?php echo $post->comments->approved->count; ?> <?php echo _n( 'comment', 'comments', $post->comments->approved->count ); ?> </a> <?php if ( is_array($post->tags) ) { echo " | Filed Under: {$post->tags_out}"; } ?> </div> </div> <?php $first = false; endforeach; ?> <div class="clear"></div> </div> </div> <!-- /#primary --> <!-- /home --> <?php include 'sidebar.php'; ?> <?php include 'footer.php'; ?> <file_sep><!-- sidebar.single --> <div id="sidebar"> <div id="search-form"> <form action="<?php URL::out('display_search'); ?>" method="get"> <fieldset> <h3><label for="criteria"><?php _e('Search', 'binadamu'); ?></label></h3> <input type="text" id="criteria" name="criteria" value="<?php if (isset($criteria)) { echo htmlentities($criteria, ENT_COMPAT, 'UTF-8'); } ?>" /> <input id="search-submit" type="submit" value="Search" /> </fieldset> </form> </div> <ul id="sidebar-1" class="xoxo"> <?php if (Plugins::is_loaded('RelatedPosts')) $theme->display('relatedposts.widget'); if (Plugins::is_loaded('RelatedTags')) $theme->display('relatedtags.widget'); ?> </ul> <ul id="sidebar-2" class="xoxo"> <?php $theme->display('recententries.widget'); $theme->display('feedlink.widget'); $theme->display('admin.widget'); ?> </ul> </div> <hr /> <!-- /sidebar.single --> <file_sep><?php /** * Backtype Connect */ class BacktypePlugin extends Plugin { public function filter_post_comments(Comments $comments, Post $post) { $url = Site::get_url('habari', true) . $post->slug; foreach (self::fetch_backtype($url) as $new) { $comments[] = $new; } return $comments; } protected static function fetch_backtype($url) { $backtype = array(); $cacheName = "backtype-$url"; if ( Cache::has( $cacheName ) ) { foreach (Cache::get( $cacheName ) as $cachedBacktype) { $cachedBacktype->date = HabariDateTime::date_create($cachedBacktype->date); $backtype[] = $cachedBacktype; } return $backtype; } $connectData = json_decode(file_get_contents("http://api.backtype.com/comments/connect.json?url={$url}&key=key&itemsperpage=10000")); if (isset($connectData->comments)) { foreach ($connectData->comments as $dat) { $comment = new StdClass; switch ($dat->entry_type) { case 'tweet': $comment->id = 'backtype-twitter-' . $dat->tweet_id; $comment->url = 'http://twitter.com/' . $dat->tweet_from_user . '/status/' . $dat->tweet_id; $comment->name = '@' . $dat->tweet_from_user . ' (via Backtype: Twitter)'; $comment->content_out = InputFilter::filter($dat->tweet_text); $comment->date = $dat->tweet_created_at; break; case 'comment': $comment->id = 'backtype-comment-' . $dat->comment->id; $comment->url = $dat->comment->url; $comment->name = $dat->author->name . ' (via Backtype: ' . InputFilter::filter($dat->blog->title) . ')'; $comment->content_out = InputFilter::filter($dat->comment->content); $comment->date = $dat->comment->date; break; } if (!$comment) { continue; } $comment->status = Comment::STATUS_APPROVED; $comment->type = Comment::TRACKBACK; $comment->email = null; $backtype[] = $comment; } } Cache::set( $cacheName, $backtype ); return $backtype; } } ?><file_sep><?php /** * YouTube Silo */ class YouTubeSilo extends Plugin implements MediaSilo { const SILO_NAME = 'YouTube'; static $cache = array(); /** * Provide plugin info to the system */ public function info() { return array('name' => 'YouTube Media Silo', 'version' => '0.1.1', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Implements basic YouTube integration', 'copyright' => '2008', ); } public function action_plugin_activation($file) { if (Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__)){ $user = User::identify(); $user->info->youtube__width = '425'; $user->info->youtube__height = '355'; $user->info->commit(); } } /** * Return basic information about this silo * name- The name of the silo, used as the root directory for media in this silo */ public function silo_info() { return array('name' => self::SILO_NAME, 'icon' => URL::get_from_filesystem(__FILE__) . '/icon.png'); } /** * Return directory contents for the silo path * * @param string $path The path to retrieve the contents of * @return array An array of MediaAssets describing the contents of the directory */ public function silo_dir($path) { set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . PATH_SEPARATOR . 'Zend'); require_once 'Zend/Loader.php'; Zend_Loader::loadClass('Zend_Gdata_YouTube'); $youtube = new Zend_Gdata_YouTube(); $props = array(); $props['filetype']= 'youtube'; $username = User::identify()->info->youtube__username; $results = array(); $section = strtok($path, '/'); // TODO remove redundant code - possibly put the calls in a YouTube class? switch($section) { case 'videos': $videoFeed = $youtube->getUserUploads($username); foreach ($videoFeed as $videoEntry) { $props['url']= $this->findFlashUrl($videoEntry); $props['thumbnail_url'] = $videoEntry->mediaGroup->thumbnail[0]->url; $props['title']= $videoEntry->mediaGroup->title->text; $props['description']= $videoEntry->mediaGroup->description->text; $results[] = new MediaAsset( self::SILO_NAME . '/videos/' . $videoEntry->getVideoId(), false, $props ); } break; case 'tags': $videoFeed = $youtube->getSubscriptionFeed($username); foreach ($videoFeed as $videoEntry) { $props['url']= $this->findFlashUrl($videoEntry); $props['thumbnail_url'] = $videoEntry->mediaGroup->thumbnail[0]->url; $props['title']= $videoEntry->mediaGroup->title->text; $props['description']= $videoEntry->mediaGroup->description->text; $results[] = new MediaAsset( self::SILO_NAME . '/videos/' . $videoEntry->getVideoId(), false, $props ); } break; case 'favorites': $videoFeed = $youtube->getUserFavorites($username); foreach ($videoFeed as $videoEntry) { $props['url']= $this->findFlashUrl($videoEntry); $props['thumbnail_url'] = $videoEntry->mediaGroup->thumbnail[0]->url; $props['title']= $videoEntry->mediaGroup->title->text; $props['description']= $videoEntry->mediaGroup->description->text; $results[] = new MediaAsset( self::SILO_NAME . '/videos/' . $videoEntry->getVideoId(), false, $props ); } break; case '': $results[] = new MediaAsset( self::SILO_NAME . '/videos', true, array('title' => 'Videos') ); $results[] = new MediaAsset( self::SILO_NAME . '/tags', true, array('title' => 'Tags') ); $results[] = new MediaAsset( self::SILO_NAME . '/favorites', true, array('title' => 'Favorites') ); break; } return $results; } /** * Get the file from the specified path * * @param string $path The path of the file to retrieve * @param array $qualities Qualities that specify the version of the file to retrieve. * @return MediaAsset The requested asset */ public function silo_get($path, $qualities = null) { } /** * Get the direct URL of the file of the specified path * * @param string $path The path of the file to retrieve * @param array $qualities Qualities that specify the version of the file to retrieve. * @return string The requested url */ public function silo_url($path, $qualities = null) { } /** * Create a new asset instance for the specified path * * @param string $path The path of the new file to create * @return MediaAsset The requested asset */ public function silo_new($path) { } /** * Store the specified media at the specified path * * @param string $path The path of the file to retrieve * @param MediaAsset $ The asset to store */ public function silo_put($path, $filedata) { } /** * Delete the file at the specified path * * @param string $path The path of the file to retrieve */ public function silo_delete($path) { } /** * Retrieve a set of highlights from this silo * This would include things like recently uploaded assets, or top downloads * * @return array An array of MediaAssets to highlihgt from this silo */ public function silo_highlights() { } /** * Retrieve the permissions for the current user to access the specified path * * @param string $path The path to retrieve permissions for * @return array An array of permissions constants (MediaSilo::PERM_READ, MediaSilo::PERM_WRITE) */ public function silo_permissions($path) { } /** * Add actions to the plugin page for this plugin * The authorization should probably be done per-user. * * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id */ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()){ $actions[] = _t('Configure'); } return $actions; } /** * Respond to the user selecting an action on the plugin page * * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook */ public function action_plugin_ui($plugin_id, $action) { if ( $plugin_id == $this->plugin_id() ) { switch ($action){ case _t('Configure'): $form = new FormUI( strtolower( get_class( $this ) ) ); $form->append('text', 'username', 'user:youtube__username', 'YouTube Username:'); $form->append('text', 'width', 'user:youtube__width', 'Video Width:'); $form->append('text', 'height', 'user:youtube__height', 'Video Height:'); $form->append('submit', 'save', 'Save'); $form->set_option('success_message', _t('Options saved')); $form->out(); break; } } } public function action_admin_footer( $theme ) { // Add the media type 'youtube' if this is the publish page if ( Controller::get_var('page') == 'publish' ) { //TODO Use cache for the dimensions variables $width = User::identify()->info->youtube__width; $height = User::identify()->info->youtube__height; echo <<< YOUTUBE <script type="text/javascript"> habari.media.output.youtube = {insert: function(fileindex, fileobj) { habari.editor.insertSelection('<object width="{$width}" height="{$height}"><param name="movie" value="' + fileobj.url + '"></param><param name="wmode" value="transparent"></param><embed src="' + fileobj.url + '" type="application/x-shockwave-flash" wmode="transparent" width="{$width}" height="{$height}"></embed></object>'); }} habari.media.preview.youtube = function(fileindex, fileobj) { var stats = ''; return '<div class="mediatitle">' + fileobj.title + '</div><img src="' + fileobj.thumbnail_url + '"><div class="mediastats"> ' + stats + '</div>'; } </script> YOUTUBE; } } /** * Finds the URL for the flash representation of the specified video * * @param Zend_Gdata_YouTube_VideoEntry $entry The video entry * @return (string|null) The URL or null, if the URL is not found */ function findFlashUrl($entry) { foreach ($entry->mediaGroup->content as $content) { if ($content->type === 'application/x-shockwave-flash') { return $content->url; } } return null; } /** * Enable update notices to be sent using the Habari beacon */ public function action_update_check() { Update::add( 'YouTubeSilo', '59423325-783e-4d76-84aa-292e3dbf42c8', $this->info->version ); } } ?> <file_sep><?php if ( ! defined('HABARI_PATH' ) ) { die( _t('Please do not load this page directly. Thanks!') ); } $cookie= 'comment_' . Options::get( 'GUID' ); if ( $user ) { if ( $user->displayname != '' ) { $commenter_name = $user->displayname; } else { $commenter_name = $user->username; } $commenter_email= $user->email; $commenter_url= Site::get_url('habari'); } elseif ( isset( $_COOKIE[$cookie] ) ) { list( $commenter_name, $commenter_email, $commenter_url )= explode( '#', $_COOKIE[$cookie] ); } else { $commenter_name= ''; $commenter_email= ''; $commenter_url= ''; } if ( ! $post->info->comments_disabled ) { ?> <h3><?php echo $post->comments->moderated->count; ?> <?php echo _n( 'Response', 'Responses', $post->comments->moderated->count ); ?></h3> <ol id="comments-list"> <?php if ( $post->comments->approved->count ) { foreach ( $post->comments->approved as $comment ) { if ( $comment->url == '' ) { $comment_url = $comment->name_out; } else { $comment_url = '<a href="' . $comment->url . '" rel="external">' . $comment->name_out . '</a>'; } ?> <li id="comment-<?php echo $comment->id; ?>" class="comment"> <p class="commenter"><cite><?php echo $comment_url; ?></cite>, on <a href="#comment-<?php echo $comment->id; ?>" title="<?php _e('Permanent link to'); ?>"><?php echo $comment->date_out('d-m-Y / H:i'); ?></a>, said:</p> <div class="response"> <?php echo $comment->content_out; ?> </div> <p> <?php if ( $user ) { ?> <a href="<?php URL::out( 'admin', 'page=comment&id=' . $comment->id); ?>" title="<?php _e('Edit this comment'); ?>"><?php _e('Edit this comment'); ?></a> <?php } ?> </p> </li> <?php } } else { ?> <li><?php _e('There are currently no comments.'); ?></li> <?php } ?> </ol> <div id="commentform"> <form action="<?php URL::out( 'submit_feedback', array( 'id' => $post->id ) ); ?>" method="post"> <fieldset> <legend><?php _e('Leave a Reply'); ?></legend> <p> <label for="comment"><?php _e('Comment'); ?>:</label><br> <textarea name="content" id="comment" rows="5" cols="25" tabindex="1"></textarea> </p> <p> <label for="name"><?php _e('Name <span class=\"required\">*Required</span>'); ?>:</label> <input type="text" name="name" id="name" value="<?php echo $commenter_name; ?>" size="22" tabindex="2"> </p> <p> <label for="email"><?php _e('Email <span class=\"required\">*Required</span>'); ?>:</label> <input type="text" name="email" id="email" value="<?php echo $commenter_email; ?>" size="22" tabindex="3"> <p> <label for="url"><?php _e('Website'); ?>:</label> <input type="text" name="url" id="url" value="<?php echo $commenter_url; ?>" size="22" tabindex="4"> </p> <p> <input name="submit" type="submit" id="submit" tabindex="5" value="<?php _e('Submit'); ?>"> </p> </fieldset> </form> </div> <?php } ?><file_sep><?php class AuthorUrls extends Plugin { /** * Add the category vocabulary and create the admin token * **/ public function action_plugin_activation($file) { /* if ( Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__) ) { } */ } /** * **/ public function action_plugin_deactivation($file) { } /** * **/ public function action_init() { } public function action_update_check() { Update::add( 'AuthorURLs', 'd16fb23f-acf4-413c-a0f8-5ba55c4b3775',$this->info->version ); } /** * Add an author rewrite rule * @param Array $rules Current rewrite rules **/ public function filter_default_rewrite_rules( $rules ) { $rule = array( 'name' => 'display_entries_by_author', 'parse_regex' => '%^author/(?P<author>[^/]*)(?:/page/(?P<page>\d+))?/?$%i', 'build_str' => 'author/{$author}(/page/{$page})', 'handler' => 'UserThemeHandler', 'action' => 'display_entries_by_author', 'priority' => 5, 'description' => 'Return posts matching specified author.', ); $rules[] = $rule; return $rules; } /** * function filter_template_where_filters * Limit the Posts::get call to authors **/ public function filter_template_where_filters( $filters ) { $vars = Controller::get_handler_vars(); if( isset( $vars['author'] ) ) { $filters['user_id']= User::get( $vars['author'] )->id; } return $filters; } /** * function filter_theme_act_display_entries_by_author * Helper function: Display the posts for an author. Probably should be more generic eventually. */ public function filter_theme_act_display_entries_by_author( $handled, $theme ) { $paramarray = array(); $vars = Controller::get_handler_vars(); $author = User::get( $vars['author'] )->id; if ( isset( $author ) ) { $paramarray['fallback'][] = 'author.{$author}'; } $paramarray['fallback'][] = 'author'; $paramarray['fallback'][] = 'multiple'; $paramarray['fallback'][] = 'home'; $default_filters = array( 'content_type' => Post::type( 'entry' ), ); $paramarray[ 'user_filters' ] = $default_filters; $theme->act_display( $paramarray ); return true; } } ?> <file_sep><?php if ( $post->comments->moderated->count ) {?> <h2 id="comments"><?php echo $post->comments->moderated->count; echo _n( ' comment', ' comments', $post->comments->moderated->count ); ?></h2> <?php foreach ( $post->comments->moderated as $comment ) { ?> <div class="comments_wrap" id="comment-<?php echo $comment->id; ?>"> <div class="left"> <img src="<?php //$theme->gravatar('X', '35'); ?>http://www.gravatar.com/avatar.php?gravatar_id=<?php echo md5( $comment->email ); ?>&size=35" alt="<?php _e('Gravatar'); ?>" /> </div> <div class="right"> <h4><b><a href="<?php echo $comment->url; ?>" rel="external"><?php echo $comment->name; ?></a></b>&nbsp; on <?php echo $comment->date_out; ?></h4> <?php echo $comment->content_out; ?> <?php if ( $comment->status == Comment::STATUS_UNAPPROVED ) { echo '<p><em>Your comment is awaiting moderation.</em></p>'; } ?> </div> </div> <?php }} ?> <h2 class="lc">Leave a Comment</h2> <?php if ( Session::has_errors() ) { Session::messages_out(); } $post->comment_form()->out(); ?> <file_sep><?php class Page_Dropown extends Plugin { /** * Build a selection input of paginated paths to be used for pagination. * * @param string The RewriteRule name used to build the links. * @param array Various settings used by the method and the RewriteRule. * @return string Collection of paginated URLs built by the RewriteRule. */ function theme_page_dropdown( $theme, $rr_name = NULL, $settings = array() ) { $output = ""; $current = $theme->page; $items_per_page = isset( $theme->posts->get_param_cache['limit'] ) ? $theme->posts->get_param_cache['limit'] : Options::get( 'pagination' ); $total = Utils::archive_pages( $theme->posts->count_all(), $items_per_page ); // Make sure the current page is valid if ( $current > $total ) { $current = $total; } else if ( $current < 1 ) { $current = 1; } $output = '<select onchange="location.href=options[selectedIndex].value">'; for ( $page = 1; $page < $total; ++$page ) { $settings[ 'page' ] = $page; $caption = ( $page == $current ) ? $current : $page; // Build the path using the supplied $settings and the found RewriteRules arguments. $url = URL::get( $rr_name, $settings, false, false, false ); // Build the select option. $output .= '<option value="' . $url . '"' . ( ( $page == $current ) ? ' selected="selected"' : '' ) . '>' . $caption . '</option>' . "\n"; } $output .= "</select>"; return $output; } function action_update_check() { Update::add( $this->info->name, $this->info->guid, $this->info->version ); } } ?> <file_sep><?php class GoogleAjax extends Plugin { /** * Required plugin information * @return array The array of information **/ public function info() { return array( 'name' => 'GoogleAjax', 'version' => '0.1', 'url' => 'http://habariproject.org/', 'author' => '<NAME>', 'authorurl' => 'http://colinseymour.co.uk/', 'license' => 'Apache License 2.0', 'description' => 'Overwrites local paths to common Javascript libraries, like jQuery, MooTool etc, with the paths hosted by Google using either direct links or Google\'s google.load() method.', 'copyright' => '2009' ); } /** * The help message - it provides a larger explanation of what this plugin * does * * @return string */ public function help() { $help = '<p>' . _t( 'The GoogleAjax plugin overwrites any local paths to common Javascript libraries, with the paths hosted by Google. ') . '</p>'; $help .= '<p>' . _t( 'A full list of libraries hosted by Google can be found' ) . ' <a href="http://code.google.com/apis/ajaxlibs/documentation/">here</a></p>'; $help .= '<p>' . _t( 'By default, this plugin uses the latest version of each library, and loads the libraries using Google\'s preferred') . ' <a href="http://code.google.com/apis/ajaxlibs/documentation/">google.load()</a> ' . _t ( 'method, however you can choose to link directly to the files if you prefer.' ) . '</p>'; $help .= '<p>' . _t( 'In order for this plugin to work, you need to ensure your plugins and theme are using Habari\'s Stack methods, ie Stack::add(), to add the libraries to either the "template_header_javascript" or "template_footer_javascript" stacks and that they are using the generic names that correspond with the generic library names offered by Google, eg jquery.') . '<br><br>'; $help .= _t( 'For example:' ) . '<br><br>'; $help .= '<code>Stack::add( "template_header_javascript", "http://example.com/scripts/jquery.js", "jquery" );</code></p>'; return $help; } /** * Beacon Support for Update checking * * @access public * @return void **/ public function action_update_check() { Update::add( 'GoogleAjax', 'DDB34CAA-ECBE-11DE-A151-593F56D89593', $this->info->version ); } /** * Add the Configure option for the plugin * * @access public * @param array $actions * @param string $plugin_id * @return array */ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t( 'Configure' ); } return $actions; } /** * Plugin UI * * @access public * @param string $plugin_id * @param string $action * @return void */ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t( 'Configure' ): $ui = new FormUI( strtolower( __CLASS__ ) ); $ui->append( 'static', 'insert_desc', _t('There are two methods in which you can link to the Google hosts libraries. Here you can choose your preferred method.' ) ); $ui->append( 'radio', 'direct_link', __CLASS__ . '__direct_link', _t( 'Insert Method' ), array( TRUE => _t( 'Direct links' ), FALSE => _t( 'google.load()' ) ) ); $ui->append( 'submit', 'save', _t( 'Save' ) ); $ui->on_success ( array( $this, 'storeOpts' ) ); $ui->out(); break; } } } /** * Save our options and display a session message to confirm the save. * * @access public * @param object $ui FormUI object * @return FALSE */ public static function storeOpts ( $ui ) { $ui->save(); Session::notice( _t( 'Options saved.' ) ); return FALSE; } /** * Process the stack and replace links to Google hosted Javascript libraries. * * @param array $stack * @param string $stack_name * @param $filter * @return array */ public function filter_stack_out( $stack, $stack_name, $filter ) { if ( count( $stack ) == 0 ) { return $stack; } // Array of direct links - defaults to latest version // TODO: Google doesn't offer a method to programatically determine the available versions, so these are hard-coded. $googleHosts = array( 'jquery' => 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', 'jqueryui' => 'http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js', 'prototype' => 'http://ajax.googleapis.com/ajax/libs/prototype/1/prototype.js', 'scriptaculous' => 'http://ajax.googleapis.com/ajax/libs/scriptaculous/1/scriptaculous.js', 'mootools' => 'http://ajax.googleapis.com/ajax/libs/mootools/1/mootools-yui-compressed.js', 'dojo' => 'http://ajax.googleapis.com/ajax/libs/dojo/1/dojo/dojo.xd.js', 'swfobject' => 'http://ajax.googleapis.com/ajax/libs/swfobject/2/swfobject.js', 'yui' => 'http://ajax.googleapis.com/ajax/libs/yui/2/build/yuiloader/yuiloader-min.js', 'ext-core' => 'http://ajax.googleapis.com/ajax/libs/ext-core/3/ext-core.js', 'chrome-frame' => 'http://ajax.googleapis.com/ajax/libs/chrome-frame/1/CFInstall.min.js' ); switch ( $stack_name ) { case 'template_footer_javascript': case 'template_header_javascript': if ( Options::get( __CLASS__ . '__direct_link') ) { $int = array_intersect_key( $googleHosts, $stack ); return array_merge( $stack, $int ); } else { $newstack['jsapi'] = 'http://www.google.com/jsapi'; $newstack['jsapi_load'] = ''; foreach ( $stack as $key => $value ) { if ( array_key_exists( $key, $googleHosts ) ) { $ver = explode( '/', $googleHosts[$key] ); $newstack['jsapi_load'] .= 'google.load("'.$key.'", "'.$ver[6].'");'; // This assumes Google keeps a consistent URL structure with the version in the 6th field. unset( $stack[$key] ); // Remove replaced key from original stack } } return array_merge( $newstack, $stack ); // Merge stacks, putting the Google API calls first. } break; default: return $stack; } } } ?><file_sep><?php include 'header.php'; ?> <!-- home --> <div id="main" class="push-4 span-16"> <h2 class="message">404 - Object not found :P</h2> <div id="content" class=""> <p>A search perhaps?</p> </div> </div> <?php include 'sidebar.php'; ?> <?php include 'footer.php'; ?> </div> </body> </html><file_sep> <ul class=items"> <li class="item clear"> <span class="title pct80"><b>Recent Accuracy</b></span><span class="comments pct20"><?php echo $accuracy; ?>%</span> </li> <li class="item clear"> <span class="pct80">Spam</span><span class="comments pct20"><?php echo $spam; ?></span> </li> <li class="item clear"> <span class="pct80">Innocents</span><span class="comments pct20"><?php echo $ham; ?></span> </li> <li class="item clear"> <span class="pct80">False Negatives</span><span class="comments pct20"><?php echo $false_negatives; ?></span> </li> <li class="item clear"> <span class="pct80">False Positives</span><span class="comments pct20"><?php echo $false_positives; ?></span> </li> </ul> <file_sep><!-- To customize this template, copy it to your currently active theme directory and edit it --> <div id="twitterlitte"> <ul> <?php if (is_array($tweets)) { foreach ($tweets as $tweet) { printf('<li class="twitter-message">%1$s <a href="%2$s"><abbr title="%3$s">#</abbr></a></li>', $tweet->message_out, $tweet->url, $tweet->created_at); } printf('<li class="twitter-more"><a href="%s">' . _t('Read more…', $this->class_name) . '</a></li>', $tweets[0]->user->profile_url); } else { // Exceptions echo '<li class="twitter-error">' . $tweets . '</li>'; } ?> </ul> </div><file_sep><?php class GoogleAjax extends Plugin { /** * Beacon Support for Update checking * * @access public * @return void */ public function action_update_check() { Update::add( 'GoogleAjax', 'DDB34CAA-ECBE-11DE-A151-593F56D89593', $this->info->version ); } /** * Add the Configure option for the plugin * * @access public * @param array $actions * @param string $plugin_id * @return array */ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t( 'Configure' ); } return $actions; } /** * Plugin UI * * @access public * @param string $plugin_id * @param string $action * @return void */ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t( 'Configure' ): $ui = new FormUI( strtolower( __CLASS__ ) ); $ui->append( 'static', 'insert_desc', _t('There are two methods in which you can link to the Google hosts libraries. Here you can choose your preferred method.' ) ); $ui->append( 'radio', 'direct_link', __CLASS__ . '__direct_link', _t( 'Insert Method' ), array( TRUE => _t( 'Direct links' ), FALSE => _t( 'google.load()' ) ) ); $ui->append( 'submit', 'save', _t( 'Save' ) ); $ui->on_success ( array( $this, 'storeOpts' ) ); $ui->out(); break; } } } /** * Save our options and display a session message to confirm the save. * * @access public * @param object $ui FormUI object * @return FALSE */ public static function storeOpts ( $ui ) { $ui->save(); Session::notice( _t( 'Options saved.' ) ); return FALSE; } /** * Process the stack and replace links to Google hosted Javascript libraries. * * @param array $stack * @param string $stack_name * @param $filter * @return array */ public function filter_stack_out( $stack, $stack_name, $filter ) { if ( count( $stack ) == 0 ) { return $stack; } // Array of direct links - defaults to latest version // TODO: Google doesn't offer a method to programatically determine the available versions, so these are hard-coded. $googleHosts = array( 'jquery' => 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', 'jqueryui' => 'http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js', 'prototype' => 'http://ajax.googleapis.com/ajax/libs/prototype/1/prototype.js', 'scriptaculous' => 'http://ajax.googleapis.com/ajax/libs/scriptaculous/1/scriptaculous.js', 'mootools' => 'http://ajax.googleapis.com/ajax/libs/mootools/1/mootools-yui-compressed.js', 'dojo' => 'http://ajax.googleapis.com/ajax/libs/dojo/1/dojo/dojo.xd.js', 'swfobject' => 'http://ajax.googleapis.com/ajax/libs/swfobject/2/swfobject.js', 'yui' => 'http://ajax.googleapis.com/ajax/libs/yui/2/build/yuiloader/yuiloader-min.js', 'ext-core' => 'http://ajax.googleapis.com/ajax/libs/ext-core/3/ext-core.js', 'chrome-frame' => 'http://ajax.googleapis.com/ajax/libs/chrome-frame/1/CFInstall.min.js' ); switch ( $stack_name ) { case 'template_header_javascript': case 'template_footer_javascript': // First we remove the duplicates that occur in the header stack if we're processing the footer stack - Habari doesn't do this, so we do. This is all about performance after all. if ( $stack_name == 'template_footer_javascript' ) { $header_stack = Stack::get_named_stack( 'template_header_javascript' ); $stack = array_diff_key( $stack, $header_stack ); } if ( Options::get( __CLASS__ . '__direct_link' ) ) { $int = array_intersect_key( $googleHosts, $stack ); return array_merge( $stack, $int ); } else { // We only need this in the footer if it's not already in the header $newstack['jsapi'] = 'http://www.google.com/jsapi'; if ( ( $stack_name == 'template_footer_javascript' ) && array_intersect_key( $googleHosts, $header_stack ) ) { unset( $newstack['jsapi'] ); } $newstack['jsapi_load'] = ''; foreach ( $stack as $key => $value ) { if ( array_key_exists( $key, $googleHosts ) ) { $ver = explode( '/', $googleHosts[$key] ); $newstack['jsapi_load'] .= 'google.load("'.$key.'", "'.$ver[6].'");'; // This assumes Google keeps a consistent URL structure with the version in the 6th field. unset( $stack[$key] ); // Remove replaced key from original stack } } return ( $newstack['jsapi_load'] != '' ) ? array_merge( $newstack, $stack ) : $stack; // Merge stacks, putting the Google API calls first. } break; default: return $stack; } } } ?><file_sep><?php /** * * * @package blogroll */ class Blogs extends ArrayObject { public function __get( $name ) { switch( $name ) { case 'oneblog': return ( count( $this ) == 1 ); case 'count': return count( $this ); } return false; } public function get( $paramarray= array() ) { //convert to array if passed as a querystring $paramarray= Utils::get_params( $paramarray ); $wheres= array(); $params= array(); $where=''; foreach ($paramarray as $key=>$value){ if ($key != 'order_by' && $key != 'limit'){ if ( isset( $value ) && $value != 'any' ){ if ( is_array( $value ) ){ $wheres[]= $key.' IN(' . implode( ',',array_fill( 0, $count($value), '?' ) ) . ')'; $params[]= array_merge($params,$value); } else { $wheres[]= $key.'='.$value; $params[]= $value; } } } } extract($paramarray= Utils::get_params( $paramarray )); if ( isset( $order_by ) ){ $order_by='ORDER BY ' . str_replace( 'random', 'RAND()', $order_by ); } else { $order_by=''; } if ( isset( $limit ) ){ $limit='LIMIT '.$limit; } else { $limit=''; } if ( !empty( $wheres ) ){ $where='WHERE '. implode(' AND ',$wheres); } $query= "SELECT * FROM {blogroll} " . $where . ' ' . $order_by . ' ' . $limit; $results= DB::get_results($query, $params, 'Blog'); $c= __CLASS__; return new $c( $results ); } public static function get_info_from_url( $url ) { $info= array(); $data= RemoteRequest::get_contents( $url ); $feed= self::get_feed_location( $data, $url ); if ( $feed ) { $info['feed']= $feed; $data= RemoteRequest::get_contents( $feed ); } else { $info['feed']= $url; } // try and parse the xml try { $xml= new SimpleXMLElement( $data ); switch ( $xml->getName() ) { case 'RDF': case 'rss': $info['name']= (string) $xml->channel->title; $info['url']= (string) $xml->channel->link; if ( (string) $xml->channel->description ) $info['description']= (string) $xml->channel->description; break; case 'feed': $info['name']= (string) $xml->title; if ( (string) $xml->subtitle ) $info['description']= (string) $xml->subtitle; foreach ( $xml->link as $link ) { $atts= $link->attributes(); if ( $atts['rel'] == 'alternate' ) { $info['url']= (string) $atts['href']; break; } } break; } } catch ( Exception $e ) { return array(); } return $info; } public static function get_feed_location( $html, $url ) { preg_match_all( '/<link\s+(.*?)\s*\/?>/si', $html, $matches ); $links= $matches[1]; $final_links= array(); $href= ''; $link_count= count( $links ); for( $n= 0; $n < $link_count; $n++ ) { $attributes= preg_split('/\s+/s', $links[$n]); foreach ( $attributes as $attribute ) { $att= preg_split( '/\s*=\s*/s', $attribute, 2 ); if ( isset( $att[1] ) ) { $att[1]= preg_replace( '/([\'"]?)(.*)\1/', '$2', $att[1] ); $final_link[strtolower( $att[0] )]= $att[1]; } } $final_links[$n]= $final_link; } for ( $n= 0; $n < $link_count; $n++ ) { if ( isset($final_links[$n]['rel']) && strtolower( $final_links[$n]['rel'] ) == 'alternate' ) { if ( isset($final_links[$n]['type']) && in_array( strtolower( $final_links[$n]['type'] ), array( 'application/rss+xml', 'application/atom+xml', 'text/xml' ) ) ) { $href= $final_links[$n]['href']; } if ( $href ) { if ( strstr( $href, "http://" ) !== false ) { $full_url= $href; } else { $url_parts= parse_url( $url ); $full_url= "http://$url_parts[host]"; if ( isset( $url_parts['port'] ) ) { $full_url.= ":$url_parts[port]"; } if ( $href{0} != '/' ) { $full_url.= dirname( $url_parts['path'] ); if ( substr( $full_url, -1 ) != '/' ) { $full_url.= '/'; } } $full_url.= $href; } return $full_url; } } } return false; } } ?> <file_sep><div id="div_<?php echo $slug; ?>"></div> <script type="text/javascript"> var opts = { <?php echo $js_opts; ?> }; <?php echo $js_data; ?> <?php echo $js_draw; ?> </script> <file_sep><?php // Apply Format::tag_and_list() to post tags... Format::apply( 'tag_and_list', 'post_tags_out' ); // Limit post length on the home page to 1 paragraph or 100 characters Format::apply( 'autop', 'post_content_excerpt' ); Format::apply_with_hook_params( 'more', 'post_content_excerpt', '', 100, 1 ); // Apply Format::nice_date() to post and comment date... Format::apply( 'nice_date', 'post_pubdate_out', 'F j, Y g:ia' ); Format::apply( 'nice_date', 'comment_date_out', 'F j, Y g:ia' ); define( 'THEME_CLASS', 'wings' ); class wings extends Theme { public function add_template_vars() { if( !$this->template_engine->assigned( 'pages' ) ) { $this->assign('pages', Posts::get( array( 'content_type' => 'page', 'status' => Post::status('published'), 'nolimit' => 1 ) ) ); } } public function action_form_comment( $form ) { $this->add_template('formcontrol_text', dirname(__FILE__).'/forms/formcontrol_text.php', true); $this->add_template('formcontrol_textarea', dirname(__FILE__).'/forms/formcontrol_textarea.php', true); $form->cf_commenter->caption = '<strong>Name</strong> *Required'; $form->cf_email->caption = '<strong>Mail</strong> (will not be published) *Required'; $form->cf_url->caption = '<strong>Website</strong>'; } } ?> <file_sep><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <?php $extra_title = ''; if( isset($posts) && count($posts) == 1 && isset($post) ) { $extra_title = ' - ' . $post->title; } ?> <title><?php Options::out( 'title' ); ?><?php echo $extra_title ?></title> <meta http-equiv="Content-Type" content="text/html"> <meta name="generator" content="Habari"> <link rel="alternate" type="application/atom+xml" title="Atom 1.0" href="<?php echo $feed_alternate; ?>"> <link rel="edit" type="application/atom+xml" title="Atom Publishing Protocol" href="<?php URL::out( 'introspection' ); ?>"> <link rel="EditURI" type="application/rsd+xml" title="RSD" href="<?php URL::out( 'rsd' ); ?>"> <link rel="stylesheet" type="text/css" media="screen" href="<?php Site::out_url( 'theme' ); ?>/style.css"> <?php $theme->header() ?> </head> <body class="home"> <div id="page-outer"> <div id="page"> <div id="header"> <h1><a href="<?php Site::out_url( 'habari' ); ?>"><?php Options::out( 'title' ); ?></a></h1> <ul class="menu"> <li><a href="<?php Site::out_url( 'habari' ); ?>" title="Home">Home</a></li> <?php // Menu tabs foreach ( $pages as $tab ) { ?> <li><a href="<?php echo $tab->permalink; ?>" title="<?php echo $tab->title; ?>"><?php echo $tab->title; ?></a></li> <?php } if ( $user ) { ?> <li class="admintab"><a href="<?php Site::out_url( 'admin' ); ?>" title="Admin area">Admin</a></li> <?php } ?> </ul> </div> <hr> <!-- /header --> <file_sep>google.load("maps", "2"); google.setOnLoadCallback(function() { var googleMaps = { map: null, pano: null, panoClient: null, overlayInstance: null, marker: null, init: function() { $('#googlemaps_streetview_canvas').hide(); if (GBrowserIsCompatible()) { googleMaps.map = new google.maps.Map2($('#googlemaps_canvas').get(0), {size: new google.maps.Size(600, 300)}); googleMaps.map.addControl(new google.maps.MapTypeControl()); googleMaps.map.addControl(new google.maps.LargeMapControl()); googleMaps.map.enableScrollWheelZoom(); googleMaps.map.enableContinuousZoom(); googleMaps.map.setCenter(new google.maps.LatLng(42.366662,-71.106262), 11); GEvent.addListener(googleMaps.map, 'click', function(overlay, point) { if (!googleMaps.marker) return; googleMaps.marker.setLatLng(point); googleMaps.panoClient.getNearestPanorama(point, googleMaps.showPanoData); }); $('#googlemaps_search').click(function () { googleMaps.search(); }); $('#googlemaps_address').keypress(function (e) { if (e.keyCode == 13) { // Enter googleMaps.search(); return false; } }); $('#googlemaps_streetview_toggle').click(function () { if (!googleMaps.overlayInstance) { googleMaps.overlayInstance = new GStreetviewOverlay(); googleMaps.map.addOverlay(googleMaps.overlayInstance); if (!googleMaps.pano) { options = { latlng: googleMaps.map.getCenter() }; googleMaps.pano = new google.maps.StreetviewPanorama($('#googlemaps_streetview_canvas').get(0), options); GEvent.addListener(googleMaps.pano, 'error', googleMaps.handleError); googleMaps.panoClient = new GStreetviewClient(); var guyIcon = new google.maps.Icon(G_DEFAULT_ICON); guyIcon.image = "http://maps.google.com/intl/en_us/mapfiles/cb/man_arrow-0.png"; guyIcon.transparent = "http://maps.google.com/intl/en_us/mapfiles/cb/man-pick.png"; guyIcon.imageMap = [ 26,13, 30,14, 32,28, 27,28, 28,36, 18,35, 18,27, 16,26, 16,20, 16,14, 19,13, 22,8 ]; guyIcon.iconSize = new google.maps.Size(49, 52); guyIcon.iconAnchor = new google.maps.Point(25, 35); guyIcon.infoWindowAnchor = new google.maps.Point(25, 5); googleMaps.marker = new google.maps.Marker(options.latlng, {icon: guyIcon, draggable: true}); googleMaps.map.addOverlay(googleMaps.marker); GEvent.addListener(googleMaps.marker, 'dragend', function() { var latlng = googleMaps.marker.getLatLng(); googleMaps.panoClient.getNearestPanorama(latlng, googleMaps.showPanoData); }); } $('#googlemaps_streetview_canvas').show(); } else { googleMaps.map.removeOverlay(googleMaps.overlayInstance); googleMaps.overlayInstance = null; $('#googlemaps_streetview_canvas').hide(); } }); $('#googlemaps_insert').click(function () { googleMaps.insert(); }); } }, unload: function() { GUnload(); }, search: function() { var geocoder = new google.maps.ClientGeocoder(); geocoder.getLatLng( $('#googlemaps_address').val(), function (point) { if (!point) { humanMsg.displayMsg('could not understand the location ' + $('#googlemaps_address').val()); } else { googleMaps.map.setCenter(point, 13); } } ); }, insert: function() { var maptype; var maptype_arg = googleMaps.map.getCurrentMapType().getUrlArg(); var center = googleMaps.map.getCenter(); var link = 'http://maps.google.com/?ie=UTF8&amp;ll=' + center.lat() + ',' + center.lng() + '&amp;z=' + googleMaps.map.getZoom() + '&amp;t=' + maptype_arg; if (googleMaps.pano) { var latlng = googleMaps.marker.getLatLng(); var pov = googleMaps.pano.getPOV(); link += '&amp;'; link += 'layer=c&amp;'; link += 'cbp=1,' + pov.yaw.toFixed(0) + ',,' + pov.zoom + ',' + pov.pitch.toFixed(0) + '&amp;'; link += 'cbll=' + latlng.lat() + ',' + latlng.lng(); } var tag = '<a href="' + link + '">Google Maps (Lat=' + center.lat() + ',Lng=' + center.lng() + ')</a>'; habari.editor.insertSelection(tag); }, handleError: function(errorCode) { if (errorCode == google.maps.FLASH_UNAVAILABLE) { humanMsg.displayMsg("Error: Flash doesn't appear to be supported by your browser"); return; } }, showPanoData: function(panoData) { if (panoData.code != 200) return; googleMaps.pano.setLocationAndPOV(panoData.location.latlng); } } googleMaps.init(); }); $(document).unload(function() { googleMaps.unload(); }); <file_sep><?php Plugins::act( 'theme_searchform_before' ); ?> <form method="get" id="searchform" action="<?php URL::out( 'display_search' ); ?>"> <div> <input type="search" id="s" name="criteria" value="<?php echo isset( $theme->criteria ) ? htmlentities( $theme->criteria, ENT_COMPAT, 'UTF-8' ) : ''; ?>" placeholder="<?php echo _t( 'Search' ); ?>" /> <input type="submit" id="searchsubmit" value="<?php echo _t( 'Search' ); ?>" /> </div> </form> <?php Plugins::act( 'theme_searchform_after' ); ?> <file_sep> <h2>Today's GetCliky Stats</h2><div class="handle">&nbsp;</div> <ul class="items"> <li class="item clear"> <span class="pct90">Site Rank</span> <span class="comments pct10"><?php print $site_rank; ?></span> </li> <li class="item clear"> <span class="pct90">Current Visitors (Online Now)</span> <span class="comments pct10"><?php print $current_visitors; ?></span> </li> <li class="item clear"> <span class="pct90">Unique Visitors</span> <span class="comments pct10"><?php print $unique_visitors; ?></span> </li> <li class="item clear"> <span class="pct90">No of Actions (sum of page views, downloads, and outbound links)</span> <span class="comments pct10"><?php print $todays_actions; ?></span> </li> <li class="item clear"> <span class="pct90">Average Actions</span> <span class="comments pct10"><?php print $actions_average; ?></span> </li> <li class="item clear"> <span class="pct90">Total Time Spent On Site</span> <span class="comments pct10"><?php print $time_total; ?></span> </li> <li class="item clear"> <span class="pct90">Average Time</span> <span class="comments pct10"><?php print $time_average; ?></span> </li> </ul> <p> For more statistics for your site visit <a href="http://getclicky.com/stats/home?site_id=<?php print $siteid;?>">GetClicky</a> </p> <file_sep><?php /** * Habari Paginator plugin, a more powerful pagination. * * @package Habari */ class Paginator extends Plugin { /** * Provide plugin info to the system */ public function info() { return array( 'name' => 'Paginator', 'version' => '0.1', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Decide how the pagination, either as a `unordered list` or as a `span`.', 'copyright' => '2007' ); } /** * Formats the pagination array. * @param array Pagination array * @param string Style to return [ list | span ] * @return string Formatted page navigation */ public function format( $pagination, $style ) { switch ( $style ) { case 'list': $out = '<ul class="page_selector">'; foreach ( $pagination['pages'] as $page ) { if ( is_array( $page ) ) { $out.= '<li><a href="' . $page['url'] . '"' . ( ( $page['caption'] == $pagination['current'] ) ? ' class="current"' : '' ) . '>' . $page['caption'] . '</a></li>'; } else { $out.= '<li>' . $page . '</li>'; } } $out.= '</ul>'; break; case 'span': $out = '<span class="page_selector">'; foreach ( $pagination['pages'] as $page ) { if ( is_array( $page ) ) { $out.= '<a href="' . $page['url'] . '"' . ( ( $page['caption'] == $pagination['current'] ) ? ' class="current">[' . $page['caption'] . ']' : '>' . $page['caption'] ) . '</a>'; } else { $out.= $page; } } $out.= '</span>'; break; } return $out; } /** * function page_selector * Returns a page selector * * The $paramarray can contain: * 'current' => Current page * 'total' => Total pages * 'token' => Token for the URL calls * 'settings' => Array of settings for the URL calls * * @param array parameters to render the pagination * @return array contains a 'current' and 'pages' key **/ public function get( $current, $total, $rr_name = NULL, $settings = array() ) { // Extract the style and remove it from the array. if ( isset( $settings['style'] ) ) { $style = $settings['style']; unset( $settings['style'] ); } else { $style = 'span'; } // If RewriteRule name is not supplied, use the current RewriteRule if ( $rr_name == '' ) { $rr = URL::get_matched_rule(); } else { list( $rr )= RewriteRules::by_name( $rr_name ); } // Retrieve the RewriteRule and aggregate an array of matching arguments $rr_named_args = $rr->named_args; $rr_args = array_merge( $rr_named_args['required'], $rr_named_args['optional'] ); $rr_args_values = array(); foreach ( $rr_args as $rr_arg ) { $rr_arg_value = Controller::get_var( $rr_arg ); if ( $rr_arg_value != '' ) { $rr_args_values[$rr_arg]= $rr_arg_value; } } $settings = array_merge( $settings, $rr_args_values ); // Current page if ( $current > $total ) { $current = $total; } $p = array( 'current' => $current ); // 1 - First page $p['pages'][1]['caption']= 1; // Skip if there is only one page if ( $total > 1 ) { // &amp; if ( ( $current != 1 || $current != $total ) && ( $current - 2 > 1 ) ) { $p['pages'][]= '&hellip;'; } // Previous Page if ( $current - 1 > 1 ) { $p['pages'][]['caption']= $current - 1; } // Current Page if ( $current > 1 && $current < $total ) { $p['pages'][]['caption']= $current; } // Next Page if ( $current + 1 < $total ) { $p['pages'][]['caption']= $current + 1; } // &hellip; if ( ( $current != 1 || $current != $total ) && ( $current + 2 < $total ) ) { $p['pages'][]= '&hellip;'; } // Last page $p['pages'][]['caption']= $total; } $count = count( $p['pages'] ); for($z = 1; $z <= $count; $z++) { if ( is_array( $p['pages'][$z] ) ) { $p['pages'][$z]['url']= $rr->build( array_merge($settings, array('page'=>$p['pages'][$z]['caption'])), false); } } return self::format( $p, $style ); } public function out( $current, $total, $rr_name = NULL, $settings = array() ) { print self::get( $current, $total, $rr_name, $settings ); } } ?> <file_sep><?php class KeyNavigation extends Plugin { /** * Add update beacon support **/ public function action_update_check() { Update::add( 'KeyNavigation', '', $this->info->version ); } /** * Add help text to plugin configuration page **/ public function help() { $help = _t('Allow users to navigate between posts on a page by pressing j (down) and k (up). Handles paging when on the first or last post.'); return $help; } /** * Set default options **/ public function action_plugin_activation( $file ) { if ( realpath( $file ) == __FILE__ ) { Options::set( 'key_nav_paging_error', '100' ); Options::set( 'key_nav_delay', '100' ); Options::set( 'key_nav_selector', 'div.post' ); } } /** * Add appropriate javascript. **/ public function action_template_header( $theme ) { Stack::add( 'template_header_javascript', Site::get_url('scripts') . '/jquery.js', 'jquery' ); Stack::add( 'template_header_javascript', Site::get_url('habari') . "/3rdparty/hotkeys/jquery.hotkeys.js", 'jquery.hotkeys', 'jquery' ); Stack::add( 'template_header_javascript', $this->js($theme), 'key_navigation', array('jquery, jquery.hotkeys') ); } /** * Create plugin configuration **/ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t('Configure'); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case _t('Configure') : $form = new FormUI(strtolower(get_class($this))); // You can't go past the first/last post message $form->append( 'text', 'paging_error', 'option:key_nav_paging_error', _t('Message to display when a user tries to go past the first or last post') ); // Selector for posts $form->append( 'text', 'selector', 'option:key_nav_selector', _t('jQuery selector to identify posts.') ); // Scroll delay // TODO Validate as a number, or perhaps a selector $form->append( 'text', 'delay', 'option:key_nav_delay', _t('Scroll delay (ms)') ); $form->append( 'submit', 'save', _t('Save') ); $form->set_option( 'success_message', _t( 'Configuration saved') ); $form->out(); break; } } } private function js($theme) { // If there's a single post, ascend or descend appropriately if ( $theme->posts instanceOf Post) { $next = Posts::ascend($theme->posts)->permalink; $previous = Posts::descend($theme->posts)->permalink; } // If there are multiple posts, page appropriately else { $page = $theme->page; $items_per_page = isset($theme->posts->get_param_cache['limit']) ? $theme->posts->get_param_cache['limit'] : Options::get('pagination'); $total = Utils::archive_pages( $theme->posts->count_all(), $items_per_page ); if ( $page + 1 > $total ) { $next = ''; } else { $next = URL::get(null, array('page' => $page + 1)); } if ( $page - 1 < 1 ) { $previous = ''; } else { $previous = URL::get(null, array('page' => $page - 1)); } } $delay = Options::get( 'key_nav_delay' ); $selector = Options::get( 'key_nav_selector' ); return <<<KEYNAV $(document).ready(function() { current = 0; $.hotkeys.add('j', {propagate:true, disableInInput: true}, function(){ if (current == $('$selector').length-1) { if ('$next' == '') { // TODO Show the no more posts message } else { // go to next page window.location = '$next'; } } else { target = $('$selector').eq(current+1).offset().top $('html,body').animate({scrollTop: target}, $delay); current++; } }); $.hotkeys.add('k', {propagate:true, disableInInput: true}, function(){ if (current == 0) { if ('$previous' == '') { // Show the no more posts message } else { // go to previous page window.location = '$previous'; } } else { target = $('$selector').eq(current-1).offset().top $('html,body').animate({scrollTop: target}, $delay); current--; } }); }); KEYNAV; } } ?> <file_sep><?php /** * Jaiku Plugin * * Usage: <?php $theme->jaiku(); ?> * **/ class Jaiku extends Plugin { private $config = array(); private $class_name = ''; private $default_options = array( 'username' => '', 'limit' => 1, 'cache' => 60 ); /** * Required plugin information * @return array The array of information **/ public function info() { return array( 'name' => 'Jaiku', 'version' => '0.5-0.5', 'url' => 'http://code.google.com/p/bcse/wiki/Jaiku', 'author' => '<NAME>', 'authorurl' => 'http://blog.bcse.info/', 'license' => 'Apache License 2.0', 'description' => 'Display your latest presences on your blog.', 'copyright' => '2008' ); } /** * Add update beacon support **/ public function action_update_check() { Update::add('Jaiku', '8d803db0-2d48-11dd-bd0b-0800200c9a66', $this->info->version); } /** * Add actions to the plugin page for this plugin * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id **/ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()) { $actions[] = _t('Configure', $this->class_name); } return $actions; } /** * Respond to the user selecting an action on the plugin page * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook **/ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id == $this->plugin_id()) { switch ($action) { case _t('Configure', $this->class_name) : $ui = new FormUI(strtolower(get_class($this))); // Username $ui->append('text', 'username', 'option:' . $this->class_name . '__username', _t('Jaiku Username', $this->class_name)); $ui->username->add_validator(array($this, 'validate_username')); $ui->username->add_validator('validate_required'); // How many presences to show? $ui->append('text', 'limit', 'option:' . $this->class_name . '__limit', _t('&#8470; of Presences', $this->class_name)); $ui->limit->add_validator(array($this, 'validate_uint')); // Cache $ui->append('text', 'cache', 'option:' . $this->class_name . '__cache', _t('Cache Expiry (in seconds)', $this->class_name)); $ui->cache->add_validator(array($this, 'validate_uint')); // Save $ui->append('submit', 'save', _t('Save', $this->class_name)); $ui->set_option('success_message', _t('Options saved', $this->class_name)); $ui->out(); break; } } } public function validate_username($username) { if (!ctype_alnum($username)) { return array(_t('Your Jaiku username is not valid.', $this->class_name)); } return array(); } public function validate_uint($value) { if (!ctype_digit($value) || strstr($value, '.') || $value < 0) { return array(_t('This field must be positive integer.', $this->class_name)); } return array(); } /** * Add last Jaiku status, time, and image to the available template vars * @param Theme $theme The theme that will display the template **/ public function theme_jaiku($theme, $params = array()) { $params = array_merge($this->config, $params); $cache_name = $this->class_name . '__' . md5(serialize($params)); if ($params['username'] != '') { if (Cache::has($cache_name)) { $theme->presences = Cache::get($cache_name); } else { if ($params['limit'] == 1) { $url = 'http://' . $params['username'] . '.jaiku.com/presence/last/json'; } else { $url = 'http://' . $params['username'] . '.jaiku.com/feed/json'; } try { // Get JSON content via Jaiku API $call = new RemoteRequest($url); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { throw Error::raise(_t('Unable to contact Jaiku.', $this->class_name)); } $response = $call->get_response_body(); // Decode JSON $obj = json_decode($response); if (! $obj instanceof stdClass) { // Response is not JSON throw Error::raise(_t('Response is not correct, maybe Jaiku server is down or API is changed.', $this->class_name)); } $serial = property_exists($obj, 'stream') ? serialize($obj->stream) : serialize($obj) ; // Convert stdClass to JaikuPresence and JaikuUser $serial = str_replace('s:4:"user";O:8:"stdClass":', 's:4:"user";O:9:"JaikuUser":', $serial); $serial = str_replace('O:8:"stdClass":', 'O:13:"JaikuPresence":', $serial); $presences = unserialize($serial); // Pass $presences to $theme if (is_array($presences)) { $theme->presences = array_slice($presences, 0, $params['limit']); } else { $theme->presences = $presences; } // Do cache Cache::set($cache_name, $theme->presences, $params['cache']); } catch (Exception $e) { $theme->presences = $e->getMessage(); } } } else { $theme->presences = _t('Please set your username in the Jaiku plugin config.', $this->class_name); } return $theme->fetch('jaiku'); } /** * On plugin activation, set the default options */ public function action_plugin_activation($file) { if (realpath($file) == __FILE__) { $this->class_name = strtolower(get_class($this)); foreach ($this->default_options as $name => $value) { $current_value = Options::get($this->class_name . '__' . $name); if (is_null($current_value)) { Options::set($this->class_name . '__' . $name, $value); } } } } /** * On plugin init, add the template included with this plugin to the available templates in the theme */ public function action_init() { $this->class_name = strtolower(get_class($this)); foreach ($this->default_options as $name => $value) { $this->config[$name] = Options::get($this->class_name . '__' . $name); } $this->load_text_domain($this->class_name); $this->add_template('jaiku', dirname(__FILE__) . '/jaiku.php'); } } class JaikuPresence extends stdClass { } class JaikuUser extends stdClass { } ?> <file_sep><?php class YUIWYSIWYG extends Plugin { public function action_admin_header($theme) { if ( $theme->page == 'publish' ) { Plugins::act('add_yuieditor_admin'); } } public function action_add_yuieditor_admin() { Stack::add('admin_header_javascript', 'http://yui.yahooapis.com/combo?2.8.2r1/build/yahoo-dom-event/yahoo-dom-event.js&2.8.2r1/build/container/container_core-min.js&2.8.2r1/build/menu/menu-min.js&2.8.2r1/build/element/element-min.js&2.8.2r1/build/button/button-min.js&2.8.2r1/build/editor/editor-min.js', 'yui_editor', 'jquery'); // Stack::add('admin_header_javascript', 'http://yui.yahooapis.com/2.8.2r1/build/yahoo-dom-event/yahoo-dom-event.js', 'yui_dom', 'jquery'); // Stack::add('admin_header_javascript', 'http://yui.yahooapis.com/2.8.2r1/build/element/element-min.js ', 'yui_element', 'yui_dom'); // Stack::add('admin_header_javascript', 'http://yui.yahooapis.com/2.8.2r1/build/container/container_core-min.js', 'yui_container', 'yui_element'); // Stack::add('admin_header_javascript', 'http://yui.yahooapis.com/2.8.2r1/build/menu/menu-min.js', 'yui_menu', 'yui_container'); // Stack::add('admin_header_javascript', 'http://yui.yahooapis.com/2.8.2r1/build/button/button-min.js', 'yui_button', 'yui_container'); // Stack::add('admin_header_javascript', 'http://yui.yahooapis.com/2.8.2r1/build/editor/editor-min.js', 'yui_editor', 'yui_container'); Stack::add('admin_stylesheet', array('http://yui.yahooapis.com/2.8.2r1/build/assets/skins/sam/skin.css', 'screen'), 'yuieditor'); } public function action_add_yuieditor_template() { Stack::add('template_header_javascript', $this->get_url() . '/jwysiwyg/jquery.wysiwyg.js'); Stack::add('admin_stylesheet', array('http://yui.yahooapis.com/2.8.2r1/build/assets/skins/sam/skin.cs', 'screen'), 'yuieditor'); } public function action_admin_footer($theme) { if ( ( $theme->page == 'publish' ) && User::identify()->info->yuiwysiwyg_activate ) { echo <<<YUIWYSIWYG <style type="text/css">.editor-hidden { visibility: hidden; top: -9999px; left: -9999px; position: absolute; } textarea { border: 0; margin: 0; padding: 0; } .yui-skin-sam #page .container h2 { color: black; font-weight: bold; margin: 0; padding: .3em 1em; font-size: 100%; text-align: left; } .yui-skin-sam #page .container h3 { color: gray; font-size: 75%; margin: 1em 0 0; padding-bottom: 0; padding-left: .25em; text-align: left; } #content { border: 0px; margin: 0px; border-radius: 0px; -webkit-border-radius: 0px; -mox-border-radius: 0px; padding: 0px; height: 300px; } .yui-editor-panel { z-index: 100 !important; } </style> <script type="text/javascript"> $('label[for=content]').hide(); var myEditor; $(function(){ $('body').addClass('yui-skin-sam'); $('#content').attr('rows', 'auto'); var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event; var myConfig = { height: '300px', width: '100%', animate: true, dompath: true, focusAtStart: true }; var state = 'off'; YAHOO.log('Set state to off..', 'info', 'example'); YAHOO.log('Create the Editor..', 'info', 'example'); myEditor = new YAHOO.widget.Editor('content', myConfig); myEditor.on('toolbarLoaded', function() { var codeConfig = { type: 'push', label: 'Edit HTML Code', value: 'editcode' }; YAHOO.log('Create the (editcode) Button', 'info', 'example'); this.toolbar.addButtonToGroup(codeConfig, 'insertitem'); this.toolbar.on('editcodeClick', function() { var ta = this.get('element'), iframe = this.get('iframe').get('element'); if (state == 'on') { state = 'off'; this.toolbar.set('disabled', false); YAHOO.log('Show the Editor', 'info', 'example'); YAHOO.log('Inject the HTML from the textarea into the editor', 'info', 'example'); this.setEditorHTML(ta.value); if (!this.browser.ie) { this._setDesignMode('on'); } Dom.removeClass(iframe, 'editor-hidden'); Dom.addClass(ta, 'editor-hidden'); this.show(); this._focusWindow(); } else { state = 'on'; YAHOO.log('Show the Code Editor', 'info', 'example'); this.cleanHTML(); YAHOO.log('Save the Editors HTML', 'info', 'example'); Dom.addClass(iframe, 'editor-hidden'); Dom.removeClass(ta, 'editor-hidden'); this.toolbar.set('disabled', true); this.toolbar.getButtonByValue('editcode').set('disabled', false); this.toolbar.selectButton('editcode'); this.dompath.innerHTML = 'Editing HTML Code'; this.hide(); } return false; }, this, true); this.on('cleanHTML', function(ev) { YAHOO.log('cleanHTML callback fired..', 'info', 'example'); this.get('element').value = ev.html; }, this, true); this.on('afterRender', function() { var wrapper = this.get('editor_wrapper'); wrapper.appendChild(this.get('element')); this.setStyle('width', '100%'); this.setStyle('height', '100%'); this.setStyle('visibility', ''); this.setStyle('top', ''); this.setStyle('left', ''); this.setStyle('position', ''); this.addClass('editor-hidden'); }, this, true); }, myEditor, true); myEditor.render(); }); habari.editor = { insertSelection: function(value) { myEditor.execCommand('inserthtml', value); } } </script> YUIWYSIWYG; } } /** * Add the configuration to the user page **/ public function action_form_user( $form, $user ) { $fieldset = $form->append( 'wrapper', 'yuiwysiwyg', 'JWYSIWYG' ); $fieldset->class = 'container settings'; $fieldset->append( 'static', 'yuiwysiwyg', '<h2>YUI WYSIWYG</h2>' ); $activate = $fieldset->append( 'checkbox', 'yuiwysiwyg_activate', 'null:null', _t('Enable YUI WYSIWYG:'), 'optionscontrol_checkbox' ); $activate->class[] = 'item clear'; $activate->value = $user->info->yuiwysiwyg_activate; $form->move_before( $fieldset, $form->page_controls ); } /** * Save authentication fields **/ public function filter_adminhandler_post_user_fields( $fields ) { $fields[] = 'yuiwysiwyg_activate'; return $fields; } } ?> <file_sep><?php class fun_with_photos_plugin extends Plugin { /** * Major Props to Ringmaster for volunteering the code for this plugin. * */ function info() { return array( 'name' => 'Fun with Photos Plugin', 'version' => '1', 'url' => 'http://www.habari-fun.co.uk/fun-with-photos/', 'author' => '<NAME>', 'authorurl' => 'http://www.habari-fun.co.uk', 'license' => 'Apache License 2.0', 'description' => 'Adds a photo field to the publish page', ); } /** * Add fields to the publish page for photos * * @param FormUI $form The publish form * @param Post $post * @return array */ public function action_form_publish( $form, $post ) { if( $form->content_type->value == Post::type( 'entry' ) ) { $form->insert('content', 'text', 'photo', 'null:null', _t('Photo URL')); if(isset($post->info->photo)) { $form->photo->value = $post->info->photo; } $form->photo->template = 'admincontrol_text'; } } /** * Allow the media browser to insert photos into the photo field * * @param Theme $theme The current theme */ public function action_admin_header( $theme ) { if( $theme->page == 'publish' ) { echo <<< PHOTO_JS <script type="text/javascript"> $.extend(habari.media.output.image_jpeg, { use_as_photo: function(fileindex, fileobj) {set_photo(fileindex, fileobj);} }); $.extend(habari.media.output.image_png, { use_as_photo: function(fileindex, fileobj) {set_photo(fileindex, fileobj);} }); $.extend(habari.media.output.image_gif, { use_as_photo: function(fileindex, fileobj) {set_photo(fileindex, fileobj);} }); $.extend(habari.media.output.flickr, { use_as_photo: function(fileindex, fileobj) {set_photo(fileindex, fileobj);} }); function set_photo(fileindex, fileobj) { $('#photo').val(fileobj.url); } </script> PHOTO_JS; } } /** * Save the photo URL in the post's postinfo * * @param Post $post The post that is being saved * @param FormUI $form The submitted publish form */ public function action_publish_post($post, $form) { if( $form->content_type->value == Post::type( 'entry' ) ) { if($form->photo->value != '') { $post->info->photo = $form->photo->value; } } } } ?> <file_sep><?php $theme->display('header'); ?> <!-- page.single --> <div id="content" class="hfeed"> <div id="page-<?php echo $post->slug; ?>" class="hentry page <?php echo $post->statusname , ' ' , $post->tags_class; ?>"> <div class="entry-head"> <h1 class="entry-title"><a href="<?php echo $post->permalink; ?>" title="<?php echo strip_tags($post->title); ?>" rel="bookmark"><?php echo $post->title_out; ?></a></h1> <ul class="entry-meta"> <li class="comments-link"><a href="<?php echo $post->permalink; ?>#comments" title="<?php _e('Comments to this post', 'binadamu') ?>"><?php printf(_n('%1$d Comment', '%1$d Comments', $post->comments->approved->count, 'binadamu'), $post->comments->approved->count); ?></a></li> <?php if ($loggedin) { ?> <li class="entry-edit"><a href="<?php echo $post->editlink; ?>" title="<?php _e('Edit post', 'binadamu') ?>"><?php _e('Edit', 'binadamu') ?></a></li> <?php } ?> </ul> </div> <div class="entry-content"> <?php echo $post->content_out; ?> </div> </div> <?php $theme->display('comments'); ?> </div> <hr /> <!-- /page.single --> <?php $theme->display('sidebar'); ?> <?php $theme->display('footer'); ?> <file_sep> <h3 id="respond" class="comment_title">Leave a Reply</h3> <?php if ( Session::has_errors() ) { Session::messages_out(); } ?> <form action="<?php URL::out( 'submit_feedback', array( 'id' => $post->id ) ); ?>" method="post" id="commentform"> <div id="comment-personaldetails"> <p> <input type="text" name="name" id="name" value="<?php echo $commenter_name; ?>" size="22" tabindex="1"> <label for="name">Name</label> </p> <p> <input type="text" name="email" id="email" value="<?php echo $commenter_email; ?>" size="22" tabindex="2"> <label for="email">Mail (will not be published)</label> </p> <p> <input type="text" name="url" id="url" value="<?php echo $commenter_url; ?>" size="22" tabindex="3"> <label for="url">Website</label> </p> </div> <p> <textarea name="content" id="comment_content" cols="100" rows="10" tabindex="4"> <?php if ( isset( $details['content'] ) ) { echo $details['content']; } ?> </textarea> </p> <p> <input name="submit" type="submit" id="submit" tabindex="5" value="Submit"> </p> <div class="clear"></div> </form> <file_sep><?php class extracontent extends Plugin { /** * Add additional controls to the publish page tab * * @param FormUI $form The form that is used on the publish page * @param Post $post The post being edited **/ public function action_form_publish( $form, $post ) { switch( $post->content_type ) { case Post::type( 'entry' ): $extra = $form->append( 'textarea', 'extra_textarea', 'null:null', _t( 'Extra', 'extra_content' ) ); $extra->value = $post->info->extra; $extra->class[] = 'resizable'; $extra->rows = 3; $extra->template = 'admincontrol_textarea'; $form->move_after($form->extra_textarea, $form->content); break; default: return; } } /** * Modify a post before it is updated * * @param Post $post The post being saved, by reference * @param FormUI $form The form that was submitted on the publish page */ public function action_publish_post($post, $form) { switch( $post->content_type ) { case Post::type( 'entry' ): $post->info->extra = $form->extra_textarea->value; break; default: return; } } } ?> <file_sep><?php class GoogleAnalytics extends Plugin { public function info() { return array( 'url' => 'http://iamgraham.net/plugins', 'name' => 'GoogleAnalytics', 'description' => 'Automatically adds Google Analytics code to the bottom of your webpage.', 'license' => 'Apache License 2.0', 'author' => '<NAME>', 'authorurl' => 'http://iamgraham.net/', 'version' => '0.5.2' ); } public function action_init() { $this->add_rule('"ga.js"', 'serve_ga'); $this->add_rule('"gaextra.js"', 'serve_gaextra'); } public function action_plugin_act_serve_ga() { if (Cache::has('ga.js')) { $js = Cache::get('ga.js'); } else { $js = RemoteRequest::get_contents('http://www.google-analytics.com/ga.js'); Cache::set('ga.js', $js, 86400); // cache for 1 day } // Clean the output buffer, so we can output from the header/scratch ob_clean(); header('Content-Type: application/javascript'); echo $js; } public function action_plugin_act_serve_gaextra() { ob_clean(); header('Content-Type: application/javascript'); include 'googleanalytics.js.php'; } private function detect_ssl() { if ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1 || $_SERVER['SERVER_PORT'] == 443) { return true; } return false; } public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()) { $actions[] = _t('Configure'); } return $actions; } public function action_plugin_ui($plugin_id, $action) { if ( $plugin_id == $this->plugin_id() ) { switch ($action) { case _t('Configure'): $form = new FormUI(strtolower(get_class($this))); $form->append('text', 'clientcode', 'googleanalytics__clientcode', _t('Analytics Client Code')); $form->append('checkbox', 'loggedintoo', 'googleanalytics__loggedintoo', _t('Track logged-in users too')); $form->append('checkbox', 'trackoutgoing', 'googleanalytics__trackoutgoing', _t('Track outgoing links')); $form->append('checkbox', 'trackmailto', 'googleanalytics__trackmailto', _t('Track mailto links')); $form->append('checkbox', 'trackfiles', 'googleanalytics__trackfiles', _t('Track download links')); $form->append('textarea', 'track_extensions', 'googleanalytics__trackfiles_extensions', _t('File extensions to track (comma separated)')); $form->append('checkbox', 'cache', 'googleanalytics__cache', _t('Cache tracking code file locally')); $form->append('submit', 'save', 'Save'); $form->out(); break; } } } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'GoogleAnalytics', '7e57a660-3bd1-11dd-ae16-0800200c9a66', $this->info->version ); } public function theme_footer() { if (URL::get_matched_rule()->entire_match == 'user/login') { // Login page; don't display return; } $clientcode = Options::get('googleanalytics__clientcode'); // get the url for the main Google Analytics code if (Options::get('googleanalytics__cache')) { $ga_url = Site::get_url('habari') . '/ga.js'; } else { $ga_url = (self::detect_ssl()) ? 'https://ssl.google-analytics.com/ga.js' : 'http://www.google-analytics.com/ga.js'; } // only actually track the page if we're not logged in, or we're told to always track $do_tracking = (!User::identify()->loggedin || Options::get('googleanalytics__loggedintoo')); $ga_extra_url = ($do_tracking) ? '<script src="' . Site::get_url('habari') . '/gaextra.js' . '" type="text/javascript"></script>' : ''; $track_page = ($do_tracking) ? 'pageTracker._trackPageview();' : ''; echo <<<ANALYTICS {$ga_extra_url} <script src="{$ga_url}" type="text/javascript"></script> <script type="text/javascript"> <!--//--><![CDATA[//><!-- try {var pageTracker = _gat._getTracker("{$clientcode}");{$track_page}} catch(e) {} //--><!]]> </script> ANALYTICS; } } ?> <file_sep><?php class TwitterComments extends Plugin { /** * Remove fields, replace a single one for twitter username * ... * @return the form **/ public function action_form_comment( $form, $context = 'public' ) { $form->append( 'hidden', 'twitter_comment' )->value = true; // add the twitter username $form->append( 'text', 'twitter_username', 'null:null', _t( 'Twitter Username', 'twittercomments' ) )->add_validator( 'validate_required', _t( 'Twitter username is required', 'twittercomments' ) )->tabindex = 1; $form->move_before( $form->twitter_username, $form->cf_commenter ); // remove the existing fields $form->cf_commenter->remove(); $form->cf_email->remove(); $form->cf_url->remove(); return $form; } /** * Populate the fields based on the twitter username * ... * @return the form **/ public function action_comment_form_submit ( $form ) { if( $form->twitter_comment->value ) { $form->append( 'hidden', 'cf_commenter' )->value = $form->twitter_username->value; $form->append( 'hidden', 'cf_email' )->value = '@' . $form->twitter_username->value; $form->append( 'hidden', 'cf_url' )->value = 'http://twitter.com/' . $form->twitter_username->value; } return $form; } /** * Add commentinfo for only these twitter comments * * @param Comment The comment that will be processed before storing it in the database. * @param Handler vars (not used) * @param Additional form fields * @return Comment The comment result to store. **/ function action_comment_accepted ( $comment, $handler_vars, $extra ) { if ( isset( $extra[ 'twitter_comment' ] ) ) { $comment->info->twitter_comment = true; } return $comment; } /** * Change priority to run after other plugins modifying the form, * under the assumption they retain the default priority of 8 **/ function set_priorities() { return array( 'action_form_comment' => 10, ); } /** * Add update beacon support **/ public function action_update_check() { Update::add( $this->info->name, $this->info->guid, $this->info->version ); } } ?> <file_sep><?php /** * GoogleCodePrettify Class * **/ class GoogleCodePrettify extends Plugin { private $config = array(); private $class_name = ''; private static function default_options() { return array ( 'color_scheme' => 'Google' ); } public function info() { return array( 'name' => 'Google Code Prettify', 'version' => '0.4', 'url' => 'http://code.google.com/p/bcse/wiki/GoogleCodePrettify', 'author' => '<NAME>', 'authorurl' => 'http://blog.bcse.info/', 'license' => 'Apache License 2.0', 'description' => _t('Allows syntax highlighting of source code snippets.', $this->class_name) ); } /** * Add update beacon support **/ public function action_update_check() { Update::add('Google Code Prettify', 'dc7d7984-ff24-46ea-b37a-1c26a6f17938', $this->info->version); } /** * On plugin init, add the template included with this plugin to the available templates in the theme */ public function action_init() { $this->class_name = strtolower(get_class($this)); foreach (self::default_options() as $name => $value) { $this->config[$name] = Options::get($this->class_name . '__' . $name); } $this->load_text_domain($this->class_name); } /** * On plugin activation, set the default options */ public function action_plugin_activation($file) { if (realpath($file) === __FILE__) { $this->class_name = strtolower(get_class($this)); foreach (self::default_options() as $name => $value) { $current_value = Options::get($this->class_name . '__' . $name); if (is_null($current_value)) { Options::set($this->class_name . '__' . $name, $value); } } } } /** * Add actions to the plugin page for this plugin * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id **/ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id === $this->plugin_id()) { $actions[] = _t('Configure', $this->class_name); } return $actions; } /** * Respond to the user selecting an action on the plugin page * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook **/ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id === $this->plugin_id()) { switch ($action) { case _t('Configure', $this->class_name): $ui = new FormUI($this->class_name); $ui->append('select', 'color_scheme', 'option:' . $this->class_name . '__color_scheme', _t('Color Scheme', $this->class_name), self::get_color_schemes()); // When the form is successfully completed, call $this->updated_config() $ui->append('submit', 'save', _t('Save', $this->class_name)); $ui->set_option('success_message', _t('Options saved', $this->class_name)); $ui->out(); break; } } } private static function get_color_schemes() { $color_scheme_dir = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'color-schemes' . DIRECTORY_SEPARATOR; $files = Utils::glob($color_scheme_dir . '*.css'); $color_schemes = array(); foreach ($files as $color_scheme) { $name = basename($color_scheme, '.css'); $color_schemes[$name] = $name; } return $color_schemes; } /** * Returns true if plugin config form values defined in action_plugin_ui should be stored in options by Habari * @return bool True if options should be stored **/ public function updated_config($ui) { return true; } function theme_header() { Stack::add('template_stylesheet', array($this->get_url(TRUE) . 'color-schemes/' . $this->config['color_scheme'] . '.css', 'all'), $this->class_name); } function theme_footer() { Stack::add('template_footer_javascript', $this->get_url(TRUE) . 'prettify.js', $this->class_name); } } ?><file_sep><?php /** * Options Manager Plugin * * Lets you manage all Habari options. This includes viewing, editing and * deleting. * * Warning: YOU CAN SERIOUSLY DAMAGE YOUR HABARI SETUP! * Warning: USE YOUR POWERS WISELY! * * So be sure you know what you're doing, especially when dealing with * core options. This plugin only guesses if a plugin is from core or * not, so also keep that in mind. In other words, this plugin may be * lying to you, and accidentally allow you to do very bad things. * * Thanks to the CronManager plugin for portions of this code base. * * @todo allow serialized (type=1) options to be viewed in a nice way * @todo allow serialized (type=1) options to be edited in a nice way * @todo better deal with log/session notices * @todo clean up hacked code, and find/fix non-habari coding standards * @todo determine proper _t() usage, and start passing domain one day * @todo add "import all default options, and/or delete the rest" feature * @todo convince a Habari veteran to review this questionable code * * @version $Id$ **/ class OptionsManager extends Plugin { public $class_name = ''; public $opts_core = array(); public $opts_local = array(); public $opts_count_total = 0; public $opts_count_inactive = 0; /** * Action: sets up a get/post alias * * @return array the aliases */ public function alias() { return array( 'action_admin_theme_get_options_edit' => 'action_admin_theme_post_options_edit', ); } /** * Action: Plugin Configure * * Sets up the plugin actions * * - Creates 'Configure' option to configure the plugin * - Creates 'View Options' tab, to view options * * @return array the actions */ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t( 'View Options' ); $actions[] = _t( 'Configure' ); } return $actions; } /** * action: add custom css for this plugin * * @access public * @return void */ public function action_admin_header() { Stack::add( 'admin_stylesheet', array( $this->get_url() . '/css/view.css', 'all') ); } /** * Action: plugin user interface * * Sets up main global user interface for this plugin * * - Creates 'Configure' option to configure the plugin * - Creates 'View Options' tab, to view options * * @return void */ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id === $this->plugin_id() ) { switch ( $action ) { case _t( 'View Options' ): Utils::redirect( URL::get( 'admin', array( 'page'=>'options_view' ) ), TRUE ); break; case _t( 'Configure' ): $ui = new FormUI($this->class_name . '_configure'); $ui->append( 'checkbox', 'allow_delete_core', $this->class_name . '__allow_delete_core', _t( 'Allow core options to be deleted?' ) ); $ui->append( 'checkbox', 'allow_delete_other', $this->class_name . '__allow_delete_other', _t( 'Allow non-core options to be deleted?' ) ); $ui->append( 'submit', 'save', _t( 'Save' ) ); $ui->set_option( 'success_message', _t( 'Options saved' ) ); $ui->out(); break; } } } /** * Action: plugin activation * * Sets up this plugin when activated, including: * * - Creates the ACL token for admin users * - Creates plugin options with initial values of 0 (off) * * @return void */ public function action_plugin_activation( $file ) { if ( $file == str_replace( '\\','/', $this->get_file() ) ) { ACL::create_token( 'manage_options', _t( 'Manage Options' ), 'Options', FALSE ); $group = UserGroup::get_by_name( 'admin' ); $group->grant( 'manage_options' ); } Options::set( strtolower(get_class($this)) . '__allow_delete_core', 0); Options::set( strtolower(get_class($this)) . '__allow_delete_other', 0); } /** * Action: plugin deactivation * * Cleans up after this plugin when deactivated, including: * * - Removes ACL token * - Removes plugin options * * @return void */ public function action_plugin_deactivation( $file ) { if ( $file == str_replace( '\\','/', $this->get_file() ) ) { ACL::destroy_token( 'manage_options' ); } Options::delete( $this->class_name . '__allow_delete_core' ); Options::delete( $this->class_name . '__allow_delete_other' ); } /** * Initializes the action * * Executed upon script execution, and initiates several conditions and variables including: * * - Templates (options_view and options_edit) * - $this->class_name : lowercase * - $this->opts_core : a hard coded list of habari core options. Likely NOT complete * - $this->opts_local : the options created by this plugin * * @return void */ public function action_init() { $this->add_template( 'options_view', dirname( $this->get_file() ) . '/options-view.php' ); $this->add_template( 'options_edit', dirname( $this->get_file() ) . '/options-edit.php' ); $this->class_name = strtolower(get_class($this)); // @todo better way to determine this? most likely $this->opts_core = array( '235381938', 'about', 'active_plugins', 'atom_entries', 'base_url', 'cron_running', 'comments_require_id', 'dash_available_modules', 'dateformat', 'db_version', 'db_upgrading', 'failed_plugins', 'GUID', 'import_errors', 'installed', 'import_errors', 'locale', 'log_backtraces', 'next_cron', 'pagination', 'plugins_present', 'system_locale', 'tagline', 'title', 'timeformat', 'timezone', 'theme_name', 'theme_dir', 'undelete__style', ); // Note: This strips the group prefix, so returns allow_delete_core and allow_delete_other $this->opts_local = Options::get_group( $this->class_name ); } /** * Admin token filter * * Filters for the required admin token of manage_options * * @param array $require_any * @param string $page * @return array or null */ public function filter_admin_access_tokens( array $require_any, $page ) { switch ($page) { case 'options_view': case 'options_edit': $require_any = array('manage_options', TRUE); break; } return $require_any; } /** * Admin control for view post * * @param AdminHandler $handler * @param Theme $theme * @return void */ public function action_admin_theme_post_options_view( AdminHandler $handler, Theme $theme ) { // saving is handled by FormUI $this->action_admin_theme_get_options_view($handler, $theme); $theme->display('options_view'); } /** * Admin control for view get * * Processes actions (like edit, delete) from the options view * * @param AdminHandler $handler * @param Theme $theme * @return void */ public function action_admin_theme_get_options_view( AdminHandler $handler, Theme $theme ) { $vars = $handler->handler_vars->getArrayCopy(); $theme = $this->create_add_option_form_tab( $theme ); if( isset($vars['action']) ) { if (empty($vars['option_name'])) { Session::error(_t( 'There is no option name set, not sure how you got here.') ); $vars['action'] = 'nothing'; } else { $info = $this->get_option_from_name( $vars['option_name'] ); if ($info === FALSE) { Session::error(_t( 'The %s option does not exist, so it cannot be acted upon', array($vars['option_name']))); $vars['action'] = 'nothing'; } } switch($vars['action']) { case 'delete': if ( $this->opts_local['allow_delete_core'] !== '1' && $info['genre'] === 'core' ) { Session::notice(_t( '%s is a core option, configuration disallows its deletion', array($vars['option_name']))); break; } if ( $this->opts_local['allow_delete_other'] !== '1' && $info['genre'] !== 'core' ) { Session::notice(_t( '%s is configured to not be deleted', array($vars['option_name'])), $this->class_name); break; } Options::delete ( $vars['option_name'] ); $success = Options::get ( $vars['option_name']); if ( is_null( $success ) ) { Session::notice( _t( 'The %s option was deleted', array($vars['option_name'])), $this->class_name ); EventLog::log( _t( 'The %s option was deleted', array($vars['option_name'])), 'notice', 'plugin' ); } else { Session::error( _t( 'I was unable to delete this option: %s', array($vars['option_name']) ) ); } break; case 'delete_group': Session::notice( _t( 'Group removal not implemented yet' ) ); break; case 'edit_group': Session::notice( _t( 'Group editing not implemented yet' ) ); break; case 'nothing': break; } } $theme->options = $this->get_options_info(); $theme->opts_local = $this->opts_local; $theme->opts_count_inactive = $this->opts_count_inactive; $theme->opts_count_total = $this->opts_count_total; } /** * Admin control for edit get * * @param AdminHandler $handler * @param Theme $theme * @return void */ public function action_admin_theme_get_options_edit( AdminHandler $handler, Theme $theme ) { $option = $this->get_option_from_name( $handler->handler_vars['option_name'] ); $theme->option = $option; $form = new FormUI( 'options_edit' ); $current_option_name = $form->append( 'hidden', 'current_option_name', 'null:null' ); $current_option_name->value = $option['name']; $name = $form->append( 'text', 'option_name', 'null:null', _t( 'Name' ), 'optionscontrol_text' ); $name->class = 'item clear'; $name->value = $option['name']; $name->helptext = _t( 'A unique name for option.' ); $value = $form->append( 'text', 'option_value', 'null:null', _t( 'Value' ), 'optionscontrol_text' ); $value->class = 'item clear'; $value->value = $option['value']; $value->helptext = _t( 'The value of the new option' ); $type = $form->append( 'text', 'option_type', 'null:null', _t( 'Type' ), 'optionscontrol_text' ); $type->class = 'item clear'; $type->value = $option['type']; $type->helptext = _t( 'The type of this option, odds are you do not want to touch this. In fact, changing will not do anything yet.' ); $form->append( 'submit', 'save', _t( 'Save' ) ); $form->on_success( array( $this, 'formui_submit_edit' ) ); $theme->form = $form->get(); } /** * Admin control for edit post * * @param AdminHandler $handler * @param Theme $theme * @return void */ public function action_admin_theme_post_options_edit( AdminHandler $handler, Theme $theme ) { // saving is handled by FormUI $option = $this->get_option_from_name( $handler->handler_vars['option_name'] ); $theme->option = $option; $theme->display( 'options_edit' ); } /** * Processes the 'option add' form * * @param FormUI $form * @return bool TRUE on success, FALSE on failure */ public function formui_submit_add ( FormUI $form ) { if ( strlen( $form->option_name->value ) < 1 ) { Session::error( _t( 'The "option_name" requires a value' ) ); return FALSE; } if ( strlen( $form->option_value->value ) < 1 ) { Session::error( _t( 'The "option_value" requires a value' ) ); return FALSE; } $message_success = 'The "%s" option was added'; if ( Options::get( $form->option_name->value ) !== NULL ) { Session::notice( _t( 'The "%s" option exists already, so I will attempt to overwrite', array( $form->option_name->value ) ) ); $message_success = 'The "%s" option was updated'; } Options::set ( $form->option_name->value, $form->option_value->value ); $success = Options::get ( $form->option_name->value ); if (is_null($success)) { Session::error( _t( 'The "%s" option failed to add', array( $form->option_name->value ) ) ); } else { Session::notice( _t( $message_success, array( $form->option_name->value ) ) ); EventLog::log( _t( $message_success, array( $form->option_name->value ) ), 'notice', 'plugin' ); } Utils::redirect( URL::get( 'admin', array( 'page'=>'options_view' ) ), TRUE ); return TRUE; } /** * Processes the 'option edit' form * * @param FormUI $form * @return bool TRUE on success, FALSE on failure */ public function formui_submit_edit( FormUI $form ) { if ( strlen( $form->option_name->value ) < 1 ) { Session::error( _t( 'The "option_name" requires a value' ) ); return FALSE; } if ( strlen( $form->option_value->value ) < 1 ) { Session::error( _t( 'The "option_value" requires a value' ) ); return FALSE; } if ( strlen( $form->current_option_name->value ) < 1 ) { Session::error( _t( 'The current/old "option_name" is missing' ) ); return FALSE; } $_opt_curr = $this->get_option_from_name( $form->current_option_name->value ); Options::set ( $form->option_name->value, $form->option_value->value ); // @todo okay? what if option type = serialized? research later $success = Options::get ( $form->option_name->value ); if ( is_null( $success ) || $success !== $form->option_value->value ) { Session::error( _t( 'The "%s" option failed to edit', array( $form->option_name->value ) ) ); } else { // The name was changed, so delete the old, depending on if we're allowed if ($form->current_option_name->value !== $form->option_name->value) { if ($this->is_option_genre_delete_allowed( $_opt_curr['genre'] ) ) { Options::delete($form->current_option_name->value); $message = 'The "%s" option name was changed and renamed to "%s"'; } else { $message = 'The "%s" option name could not be renamed, but a new option named "%s" was added'; } Session::notice( _t( $message, array( $form->current_option_name->value, $form->option_name->value ) ) ); EventLog::log( _t( $message, array( $form->current_option_name->value, $form->option_name->value ) ), 'notice', 'plugin' ); } else { Session::notice( _t( 'The "%s" option was edited to %s', array( $form->option_name->value, $form->option_value->value ) ) ); EventLog::log( _t( 'The %s option was edited', array( $form->option_name->value ) ), 'notice', 'plugin' ); } } Utils::redirect( URL::get( 'admin', array( 'page'=>'options_view' )), TRUE ); return TRUE; } /** * Creates (attaches) the 'add new option' form/tab * @todo Determine if this is a hack :) * * @param $theme The theme being attached to * @return Theme The modified Theme object */ public function create_add_option_form_tab( Theme $theme ) { $form = new FormUI('options-view-new'); $form->set_option( 'form_action', URL::get('admin', 'page=options_view' ) ); $form->class[] = 'form comment'; $tabs = $form->append( 'tabs', 'publish_controls' ); $new = $tabs->append( 'fieldset', 'settings', _t( 'Add a new option' ) ); $action = $new->append( 'hidden', 'action', 'null:null' ); $action->value = 'add'; $name = $new->append( 'text', 'option_name', 'null:null', _t( 'Name'), 'tabcontrol_text' ); $name->value = ''; $name->helptext = _t( 'Name of the new option' ); $value = $new->append( 'text', 'option_value', 'null:null', _t( 'Value' ), 'tabcontrol_text' ); $value->value = ''; $value->helptext = _t( 'Value of the new option' ); $new->append( 'submit', 'save', _t('Save' ) ); $form->on_success( array( $this, 'formui_submit_add' ) ); $theme->form = $form->get(); return $theme; } /** * Gets option information from a name * * @param $name The options name (e.g., 'theme_name') * @return mixed Returns the options information (array) on success, or FALSE on error */ public function get_option_from_name( $name ) { $options = $this->get_options_info(); if ( !empty( $options[$name] ) ) { return $options[$name]; } return FALSE; } /** * Gets all Habari option information, and determines other information about these options * * Returned array equals: array('name','value','type','genre','plugin_name','active','delete_allowed'); * It also sets: * $this->opts_count_total with the number of found options * $this->opts_count_inactive with the number of inactive options * * @return array An array of options [with associated info] on success, or FALSE on failure */ public function get_options_info() { $raw_options = DB::get_results( 'SELECT name, value, type FROM {options}', array(), 'QueryRecord' ); $actives = Options::get('active_plugins'); $actives = array_change_key_case($actives, CASE_LOWER); //$deactives = $this->get_deactives(); if (!$raw_options) { return FALSE; } $this->opts_count_inactive = 0; $options = array(); foreach ($raw_options as $raw_option) { $_name = $raw_option->name; $options[$_name] = array( 'name' => $_name, 'type' => $raw_option->type, 'value' => $raw_option->value, ); if ($raw_option->type) { $options[$_name]['value_unserialized'] = unserialize( $raw_option->value ); } $active = 'no'; // Guessing theme options begin with themes name followed by '_' if ($theme = $this->is_theme_option($_name)) { $genre = 'theme'; $plugin_name = $theme; if (Options::get('theme_name') === $theme || (0 === strpos( Options::get('theme_dir') . '_', $theme))) { $active = 'yes'; } else { $active = 'no'; } // Guessing that only plugins contain '__' } elseif (FALSE === strpos($_name, '__')) { $active = 'unknown'; if (in_array($_name, $this->opts_core)) { $genre = 'core'; $plugin_name = 'core'; } else { $genre = 'unknown'; $plugin_name = 'unknown'; } // So, these contain '__', so I guess are from plugins } else { // @todo Obviously only a guess, consider better checks $plugin_name = substr($_name, 0, strpos($_name, '__')); $genre = 'plugin'; // @todo Check if known deactive instead of just guessing if (isset($actives[$plugin_name])) { $active = 'yes'; } } if ($active === 'no') { $this->opts_count_inactive++; } $options[$_name]['active'] = $active; $options[$_name]['genre'] = $genre; $options[$_name]['plugin_name'] = $plugin_name; $options[$_name]['delete_allowed'] = $this->is_option_genre_delete_allowed($genre); } $this->opts_count_total = count($raw_options); if ($this->opts_count_total > 0) { return $options; } return FALSE; } /** * Gets the deactived plugins and themes * * @todo This makes guesses and is not yet used. * * @return array An array of deactivated plugins, with an empty array() on failure */ public function get_deactives() { $active_plugins = Plugins::get_active(); $deactive_plugins = array(); foreach ( Plugins::list_all() as $fname => $fpath ) { $id = Plugins::id_from_file( $fpath ); $info = Plugins::load_info ( $fpath ); if (is_null($info) || is_null($id)) { continue; } //@todo $info differs from get_option_from_name() output, but would be inefficient to use for 300+ plugins if (empty($active_plugins[$id])) { $deactive_plugins[$id] = $info; } } return $deactive_plugins; } /** * Determines if the option can be deleted, by using the appropriate configure * directives. * * @param $genre will likely be either core or something else * @return bool */ public function is_option_genre_delete_allowed( $genre ) { if ( $genre === 'core' ) { return (bool) $this->opts_local['allow_delete_core']; } else { return (bool) $this->opts_local['allow_delete_other']; } return FALSE; } /** * Determines if an option is for a theme * * @param $option Name of the option being checked * @return mixed Returns the theme name on success, or FALSE if not found */ public function is_theme_option( $option ) { if ( $all_themes = Themes::get_all() ) { foreach ($all_themes as $theme_name => $theme_file) { if (0 === strpos($option, strtolower($theme_name) . '_')) { return $theme_name; } } } return FALSE; } } ?> <file_sep><?php class ThreadedComment extends Plugin { const MAIL_FILENAME = 'threaded_comment_mail.php'; const SUBJECT_DEL = '====== Subject ======'; const TEXT_DEL = '====== Text ======'; const HTML_DEL = '====== HTML ======'; const END_DEL = '====== End ======'; public function action_plugin_activation( $file ) { if ( Plugins::id_from_file( $file ) == Plugins::id_from_file( __FILE__ ) ) { EventLog::register_type( 'ThreadedComment' ); } } public function action_plugin_deactivation( $file ) { if ( Plugins::id_from_file( $file ) == Plugins::id_from_file( __FILE__ ) ) { EventLog::unregister_type( 'ThreadedComment' ); } } /* Add threaded_comment.js to header */ public function action_init() { Stack::add( 'template_header_javascript', $this->get_url( true ) . 'threaded_comment.js', 'threaded_comment' ); } public function configure() { $form = new FormUI( 'threaded_comment' ); $depth = $form->append( 'text', 'threaded_depth', 'threaded_comment__depth', _t( 'Max depth of thread:' ) ); $depth->add_validator( 'validate_regex', '/^[0-9]*$/', _t( 'Please enter a valid positive integer.' ) ); $form->append( 'submit', 'save', _t( 'Save' ) ); $form->set_option( 'success_message', _t( 'Configuration saved' ) ); return $form; } /* Add comment parent field to comment */ public function action_comment_accepted( $comment, $handlervars, $extra ) { if( isset( $extra['cf_commentparent'] ) && $extra['cf_commentparent'] != '-1' ) { $comment->info->comment_parent = $extra['cf_commentparent']; } if( isset( $extra['cf_emailnotify'] ) ) { $comment->info->email_notify = 1; } } /* Adds the subscribe button to the comment form * */ public function action_form_comment( $form, $post, $context ) { $form->insert( $form->cf_submit, 'checkbox', 'cf_emailnotify', 'null:null', _t( 'Receive email notification if someone replies to my comment', 'formcontrol_checkbox' ) ); $form->cf_emailnotify->id = 'cf_emailnotify'; $form->append( 'static', 'cf_cancel_reply', '<p id="cancel_reply" style="display:none;" ><a href="javascript:void(0)" onclick="movecfm(null,0,1,null);" style="color:red;">' . _t( 'Cancel Reply' ) . "</a></p>\n" ); $form->append( 'hidden', 'cf_commentparent', 'null:null' ); $form->cf_commentparent->id = 'cf_commentparent'; $form->cf_commentparent->value = -1; } /* Email notify to subscribed user */ public function action_comment_insert_after( $comment ) { if( ( $comment->type != Comment::COMMENT ) || ( $comment->status == Comment::STATUS_SPAM ) ) { return; } $post = Post::get( array( 'id' => $comment->post_id ) ); $author = User::get_by_id( $post->user_id ); $c = $comment; $sent = array(); $sent[] = $author->email; $sent[] = $comment->email; while( isset( $c->info->comment_parent ) ) { $cc = Comment::get( $c->info->comment_parent ); if( isset( $cc->info->email_notify ) && $cc->info->email_notify == 1 ) { if( !in_array( $cc->email, $sent ) ) { $sent[] = $cc->email; $this->mail_notify( $cc->email, $cc, $comment ); } } $c = $cc; } } public function action_admin_moderate_comments( $action, $comments ) { if( 'approved' == $action ) { foreach( $comments as $c ) { $this->action_comment_insert_after( $c ); } } } public function filter_post_threadedComments( $out, $post ) { $ret = null; if( $post->comments->moderated->count ) { $ret = array(); $comments = $post->comments->moderated->getArrayCopy(); $num = count( $comments ); while( $num-- > 0) { $c = array_pop( $comments ); if( isset( $c->info->comment_parent ) ) { $p = $this->get_comment_by_id( $comments, $c->info->comment_parent ); if( $p != null ) { if( !isset( $p->children ) ) { $children = array(); } else { $children = $p->children; } array_unshift( $children, $c ); $p->children = $children; continue; } } array_unshift( $ret, $c ); } } return $ret; } public function action_add_template_vars( $theme, $handler_vars ) { if( !$theme->template_engine->assigned( 'commentThreadMaxDepth' ) ) { $depth = Options::get( 'threaded_comment__depth', 5 ); // default value is 5. if( ( isset( $theme->user ) && isset( $theme->post ) ) && ( $theme->user->id == $theme->post->user_id ) ) { $depth++; } $theme->assign( 'commentThreadMaxDepth', $depth ); } } public function filter_rewrite_rules( $db_rules ) { $db_rules[]= RewriteRule::create_url_rule( '"tc_unsubscribe"', 'ThreadedComment', 'unsubscribe' ); return $db_rules; } public function action_handler_unsubscribe( $handler_vars ) { $key = $handler_vars['id']; if( $key != null ) { $key_text = base64_decode( $key ); $pieces = explode( ',', $key_text ); if( count( $pieces ) == 3) { if( Utils::crypt( $pieces[0] . $pieces[1] ) ) { $comments = Comments::get( array( 'id' => $pieces[1], 'email' => $pieces[0] ) ); if( count( $comments ) == 1 ) { unset( $comments[0]->info->email_notify ); die( 'Unsubscribe successfully' ); } } } } die( 'Invalid Request' ); } private function get_comment_by_id( $comments, $id ) { $ret = null; $begin = 0; $end = count( $comments) - 1; while( $begin <= $end ) { $curr = floor( ( $begin + $end ) / 2 ); if( $comments[$curr]->id == $id ) { $ret = $comments[$curr]; break; } else if( $comments[$curr]->id > $id ) { $end = $curr - 1; } else { $begin = $curr + 1; } }; return $ret; } private function mail_notify( $email, $comment, $reply ) { EventLog::log( 'Email notify ' . $email, 'info', 'ThreadedComment', 'ThreadedComment' ); $post = Post::get( array( 'id' => $comment->post_id ) ); $author = User::get_by_id( $post->user_id ); $mail_data = $this->get_mail_data( $comment, $reply ); $boundary = md5( time() ); $headers = array( 'MIME-Version: 1.0', "Content-type: multipart/alternative; boundary=\"$boundary\"", 'From: ' . $this->mh_utf8( Options::get( 'title' ) ) . ' <no-reply@' . Site::get_url( 'hostname' ) . '>', ); $message = "--$boundary" . PHP_EOL; $message .= 'Content-Type: text/plain; charset=UTF-8' . PHP_EOL; $message .= 'Content-Transfer-Encoding: 8bit' . PHP_EOL . PHP_EOL; $message .= $mail_data['text']; $message .= PHP_EOL . "--$boundary" . PHP_EOL; $message .= 'Content-Type: text/html; charset=UTF-8' . PHP_EOL; $message .= 'Content-Transfer-Encoding: 8bit' . PHP_EOL . PHP_EOL; $message .= $mail_data['html']; $message .= PHP_EOL . "--$boundary--" . PHP_EOL; mail( $email, $this->mh_utf8( $mail_data['subject'] ), $message, implode( PHP_EOL, $headers ) ); } private function get_mail_data( $comment, $reply) { $ret = array(); $eol_tag = '--EOL--'; $fp = $this->find_file( self::MAIL_FILENAME); $post = Post::get( array( 'id' => $comment->post_id ) ); /* prepare for vars used in template file */ $site_name = Options::get( 'title' ); $site_link = Site::get_url( 'habari' ); $post_title = $post->title; $post_link = $post->permalink; $comment_id = $comment->id; $comment_author = $comment->name; $comment_content = str_replace( "\r\n", "\n", $comment->content ); $comment_content = str_replace( "\n", $eol_tag, $comment_content ); $reply_id = $reply->id; $reply_author = $reply->name; $reply_content = str_replace( "\r\n", "\n", $reply->content ); $reply_content = str_replace( "\n", $eol_tag, $reply_content ); $unsubscribe_link = $site_link . '/tc_unsubscribe?id=' . base64_encode( $comment->email. ',' . $comment_id . ',' . Utils::crypt( $comment->email . $comment_id ) ); ob_start(); include( $fp ); $cont = ob_get_clean(); $pieces = explode( self::END_DEL, $cont); $ret['subject'] = substr( $pieces[0], strpos( $pieces[0], self::SUBJECT_DEL ) + strlen( self::SUBJECT_DEL . PHP_EOL ) ); $ret['text'] = substr( $pieces[1], strpos( $pieces[1], self::TEXT_DEL ) + strlen( self::TEXT_DEL . PHP_EOL ) ); $ret['text'] = str_replace( $eol_tag, PHP_EOL, $ret['text'] ); $ret['html'] = substr( $pieces[2], strpos( $pieces[2], self::HTML_DEL ) + strlen( self::HTML_DEL . PHP_EOL ) ); $ret['html'] = str_replace( $eol_tag, '<br />' . PHP_EOL, $ret['html'] ); return $ret; } private function mh_utf8( $str ) { return '=?UTF-8?B?' . base64_encode( $str ) . '?='; } private function find_file( $filename ) { $theme_dir = Site::get_dir( 'theme', true ); $fp = $theme_dir . $filename; if( !file_exists( $fp ) ) { $plugin_dir = dirname( $this->get_file() ); $fp = $plugin_dir . '/' . $filename; } return $fp; } public function theme_output_comment( $theme, $post, $comment, $level, $max_depth ) { if ( '' == $comment->url_out ) { $comment_url = $comment->name_out; } else { $comment_url = '<a href="' . $comment->url_out . '" rel="external nofollow">' . $comment->name_out . '</a>'; } $class = ' class="comment'; if ( Comment::STATUS_UNAPPROVED == $comment->status ) { $class .= '-unapproved'; } // check to see if the comment is by a registered user if ( $u = User::get( $comment->email ) ) { $class .= ' byuser comment-author-' . Utils::slugify ( $u->displayname ); } if ( $comment->email == $post->author->email ) { $class .= ' bypostauthor'; } if ( $level > 1 ) { $class .= ' comment-reply'; } if ( $level % 2 ) { $class .= ' odd'; } else { $class .= ' even'; } $class .= " depth-$level\""; echo '<'; if( 1 == $level ) { echo 'li '; } else { echo 'div '; } echo "id=\"comment-$comment->id\""; echo $class . '>'; echo '<h3>' . $comment_url . '</h3>'; echo '<div class="comment-date">'; echo '<a href="#comment-' . $comment->id . '" title="' . _t( 'Time of this Comment' ) . '">' . $comment->date->out() . '</a>'; if ( Comment::STATUS_UNAPPROVED == $comment->status ) { echo '<em>' . _t( 'In moderation' ) . '</em>'; } echo '</div>'; echo '<div class="comment-content">' . $comment->content_out . '</div>'; if( $level < $max_depth ) { $this->output_reply_link( $comment ); } if ( isset( $comment->children ) ) { foreach ( $comment->children as $child ) { $theme->output_comment( $post, $child, $level + 1, $max_depth ); } } echo ( $level == 1 ? "</li>\n" : "</div>\n" ); } private function output_reply_link( $comment ) { echo '<div class="reply-link">'; echo '<a href="#" onclick="movecfm (event, ' . $comment->id . ', 1, \'' . $comment->name . '\'); return false;">' . _t( 'Reply' ) . '</a>'; echo '</div>'; } } ?> <file_sep><?php class NicEditor extends Plugin { /* * NicEditor * */ /* Required Plugin Informations */ public function info() { return array( 'name' => 'NicEditor', 'version' => '0.2.5', 'url' => 'http://habariproject.org/', 'author' => 'The Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'NicEditor Plugin for Habari', 'copyright' => '2007' ); } /** * Add actions to the plugin page for this plugin * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id **/ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = 'Configure'; } return $actions; } /** * Respond to the user selecting an action on the plugin page * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook **/ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case 'Configure' : $ui = new FormUI( strtolower( get_class( $this ) ) ); // Add configurable options here $ui->on_success( array( $this, 'updated_config' ) ); $ui->out(); break; } } } /** * Respond to the submitted configure form * @param FormUI $ui The form that was submitted * @return boolean Whether to save the returned values. **/ public function updated_config( $ui ) { $options = array(); // Get the configurable options from the UI with $ui->controls['name_of_control_set_in_ui']->value and add them to the $options array $options[]= 'fullPanel : true'; // Save configurable options for this user Options::set(strtolower(get_class($this)) . ':options_' . User::identify()->id, '{' . implode($options, ',') . '}'); // No need to save input values return false; } /** * Add the JavaScript required for the NicEdit editor to the publish page */ public function action_admin_header($theme) { if ( $theme->page == 'publish' ) { Stack::add( 'admin_header_javascript', $this->get_url() . '/nicEditor/nicEdit.js', 'niceditor' ); } } /** * Instantiate the NicEdit editor and enable media silos */ public function action_admin_footer($theme) { if ( $theme->page == 'publish' ) { $options = Options::get(strtolower(get_class($this) . ':options_' . User::identify()->id)); echo <<<NICEDIT <script type="text/javascript"> $('[@for=content]').removeAttr('for'); new nicEditor({$options}).panelInstance('content'); habari.editor = { insertSelection: function(value) { $(".nicEdit").append(value); } } </script> NICEDIT; } } /** * Enable update notices to be sent using the Habari beacon */ public function action_update_check() { Update::add( 'NicEdit', '2ba6f5fe-b634-4407-bea1-a358c20b146a', $this->info->version ); } } ?> <file_sep><?php /** * Inserts the Javascript from http://browser-update.org. * Following versions should be able to configure for which browsers the notification appears. **/ class Browserupdate extends Plugin { public function action_plugin_activation($file) { } /** * Create plugin configuration menu entry **/ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t('Configure'); } return $actions; } /** * Create plugin configuration **/ public function action_plugin_ui($plugin_id, $action) { } /** * Add help text to plugin configuration page **/ public function help() { $help = ""; return $help; } /** * Nothing to do here atm **/ public function action_init() { } /** * Add the Javascript **/ public function action_template_header() { Stack::add('template_header_javascript', $this->get_url(true) . 'browserupdate.js', 'browserupdate'); } } ?><file_sep><?php class AutoSave extends Plugin { public function action_admin_theme_get_publish() { Stack::add('admin_header_javascript', array($this->get_url() . '/autosave.plugin.js'), 'autosave'); Stack::add('admin_header_javascript', 'autoSave.url=\'' . URL::get('auth_ajax', array('context' => 'autosave')) . '\'', 'autosave-url'); } /** * Altered copy of AdminHandler::post_publish(): * - Throws exceptions rather than Session notices so we can return errors to AJAX calls; * - Does not redirect but echo a JSON object with the post's ID and slug * * @see AdminHandler::post_publish() * * @param AjaxHandler $that The AjaxHandler instance */ public function action_auth_ajax_autosave($handler) { // @todo until ACL checks forr this are added, make inoperable return null; $response = array(); try { $post_id = 0; if ( isset($handler->handler_vars['id']) ) { $post_id = intval($handler->handler_vars['id']); } // If an id has been passed in, we're updating an existing post, otherwise we're creating one if ( 0 !== $post_id ) { $post = Post::get( array( 'id' => $post_id, 'status' => Post::status( 'any' ) ) ); $this->theme->admin_page = sprintf(_t('Publish %s'), Plugins::filter('post_type_display', Post::type_name($post->content_type), 'singular')); $form = $post->get_form( 'ajax' ); $post->title = $form->title->value; if ( $form->newslug->value == '' ) { Session::notice( _t('A post slug cannot be empty. Keeping old slug.') ); } elseif ( $form->newslug->value != $form->slug->value ) { $post->slug = $form->newslug->value; } $post->tags = $form->tags->value; $post->content = $form->content->value; $post->content_type = $form->content_type->value; // if not previously published and the user wants to publish now, change the pubdate to the current date/time // if the post pubdate is <= the current date/time. if ( ( $post->status != Post::status( 'published' ) ) && ( $form->status->value == Post::status( 'published' ) ) && ( HabariDateTime::date_create( $form->pubdate->value )->int <= HabariDateTime::date_create()->int ) ) { $post->pubdate = HabariDateTime::date_create(); } // else let the user change the publication date. // If previously published and the new date is in the future, the post will be unpublished and scheduled. Any other status, and the post will just get the new pubdate. // This will result in the post being scheduled for future publication if the date/time is in the future and the new status is published. else { $post->pubdate = HabariDateTime::date_create( $form->pubdate->value ); } $minor = $form->minor_edit->value && ($post->status != Post::status('draft')); $post->status = $form->status->value; } else { $post = new Post(); $form = $post->get_form( 'ajax' ); $form->set_option( 'form_action', URL::get('admin', 'page=publish' ) ); $postdata = array( 'slug' => $form->newslug->value, 'title' => $form->title->value, 'tags' => $form->tags->value, 'content' => $form->content->value, 'user_id' => User::identify()->id, 'pubdate' => HabariDateTime::date_create($form->pubdate->value), 'status' => $form->status->value, 'content_type' => $form->content_type->value, ); $minor = false; $post = Post::create( $postdata ); } if ( $post->pubdate->int > HabariDateTime::date_create()->int && $post->status == Post::status( 'published' ) ) { $post->status = Post::status( 'scheduled' ); } $post->info->comments_disabled = !$form->comments_enabled->value; Plugins::act('publish_post', $post, $form); $post->update( $minor ); $permalink = ( $post->status != Post::status( 'published' ) ) ? $post->permalink . '?preview=1' : $post->permalink; Session::notice( sprintf( _t( 'The post %1$s has been saved as %2$s.' ), sprintf('<a href="%1$s">\'%2$s\'</a>', $permalink, htmlspecialchars( $post->title ) ), Post::status_name( $post->status ) ) ); if ( $post->slug != Utils::slugify( $post->title ) ) { Session::notice( sprintf( _t( 'The content address is \'%1$s\'.'), $post->slug )); } $response['post_id'] = $post->id; $response['post_slug'] = $post->slug; $response['messages'] = Session::messages_get( true, 'array' ); ob_end_clean(); echo json_encode($response); // Prevent rest of adminhandler to run, we only wanted to save! exit; } catch(Exception $e) { $response['error'] = $e->getMessage(); ob_end_clean(); echo json_encode($response); // Prevent rest of adminhandler to run, we only wanted to save! exit; } } } ?> <file_sep><?php if ( ! empty( $blogs ) ) { ?> <li id="widget-blogroll" class="widget widget_comments"> <h3><?php _e('Blogroll'); ?></h3> <ul> <?php foreach ( $blogs as $blog ) { printf('<li><a href="%1$s" title="%2$s" rel="%3$s">%4$s</a></li>', $blog->url, $blog->description, $blog->rel, $blog->name); } ?> </ul> </li> <?php } ?> <file_sep><?php $theme->display( 'header'); ?> <?php //hide the photo if details have been requested $class_hidden_photo = ( isset($_GET['show_details']) && $_GET['show_details'] == true ) ? 'hidden' : ''; ?> <div id="post_content" class="<?php echo $class_hidden_photo; ?>"> <div id="prev_post"><?php echo $theme->prev_post_link( $post ) ?></div> <?php echo $post->content_out; ?> <div id="next_post"><?php echo $theme->next_post_link( $post ); ?></div> </div> <div id="post_details_link" class="<?php echo $class_hidden_photo; ?>"><a href="<?php echo $post->permalink; ?>?show_details=true" title="View details and comments about <?php echo $post->title_out; ?>">[Details / Comments]</a></div> <?php //hide the details if they haven't been requested $class_hidden_details = ( isset($_GET['show_details']) && $_GET['show_details'] == true ) ? '' : 'hidden'; ?> <div id="post_content_link" class="<?php echo $class_hidden_details; ?>"><a href="<?php echo $post->permalink; ?>" title="View <?php echo $post->title_out; ?>">[View photo]</a></div> <div id="post_details" class="<?php echo $class_hidden_details; ?>"> <div id="details"> <h2>Photo Details</h2> <p class="tags">Tagged: <?php $tags = 0; foreach( $post->tags_out as $tag ) {$tags++; echo ( $tags > 1 ) ? ', '.$tag : $tag;} ?></p> <?php echo $theme->post_content_more; ?> </div> <div id="comments"> <?php $theme->display ( 'comments' ); ?> </div> <div class="clear"></div> </div> <div id="footer"><p>This site is powered by <a href="http://habariproject.org/en/" title="Habari Project">Habari</a></p></div> </div> </div> </body> </html><file_sep><?php /** * MyTheme is a custom Theme class for the K2 theme. * * @package Habari */ /** * @todo This stuff needs to move into the custom theme class: */ // Apply Format::autop() to post content... Format::apply( 'autop', 'post_content_out' ); // Apply Format::autop() to comment content... Format::apply( 'autop', 'comment_content_out' ); // Apply Format::tag_and_list() to post tags... Format::apply( 'tag_and_list', 'post_tags_out' ); // Apply Format::nice_date() to post date... Format::apply( 'nice_date', 'post_pubdate_out', 'l, d F Y' ); // Apply Format::nice_date() to comment date... Format::apply( 'nice_date', 'comment_date_out', 'l, d F Y' ); $header_text = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt.'; // Remove the comment on the following line to limit post length on the home page to 2 paragraphs or 150 characters //Format::apply_with_hook_params( 'more', 'post_content_out', 'Continue Reading &raquo;', 150, 2 ); // We must tell Habari to use MyTheme as the custom theme class: define( 'THEME_CLASS', 'MyTheme' ); /** * A custom theme for K2 output */ class MyTheme extends Theme { public function add_template_vars() { //Theme Options $this->assign('header_text','Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt.'); if( !$this->template_engine->assigned( 'pages' ) ) { $this->assign('pages', Posts::get( array( 'content_type' => 'page', 'status' => Post::status('published'), 'nolimit' => 1 ) ) ); } if( !$this->template_engine->assigned( 'user' ) ) { $this->assign('user', User::identify()->loggedin ); } /* if( !$this->template_engine->assigned( 'page' ) ) { $this->assign('page', isset( $page ) ? $page : 1 ); }*/ if( !$this->template_engine->assigned( 'all_tags' ) ) { // List of all the tags $tags = Tags::get(); $this->assign('all_tags', $tags);} //visiting page/2, /3 will offset to the next page of posts in the sidebar $page=Controller::get_var( 'page' ); $pagination=Options::get('pagination'); if ( $page == '' ) { $page= 1; } $this->assign( 'more_posts', Posts::get(array ( 'status' => 'published','content_type' => 'entry','offset' => ($pagination)*($page), 'limit' => 5, ) ) ); parent::add_template_vars(); $this->add_template('formcontrol_text', dirname(__FILE__).'/forms/formcontrol_text.php', true); $this->add_template('formcontrol_textarea', dirname(__FILE__).'/forms/formcontrol_textarea.php', true); } // called in theme template like so: $theme->monthly_archives_links_list(); public function theme_monthly_archives_links_list( $theme, $full_names = TRUE, $show_counts = TRUE, $type = 'entry', $status = 'published' ) { $results = Posts::get( array( 'content_type' => $type, 'status' => $status, 'month_cts' => 1 ) ); $archives[] = ''; foreach ( $results as $result ) { // add leading zeros $result->month= str_pad( $result->month, 2, 0, STR_PAD_LEFT ); // what format do we want to show the month in? if( $full_names ) { $display_month = HabariDateTime::date_create()->set_date( $result->year, $result->month, 1)->get( 'F' ); } else { $display_month = HabariDateTime::date_create()->set_date( $result->year, $result->month, 1)->get( 'M' ); } // do we want to show the count of posts? if ( $show_counts ) { $count = ' (' . $result->ct . ')'; } else { $count = ''; } $archives[] = '<li>'; $archives[] = '<a href="' . URL::get( 'display_entries_by_date', array( 'year' => $result->year, 'month' => $result->month ) ) . '" title="View entries in ' . $display_month . '/' . $result->year . '">' . $display_month . ' ' . $result->year . ' ' . $count . '</a>'; $archives[] = '</li>'; } $archives[] = ''; return implode( "\n", $archives ); } public function action_form_comment( $form ) { $form->cf_commenter->caption = 'Username :'; $form->cf_email->caption = 'Email :'; $form->cf_url->caption = 'Web Site :'; $form->cf_content->caption = 'Comment :'; $form->cf_content->cols = 50; $form->cf_content->rows = 8; } /*public function gravatar($rating = false, $size = false, $default = false, $border = false) { $out = "http://www.gravatar.com/avatar.php?gravatar_id=".md5( $posts->comments->moderated->email ); if($rating && $rating != '') $out .= "&amp;rating=".$rating; if($size && $size != '') $out .="&amp;size=".$size; if($default && $default != '') $out .= "&amp;default=".urlencode($default); if($border && $border != '') $out .= "&amp;border=".$border; echo $out; }*/ } ?> <file_sep><div id="post-<?php echo $content->id; ?>" class="entry <?php echo $content->statusname; ?>"> <div class="entry-head"> <h2 class="entry-title"><a href="<?php echo $content->permalink; ?>" title="<?php echo $content->title; ?>"><?php echo $content->title_out; ?></a></h2> <div class="entry-meta"> <span class="chronodata published"><?php echo $content->pubdate_ago; ?></span> &middot; <span class="commentslink"><a href="<?php echo $content->permalink; ?>#comments" title="<?php _e('Comments on this post', 'resurrection'); ?>"><?php printf(_n( '%d Comment', '%d Comments', $content->comments->approved->count, 'resurrection' ), $content->comments->approved->count); ?></a></span> <?php if ( is_object($user) && $user->can('edit_post') ) : ?> &middot; <span class="entry-edit"><a href="<?php echo $content->editlink; ?>" title="<?php _e('Edit post', 'resurrection'); ?>"><?php _e('Edit', 'resurrection'); ?></a></span> <?php endif; ?> <?php if ( is_array( $content->tags ) ) : ?> &middot; <span class="entry-tags"><?php echo $content->tags_out; ?></span> <?php endif; ?> </div> </div> <div class="entry-content"> <?php echo $content->content_out; ?> </div> <?php if($request->display_entry): ?> <h3 id="others">Other Posts</h3> <?php $others = array(); $others['Older'] = $post->descend(); $others['Newer'] = $post->ascend(); foreach($post->tags as $tag) { //$other = Post::get('limit=1&vocabulary[tags:all:term]=habari'); //$other = Post::get('limit=1&vocabulary=tags:all:term_display=habari'); $other = Post::get(array('vocabulary' => 'tags[any:term][]=habari&tags[any:term][]=foo')); //$other = Post::get(array('limit'=> 1, 'before' => $post->pubdate->format('Y-m-d'), 'vocabulary'=> 'tags[all:term]=' . $tag->term)); //$other = Post::get('limit=1&before=' . $post->pubdate->format('Y-m-d') . '&vocabulary[tags][all:term]=' . $tag->term); /* $other = Post::get( array( 'limit' => 1, 'vocabulary' => array('all'=>array($tag)), 'before' => $post->pubdate, ) ); //*/ $others['On ' . $tag] = $other; } $others = array_filter($others); ?> <ul class="other_posts"> <?php foreach($others as $othername => $other): ?> <li><b><?php echo $othername; ?>:</b> <a href="<?php echo $other->permalink; ?>"><?php echo htmlspecialchars($other->title); ?></a></li> <?php endforeach; ?> </ul> <?php if(!$post->info->comments_disabled || $content->comments->moderated->comments->count > 0): ?> <h3 id="comments">Comments</h3> <ol class="entry-comments"> <?php foreach($content->comments->moderated->comments as $comment): ?> <li> <?php $theme->content($comment); ?> </li> <?php endforeach; ?> </ol> <?php endif; ?> <?php if(!$post->info->comments_disabled): ?> <?php $post->comment_form()->out(); ?> <?php endif; ?> <?php endif; ?> </div><file_sep><?php include 'header.php'; ?> <!-- entry.single --> <div id="primary" class="single-post"> <div class="inside"> <div class="primary"> <h1><?php echo $post->title; ?></h1> <?php echo $post->content_out; ?> </div> <hr class="hide" /> <div class="secondary"> <div> <b class="spiffy"> <b class="spiffy1"><b></b></b> <b class="spiffy2"><b></b></b> <b class="spiffy3"></b> <b class="spiffy4"></b> <b class="spiffy5"></b> </b> <div class="spiffy_content"> <div class="featured"> <h2>About this entry</h2> <p>You&rsquo;re currently reading &ldquo;<?php echo $post->title; ?>,&rdquo; an entry on <?php Options::out( 'title' ) ; ?></p> <?php if ( is_array($post->tags) ) : ?> <dl> <dt>Tags:</dt> <dd><?php echo $post->tags_out ?></dd> </dl> <?php endif; ?> <?php if ( $loggedin ) : ?> <dl> <dt>Edit:</dt> <dd><a href="<?php URL::out( 'admin', 'page=publish&id=' . $post->id ); ?>" title="Edit post">Edit this entry.</a></dd> </dl> <?php endif; ?><br/> </div> </div> <b class="spiffy"> <b class="spiffy5"></b> <b class="spiffy4"></b> <b class="spiffy3"></b> <b class="spiffy2"><b></b></b> <b class="spiffy1"><b></b></b> </b> </div> </div> <div class="clear"></div> </div> </div> <!-- [END] #primary --> <hr class="hide" /> <div id="secondary"> <div class="inside"> Comments </div> </div> <!-- /entry.single --> <?php include 'sidebar.php'; ?> <?php include 'footer.php'; ?> <file_sep><?php class PageMenuPlugin extends Plugin { function action_init() { $this->add_template( 'pagemenu', dirname(__FILE__) . '/pagemenu.php' ); $this->add_template( 'block.pagemenu', dirname(__FILE__) . '/block.pagemenu.php' ); } public function configure() { if($_SERVER['REQUEST_METHOD']=='POST') { $this->process_form(); } else { $this->show_form(); } } public function show_form() { $candidates = Posts::get(array('content_type'=>'page', 'status'=>'published', 'nolimit'=>true)); usort($candidates, array($this, 'sort_candidates')); $menuids = (array)Options::get('pagemenu__ids'); echo '<form action="" method="post">'; echo '<ul id="pagemenu_candidates">'; foreach($candidates as $candidate) { $checked = in_array($candidate->id, $menuids) ? ' checked' : ''; echo '<li><label><input type="checkbox" name="pagemenu[]" value="' . $candidate->id . '" ' . $checked . '> ' . $candidate->title . '</label></li>'; } echo '</ul>'; echo '<div><label><input id="#pagemenu_show" type="checkbox" checked onclick="pagemenu_toggle(this);"> List pages not currently selected for the menu</label></div>'; echo '<input type="submit" name="submit" value="Set Menu">'; echo '</form>'; } public function sort_candidates($a, $b) { static $menuids = null; if(empty($menuids)) { $menuids = (array)Options::get('pagemenu__ids'); } $ia = in_array($a->id, $menuids); $ib = in_array($b->id, $menuids); if(!$ia && !$ib) { return $a->title > $b->title ? 1 : -1; } elseif($ia && !$ib) { return -1; } elseif(!$ia && $ib) { return 1; } else { $sa = array_search($a->id, $menuids); $sb = array_search($b->id, $menuids); return $sa > $sb ? 1 : -1; } } public function action_admin_header() { $script = <<< HEADER_JS $(function(){ $('#pagemenu_candidates').sortable({axis: 'y', distance: 3}); }); function pagemenu_toggle(e){ if($(e).attr('checked')) { $('#pagemenu_candidates li').show(); } else { $('#pagemenu_candidates input[type=checkbox]:not(:checked)').parents('li').hide(); } } HEADER_JS; Stack::add( 'admin_header_javascript', $script, 'pagemenu', array('jquery', 'ui.sortable') ); $styles = " #pagemenu_candidates { margin: 10px; } #pagemenu_candidates li { border: 1px solid #ccc; border-width: 1px 2px; width: 50%; padding: 5px; margin-bottom: 3px; } #pagemenu_candidates label { background: url(" . Site::get_url('system') . "/admin/images/dashboardhandle.png) no-repeat scroll 320px center; display: block; } #pagemenu_candidates li:hover { background: #f3f3f3; } "; Stack::add( 'admin_stylesheet', array($styles, 'screen'), 'pagemenu'); } public function process_form() { $menus = $_POST['pagemenu']; Options::set('pagemenu__ids', $menus); Session::notice(_t('Updated the menu.')); $this->show_form(); //Utils::redirect(); // Should do this instead, wasn't working locally? } public function theme_pagemenu($theme) { $theme->start_buffer(); $menuids = (array)Options::get('pagemenu__ids'); if(count($menuids) > 0) { $orderbys = array(); foreach(array_reverse($menuids) as $id) { $orderbys[] = "id = {$id}"; } $orderby = implode(',', $orderbys); $menupages = Posts::get(array('content_type'=>'page', 'id'=>$menuids, 'orderby' => $orderby, 'nolimit' => true)); foreach($menupages as $key => $page) { if(isset($theme->post) && $theme->post->slug == $page->slug) { $theme->activemenu = $page; $menupages[$key]->active = true; $menupages[$key]->activeclass = 'active'; } else { $menupages[$key]->active = false; $menupages[$key]->activeclass = 'inactive'; } } } else { $menupages = new Posts(); } $theme->menupages = $menupages; $out = $theme->fetch('pagemenu', true); return $out; } public function help() { return <<< END_HELP <p>To output the menu in your theme, insert this code where you want the menu to appear:</p> <blockquote><code>&lt;?php \$theme-&gt;pagemenu(); ?&gt;</code></blockquote> <p>The default theme only displays the &lt;li&gt; and &lt;a&gt; elements for the menu item. If you want to alter this, you should copy the <tt>pagemenu.php</tt> template included with this plugin to your current theme directory and make changes to it there.</p> END_HELP; } public function filter_block_list($block_list) { $block_list['pagemenu'] = _t('Page Menu'); return $block_list; } public function action_block_content_pagemenu($block, $theme) { $menuids = (array)Options::get('pagemenu__ids'); if(count($menuids) > 0) { $orderbys = array(); foreach(array_reverse($menuids) as $id) { $orderbys[] = "id = {$id}"; } $orderby = implode(',', $orderbys); $menupages = Posts::get(array('content_type'=>'page', 'id'=>$menuids, 'orderby' => $orderby)); foreach($menupages as $key => $page) { if(isset($theme->post) && $theme->post->id == $page->id) { $block->activemenu = $page; $menupages[$key]->active = true; $menupages[$key]->activeclass = 'active'; } else { $menupages[$key]->active = false; $menupages[$key]->activeclass = 'inactive'; } } } else { $menupages = new Posts(); } $block->menupages = $menupages; } } ?><file_sep> <?php Plugins::act( 'theme_sidebar_top' ); ?> <div class="block" id="search"> <h3>Search</h3> <?php include 'searchform.php'; ?> </div> <?php $theme->flickrfeed(); ?> <?php $theme->switcher(); ?> <div class="block" id="recent_comments"> <h3>Recent comments</h3> <ul> <?php foreach($recent_comments as $recent_comment): ?> <li><span class="user"><a href="<?php echo $recent_comment->url; ?>"><?php echo $recent_comment->name; ?></a></span> on <a href="<?php echo $recent_comment->post->permalink; ?>"><?php echo $recent_comment->post->title; ?></a></li> <?php endforeach; ?> </ul> </div> <?php $theme->twitter (); ?> <?php $theme->show_blogroll(); ?> <div class="block" id="recent_posts"> <h3>Recent posts</h3> <ul> <?php foreach($recent_posts as $recent_post): ?> <li><a href="<?php echo $recent_post->permalink; ?>"><?php echo $recent_post->title; ?></a></li> <?php endforeach; ?> </ul> </div> <div class="block" id="login"> <h3>User</h3> <?php include 'loginform.php'; ?> </div> <div class="block" id="footer"> <p><?php Options::out('title'); _e(' is powered by'); ?> <a href="http://www.habariproject.org/" title="Habari">Habari</a> and <a rel="nofollow" href="http://wiki.habariproject.org/en/Available_Themes#Habarism">Habarism</a><br> <a href="<?php URL::out( 'atom_feed', array( 'index' => '1' ) ); ?>">Atom Entries</a> and <a href="<?php URL::out( 'atom_feed_comments' ); ?>">Atom Comments</a></p> <?php $theme->footer(); ?> </div> <?php Plugins::act( 'theme_sidebar_bottom' ); ?> </div> <file_sep><?php include_once dirname( __FILE__ ) . "/classes/pluginsearchinterface.php"; /** * Extensible, but currently Xapian based, search plugin for Habari. * * @todo Better support for pagination count system * @todo Allow filtering based on tags * @todo Sorting by other than relevance (date?) * @todo Caching on get_similar_posts * @todo Index comments as a lower weighted set of terms on their posts * @todo Handle ACL system * */ class MultiSearch extends Plugin { /** * Constant for the option value for the index location */ const PATH_OPTION = 'multisearch__search_db_path'; /** * Constant for th option value for the chosen backend */ const ENGINE_OPTION = 'multisearch__chosen_engine'; /** * The path to the index file */ private $_root_path; /** * The last search query performed */ private $_last_search; /** * Indicate whether the plugin is properly initialised */ private $_enabled; /** * The backend used for searching * * @var PluginSearchInterface */ private $_backend = false; /** * List of id => status maps for post updates. * * @var array */ private $_prior_status = array(); /** * The list of search engines that can be supported * * @var array */ private $_available_engines = array( 'xapian' => 'Xapian', 'zend_search_lucene' => 'Zend Search Lucene' ); /** * The classes and files for available engines. * * @package default * @var array */ private $_engine_classes = array( 'xapian' => array( 'XapianSearch', 'xapiansearch.php' ), 'zend_search_lucene' => array( 'ZendSearchLucene', 'zendsearchlucene.php' ), ); /** * Null the backend to cause it to flush */ public function __destruct() { $this->_backend = null; } /** * Initialize some internal values when plugin initializes */ public function action_init() { $this->init_backend(); if ( !$this->_backend || !$this->_backend->check_conditions() ) { $this->_enabled = false; //Utils::redirect(); //Refresh page. return; } $this->add_template( 'searchspelling', dirname( __FILE__ ) . '/searchspelling.php' ); $this->add_template( 'searchsimilar', dirname( __FILE__ ) . '/searchsimilar.php' ); $this->_enabled = true; } /** * Force a backend - mainly for testing. * * @param PluginSearchInterface $backend */ public function force_backend( $backend ) { $this->_backend = $backend; $this->_enabled = true; } /** * Deactivate the plugin and remove the options * * @param string $file */ public function action_plugin_deactivation( $file ) { Options::delete( self::ENGINE_OPTION ); } /** * Add actions to the plugin page for this plugin * The authorization should probably be done per-user. * * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id */ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ){ if( strlen( Options::get(self::ENGINE_OPTION) ) > 0 ) { $actions[] = _t( 'Configure' ); } $actions[] = _t( 'Choose Engine' ); } return $actions; } /** * Respond to the user selecting an action on the plugin page * * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook * @todo This needs to know about remote backends as well as file paths */ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ){ $action = strlen( Options::get(self::ENGINE_OPTION) ) > 0 ? $action : 'Choose Engine' ; switch ( $action ){ case 'Configure' : $ui = new FormUI( strtolower( get_class( $this ) ) ); $ui->append( 'text', 'index_path', 'option:' . self::PATH_OPTION, _t('The location where the search engine will create the search database.')); $ui->append( 'submit', 'save', _t( 'Save' ) ); $ui->set_option( 'success_message', _t('Options saved') ); $ui->on_success( array( $this, 'updated_config' ) ); $ui->out(); break; case 'Choose Engine' : $ui = new FormUI( strtolower( get_class( $this ) ) ); $options_array = $this->_available_engines; $ui->append( 'select','engine', 'option:' . self::ENGINE_OPTION, _t('Which search engine would you like to use?'), $options_array ); $ui->append( 'submit', 'save', _t( 'Save' ) ); $ui->set_option( 'success_message', _t('Options saved') ); $ui->on_success( array( $this, 'chosen_engine' ) ); $ui->out(); break; } } } /** * Callback from config form submit. Store the details if the location is writeable. * * @param FormUI $ui * @return string|bool */ public function updated_config( $ui ) { $this->init_backend(); if( !$this->_backend || !$this->_backend->check_conditions() ) { $ui->set_option( 'success_message', _t('The engine is not configured correctly.') ); } else { $ui->save(); $this->reindex_all(); return '<p>' . _t('Search database updated.') . '</p>'; } return false; } /** * Callback function from choosing the engine. * * @param FormUI $ui * @return string|bool */ public function chosen_engine( $ui ) { $this->load_backend( $ui->engine->value ); if( !$this->_backend->check_conditions() ) { $ui->set_option( 'success_message', _t('The engine could not be set up, please check the requirements.') ); } else { $ui->save(); return '<p>' . _t('Engine saved - please press close and then select Configure in order to check the details and activate the engine.') . '</p>'; } return false; } /** * If a post is published, add it to the search index. * * @param Post $post the post being inserted */ public function action_post_insert_after( $post ) { if ( !$this->_enabled || Post::status( 'published' ) != $post->status ) { return; } $this->_backend->open_writable_database(); $this->_backend->index_post( $post ); } /** * If a post is modified, track the status in case we * need to delete it from the search index. * * @param string $post * @return void */ public function action_post_update_before( $post ) { if( !$this->_enabled ) { return; } $this->_prior_status[$post->id] = $post->status; } /** * If a post is modified, update the index * * @todo Better handling on published -> unpublished & unpub modify. * @param Post $post the post being updated */ public function action_post_update_after( $post ) { if( !$this->_enabled ) { return; } $this->_backend->open_writable_database(); if ( Post::status( 'published' ) != $post->status && $this->_prior_status[$post->id] == Post::status( 'published' ) ) { $this->_backend->delete_post( $post ); return; } $this->_backend->update_post( $post ); } /** * If a post is deleted, remove it from the index. * * @param Post $post the post being deleted */ public function action_post_delete_before( $post ) { if( !$this->_enabled ) { return; } $this->_backend->open_writable_database(); $this->_backend->delete_post( $post ); } /** * Hook in to the param array in posts to allow handling * the search results * * @param array $paramarray the array of parameters for the Posts get */ public function filter_posts_get_paramarray( $paramarray ) { if( $this->_enabled && isset( $paramarray['criteria'] ) ) { if( $paramarray['criteria'] != '' ) { $this->_last_search = $paramarray['criteria']; // flag that there was a criteria, but blank it. $paramarray['criteria'] = ''; } if( !isset( $paramarray['limit'] ) ) { // magic default number from posts, probably want to change that $paramarray['limit'] = Options::get('pagination') ? (int) Options::get('pagination') : 5; } $limit = $paramarray['limit']; $offset = 0; if( isset($paramarray['count']) ) { // Fudge to get pagination kicking in $limit = $limit * 10; } else if ( isset( $paramarray['page'] ) && is_numeric( $paramarray['page'] ) ) { // Nix the pagination on the SQL query, so it's handled in the SE instead. $paramarray['offset'] = '0'; $offset = ( intval( $paramarray['page'] ) - 1 ) * intval( $limit ); } $this->_backend->open_readable_database(); $ids = $this->_backend->get_by_criteria($this->_last_search, $limit, $offset); if( count( $ids ) > 0 ) { $paramarray['id'] = $ids; $orderby = 'CASE'; $i = 1; foreach($ids as $id) { $orderby .= " WHEN id = " . $id . " THEN " . $i++; } $orderby .= " END"; $paramarray['orderby'] = $orderby; } else { $paramarray['id'] = array(-1); } } return $paramarray; } /** * Output data for the spelling correction theme template. By default will * display a 'Did you mean?' message if spelling corrections were available, * and a link to the corrected search. * * Called from theme like <code><?php $theme->search_spelling(); ?></code> * USes search_spelling template. * * @param Theme $theme */ public function theme_search_spelling( $theme ) { if( !$this->_enabled ) { return; } $theme->spelling = $this->_backend->get_corrected_query_string(); return $theme->fetch( 'searchspelling' ); } /** * Theme function for displaying similar posts to the post passed in. By default * will display a list of post titles that are considered similar to the post in * question. Note that the post needs to be found in the search index, so this * will only work on published items. The easiest way with unpublished would be to * index then delete the post. * * Called from a theme like <code><?php $theme->similar_posts($post); ?></code> * Uses search_similar template. * * @param Theme $theme * @param Post $post * @param int $max_recommended */ public function theme_similar_posts( $theme, $post, $max_recommended = 5 ) { if( !$this->_enabled ) { return; } if( $this->_enabled && $post instanceof Post && intval($post->id) > 0 ) { $ids = $this->_backend->get_similar_posts( $post, $max_recommended ); $theme->similar = count($ids) > 0 ? Posts::get( array('id' => $ids) ) : array(); $theme->base_post = $post; return $theme->fetch( 'searchsimilar' ); } } /** * Reindex the database, and reinit paths. * */ protected function reindex_all() { if( !$this->_enabled ) { return; } $this->_backend->open_writable_database( PluginSearchInterface::INIT_DB ); $posts = Posts::get(array( 'status' => Post::status( 'published' ), 'ignore_permissions' => true, 'nolimit' => true, // techno techno techno techno )); if( $posts instanceof Posts ) { foreach( $posts as $post ) { $this->_backend->index_post( $post ); } } else if( $posts instanceof Post ) { $this->_backend->index_post( $posts ); } } /** * Initialise the file paths * */ protected function init_backend() { $this->_root_path = Options::get( self::PATH_OPTION ); if(!$this->_root_path) { // default to this directory $this->_root_path = HABARI_PATH . '/' . Site::get_path( 'user', true ) . '/plugins/multisearch/indexes/'; Options::set( self::PATH_OPTION, $this->_root_path ); } if( Options::get( self::ENGINE_OPTION ) ) { $this->load_backend( Options::get( self::ENGINE_OPTION ) ); } } /** * Load the files for the backend * * @param string $engine */ protected function load_backend( $engine ) { if( isset( $this->_engine_classes[$engine] ) ) { list( $class, $file ) = $this->_engine_classes[$engine]; include_once dirname( __FILE__ ) . "/classes/" . $file; $this->_backend = new $class( $this->_root_path ); return true; } return false; } } ?><file_sep><form id="month_archive_form" action=""> <fieldset><legend><h3>Browse Archives</h3></legend> <ul><li><select name="archive_tags" onchange="window.location = (document.forms.month_archive_form.archive_tags[document.forms.month_archive_form.archive_tags.selectedIndex].value);"> <option value=''>by date</option> <?php $months = $content->months; foreach( $months as $month ): ?> <option value="<?php echo $month[ 'url' ]; ?>"><?php echo $month[ 'display_month' ] . " " . $month[ 'year' ] . $month[ 'count' ]; ?></option> <?php endforeach; ?> </select></li></ul> </fieldset> </form><file_sep><?php class Polls extends Plugin { //initilization public function action_init() { Post::add_new_type('poll'); $this->add_template('widget', dirname(__FILE__) . '/widget.php'); $this->add_template('poll.single', dirname(__FILE__) . '/poll.single.php'); Stack::add( 'template_header_javascript', Site::get_url('scripts') . '/jquery.js', 'jquery' ); Stack::add( 'template_stylesheet', array(URL::get_from_filesystem(__FILE__) . '/widget.css', 'screen'), 'pollwigitcss'); } //deactivate public function remove_template() { Post::deactivate_post_type('poll'); $this->remove_template('widget', dirname(__FILE__) . '/widget.php'); Stack::remove( 'template_header_javascript', Site::get_url('scripts') . '/jquery.js', 'jquery' ); Stack::remove( 'template_stylesheet', array(URL::get_from_filesystem(__FILE__) . '/widget.css', 'screen'), 'pollwigitcss'); $this->remove_template('poll.single', dirname(__FILE__) . '/poll.single.php'); } public function action_ajax_ajaxpoll() { $pollid = $_GET['pollid']; $vote = $_GET['result']; $post = Post::get(array('content_type'=>Post::type('poll'), 'id'=>$pollid)); if ($vote != 'null') { $array = $post->info->r; $temp = $post->info->r; $temp[$vote]++; $post->info->r = $temp; Session::add_to_set('votes', $post->id); } $post->update(); ?> <ul id="poll_results"> <?php $length = 200; $post->info->r; $max = max($post->info->r); for($n=1; $n<sizeof($post->info->r); $n++) { ?> <label > <?php echo $post->info->entry[$n] ."(". $post->info->r[$n]. ")"; ?> <li style='width: <?php echo $length*($post->info->r[$n]/$max); ?>px'> </li> </label> <?php }; ?> </ul> <?php } //displaying the poll by this //WIGET public function theme_poll($theme, $pollid = null) { include 'widget.php'; } public function action_form_publish($form, $post) { if($post->content_type == Post::type('poll')) { if ($form->silos) $form-> silos->remove(); if ($form->clearbutton) $form-> clearbutton->remove(); $form->title->caption = "Poll Name"; $form->append('text','entry1', 'null:null', 'entry 1','admincontrol_text'); $form->move_after($form->entry1, $form->title); $form->entry1->value = $post->info->entry[1]; $form->append('text','entry2', 'null:null', 'entry 2','admincontrol_text'); $form->move_after($form->entry2, $form->entry1); $form->entry2->value = $post->info->entry[2]; $form->append('text','entry3', 'null:null', 'entry 3','admincontrol_text'); $form->move_after($form->entry3, $form->entry2); $form->entry3->value = $post->info->entry[3]; $form->append('text','entry4', 'null:null', 'entry 4','admincontrol_text'); $form->move_after($form->entry4, $form->entry3); $form->entry4->value = $post->info->entry[4]; $form->append('text','entry5', 'null:null', 'entry 5','admincontrol_text'); $form->move_after($form->entry5, $form->entry4); $form->entry5->value = $post->info->entry[5]; } } public function action_publish_post($post, $form) { if ($post->content_type == Post::type('poll')) { $this->action_form_publish($form, $post); $entry= array(); $entry[1] = $form->entry1->value; $entry[2] = $form->entry2->value; $entry[3] = $form->entry3->value; $entry[4] = $form->entry4->value; $entry[5] = $form->entry5->value; $post->info->entry= $entry; $n = 1; $r = array(); if (!$post->info->r) { foreach ( $post->info->entry as $result): $r[$n] = 0; $n++; endforeach; $post->info->r = $r; } } } } ?> <file_sep><?php /** * Amazon * easily/quickly insert Amazon Products into your posts. * * @package amazon * @version $Id$ * @author ayunyan <<EMAIL>> * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link http://ayu.commun.jp/habari-amazon */ class Amazon extends Plugin { var $countries = array( 'ca' => 'Canada', 'de' => 'Germany', 'fr' => 'France', 'jp' => 'Japan', 'uk' => 'United Kingdom', 'com' => 'United States'); var $search_indexes = array( 'ca' => array( 'Blended', 'Books', 'Classical', 'DVD', 'ForeignBooks', 'Music', 'Software', 'SoftwareVideoGames', 'VHS', 'Video', 'VideoGames'), 'de' => array( 'Apparel', 'Baby', 'Blended', 'Books', 'Classical', 'DVD', 'Electronics', 'ForeignBooks', 'HealthPersonalCare', 'HomeGarden', 'Kitchen', 'Magazines', 'Music', 'MusicTracks', 'OutdoorLiving', 'PCHardware', 'Photo', 'Software', 'SoftwareVideoGames', 'SportingGoods', 'Tools', 'Toys', 'VHS', 'Video', 'VideoGames', 'Watches'), 'fr' => array( 'Blended', 'Books', 'Classical', 'DVD', 'Electronics', 'ForeignBooks', 'Kitchen', 'Music', 'MusicTracks', 'Software', 'SoftwareVideoGames', 'VHS', 'Video', 'VideoGames', 'Watches'), 'jp' => array( 'Apparel', 'Baby', 'Blended', 'Books', 'Classical', 'DVD', 'Electronics', 'ForeignBooks', 'HealthPersonalCare', 'Hobbies', 'Kitchen', 'Music', 'MusicTracks', 'Software', 'SoftwareGoods', 'Toys', 'VHS', 'Video', 'VideoGames', 'Watches'), 'uk' => array( 'Apparel', 'Baby', 'Blended', 'Books', 'Classical', 'DVD', 'Electronics', 'HealthPersonalCare', 'HomeGarden', 'Kitchen', 'Music', 'MusicTracks', 'OutdoorLiving', 'Software', 'SoftwareVideoGames', 'Toys', 'VHS', 'Video', 'VideoGames', 'Watches'), 'com' => array( 'All', 'Apparel', 'Automotive', 'Baby', 'Beauty', 'Blended', 'Books', 'Classical', 'DigitalMusic', 'DVD', 'Electronics', 'GourmetFood', 'HealthPersonalCare', 'HomeGarden', 'Industrial', 'Jewelry', 'KindleStore', 'Kitchen', 'Magazines', 'Merchants', 'Miscellaneous', 'MP3Downloads', 'Music', 'Musicallnstruments', 'MusicTracs', 'OfficeProducts', 'OutdoorLiving', 'PCHardware', 'PetSupplies', 'Photo', 'SilverMerchants', 'Software', 'SportingGoods', 'Tools', 'Toys', 'UnboxVideo', 'VHS', 'Video', 'VideoGames', 'Watches', 'Wireless', 'WirelessAccessories') ); var $access_key = '1D19NAY95HR62NY7BAG2'; var $star_image_url = 'http://g-ecx.images-amazon.com/images/G/01/x-locale/common/customer-reviews/stars-'; /** * action: plugin_activation * * @access public * @param string $file * @return void */ public function action_plugin_activation( $file ) { if ( Plugins::id_from_file( $file ) != Plugins::id_from_file( __FILE__ ) ) return; Options::set('amazon__country', 'com'); Options::set('amazon__associate_tag', ''); Options::set('amazon__template', 'reviewsummary'); } /** * action: init * * @access public * @return void */ public function action_init() { $this->load_text_domain('amazon'); } /** * action: update_check * * @access public * @return void */ public function action_update_check() { Update::add($this->info->name, $this->info->guid, $this->info->version); } /** * action: plugin_ui * * @access public * @param string $plugin_id * @param string $action * @return void */ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id != $this->plugin_id() ) return; if ( $action == _t( 'Configure' ) ) { $template_dir = dirname( $this->get_file() ) . DIRECTORY_SEPARATOR . 'templates'; $templates = array(); if ( $dh = opendir( $template_dir ) ) { while ( ( $file = readdir( $dh ) ) !== false ) { if ( substr( $file, -4 ) == '.php' ) { $template = substr( $file, 0, strlen( $file ) - 4 ); $templates[$template]= $template; } } } $form = new FormUI( strtolower( get_class( $this ) ) ); $form->append( 'select', 'country', 'amazon__country', _t('Country: ', 'amazon'), $this->countries); $form->append( 'text', 'associate_tag', 'amazon__associate_tag', _t('Associate Tag: ', 'amazon') ); $form->append( 'select', 'template', 'amazon__template', _t('Template: ', 'amazon'), $templates); $form->append( 'submit', 'save', _t( 'Save' ) ); $form->out(); } } /** * action: admin_header * * @access public * @param object $theme * @return void */ public function action_admin_header( $theme ) { $handler_vars = Controller::get_handler_vars(); if (!isset($handler_vars['page']) || $handler_vars['page'] != 'publish' ) return; Stack::add( 'admin_header_javascript', $this->get_url() . '/js/amazon.js' ); Stack::add( 'admin_stylesheet', array($this->get_url() . '/css/amazon.css', 'screen') ); } /** * action: ajax_amazon_search * * @access public * @return void */ public function action_before_act_admin_ajax() { $handler_vars = Controller::get_handler_vars(); switch ($handler_vars['context']) { case 'amazon_search': if ( empty( $handler_vars['keywords'] ) ) { echo json_encode( array( 'errorMessage' => _t( 'please specify keywords.' ) ) ); die(); } if ( empty( $handler_vars['search_index'] ) ) { echo json_encode( array( 'errorMessage' => _t( 'please specify searchIndex.' ) ) ); die(); } $keywords = InputFilter::filter($handler_vars['keywords']); $search_index = InputFilter::filter($handler_vars['search_index']); if ( empty( $handler_vars['page'] ) ) { $page = 1; } else { $page = InputFilter::filter($handler_vars['page']); } $result = $this->item_search( $keywords, $search_index, $page ); $xml = simplexml_load_string( $result ); if ( (string)$xml->Items->Request->IsValid != 'True' ) { echo json_encode(array('errorMessage' => _t('following error reply existed from the server: ', 'amazon') . (string)$xml->Items->Request->Errors->Error->Message)); die(); } if ( (int)$xml->Items->TotalResults == 0) { echo json_encode(array('errorMessage' => _t('did not match any items.', 'amazon'))); die(); } $output = array(); $output['TotalResults'] = (int)$xml->Items->TotalResults; $output['TotalPages'] = (int)$xml->Items->TotalPages; $output['CurrentPage'] = $page; $output['Start'] = ($page - 1) * 10 + 1; $output['End'] = $output['Start'] + 10; if ( $output['End'] > $output['TotalResults'] ) $output['End'] = $output['TotalResults']; $output['HasPrev'] = false; $output['HasNext'] = false; if ( $page != 1 ) $output['HasPrev'] = true; if ( $page < $output['TotalPages'] ) $output['HasNext'] = true; $output['Items'] = array(); for ( $i = 0; $i < count( $xml->Items->Item ); $i++ ) { $item = array(); $item['ASIN'] = (string)$xml->Items->Item[$i]->ASIN; $item['DetailPageURL'] = (string)$xml->Items->Item[$i]->DetailPageURL; $item['SmallImageURL'] = (string)$xml->Items->Item[$i]->SmallImage->URL; $item['SmallImageWidth'] = (int)$xml->Items->Item[$i]->SmallImage->Width; $item['SmallImageHeight'] = (int)$xml->Items->Item[$i]->SmallImage->Height; $item['Title'] = (string)$xml->Items->Item[$i]->ItemAttributes->Title; $item['Price'] = (string)$xml->Items->Item[$i]->ItemAttributes->ListPrice->FormattedPrice; $item['Binding'] = (string)$xml->Items->Item[$i]->ItemAttributes->Binding; $output['Items'][] = $item; } echo json_encode( $output ); die(); case 'amazon_insert': if (empty($handler_vars['asin'])) { echo json_encode(array('errorMessage' => _t('please specify ASIN.', 'amazon'))); die(); } $asin = InputFilter::filter($handler_vars['asin']); $result = $this->item_lookup( $asin ); $xml = simplexml_load_string( $result ); if ((string)$xml->Items->Request->IsValid != 'True') { echo json_encode(array('errorMessage' => _t( 'following error reply existed from the server: ', 'amazon') . (string)$xml->Items->Request->Errors->Error->Message )); die(); } $item =& $xml->Items->Item; ob_start(); $template = preg_replace( '/[^A-Za-z0-9\-\_]/', '', Options::get( 'amazon__template' ) ); include( dirname( $this->get_file() ) . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . $template . '.php' ); $output['html'] = ob_get_contents(); ob_end_clean(); echo json_encode( $output ); //echo $output['html']; die(); default: break; } } /** * action: form_publish * * @access public * @param object $form * @return void */ public function action_form_publish($form) { $container = $form->publish_controls->append('fieldset', 'amazon', _t('Amazon')); $search_index = $this->search_indexes[Options::get('amazon__country')]; $search_index = array_combine($search_index, $search_index); ob_start(); ?> <div class="container"> <?php echo Utils::html_select('amazon-search-index', $search_index, null); ?> <input type="text" id="amazon-keywords" name="amazon-keywords" /> <input type="button" id="amazon-search" value="<?php echo _t('Search'); ?>" /> <div id="amazon-spinner"></div> </div> <a name="amazon-result" /> <div id="amazon-result"> </div> <?php $container->append('static', 'static_amazon', ob_get_contents()); ob_end_clean(); } /** * filter: plugin_config * * @access public * @return array */ public function filter_plugin_config($actions, $plugin_id) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t( 'Configure' ); } return $actions; } /** * AWS ItemSearch * * @access private * @param string $keywords * @param string $search_index * @return string */ private function item_search($keywords, $search_index, $page = 1) { // TODO: Paging $url = 'http://ecs.amazonaws.' . Options::get( 'amazon__country' ) . '/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=' . $this->access_key . '&Operation=ItemSearch&ResponseGroup=Small,Images,ItemAttributes&Keywords=' . urlencode($keywords) . '&SearchIndex=' . $search_index . '&ItemPage=' . $page; $associate_tag = Options::get( 'amazon__associate_tag' ); if ( !empty( $associate_tag ) ) $url .= '&AssociateTag=' . $associate_tag; $request = new RemoteRequest( $url, 'GET' ); if ( $request->execute() === false ) return false; return $request->get_response_body(); } /** * AWS ItemLookup * * @access private * @param string $asin * @return string */ private function item_lookup($asin) { $url = 'http://ecs.amazonaws.' . Options::get( 'amazon__country' ) . '/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=' . $this->access_key . '&Operation=ItemLookup&ResponseGroup=Large&ItemId=' . $asin; $associate_tag = Options::get( 'amazon__associate_tag' ); if ( !empty( $associate_tag ) ) $url .= '&AssociateTag=' . $associate_tag; $request = new RemoteRequest( $url, 'GET' ); if ( $request->execute() === false ) return false; return $request->get_response_body(); } /** * Rating to Star Image URL * * @access private * @param float $rating * @return string */ private function ratingToStarImage($rating) { $rating = sprintf( "%.1f", $rating ); $rating_str = str_replace( '.', '-', $rating ); return '<img src="' . $this->star_image_url . $rating_str . '.gif" alt="' . $rating . '" />'; } } ?> <file_sep> <div id="sidebar"> <div id="rss"> <a href="<?php URL::out( 'atom_feed', array( 'index' => '1' ) ); ?>"><span>Subscribe</span></a> </div> <div id="sidebar_main"> <h2>Search</h2> <div id="search_block"> <form method="get" id="searchform" action="<?php URL::out('display_search'); ?>/"> <div> <input type="text" name="criteria" id="s" class="field" value="Searching for ?" onfocus="if (this.value == 'Searching for ?') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Searching for ?';}" /> <input type="image" src="<?php Site::out_url( 'theme' ); ?>/img/search.gif" id="searchsibmit" class="submit" name="submit" /> </div> </form> </div> <?php include "sidebar-text.php"; ?> <h2>Categories</h2> <ul> <?php if( count( $all_tags ) > 0 ) { ?> <ul class="tags"> <?php foreach($all_tags as $tag) { ?> <li> <a href="<?php Site::out_url( 'habari' ); ?>/tag/<?php echo $tag->slug; ?>/" rel="tag" title="See posts with <?php echo $tag->tag; ?> tag"> <?php echo $tag->tag; ?> </a> </li> <?php } ?> </ul> <?php } ?> </ul> <h2>Archives</h2> <ul> <?php $theme->monthly_archives_links_list(); ?> </ul> </div> <div id="sidebar_bottom"> </div> </div><file_sep><?php class AdminPlugin extends Plugin { /** * function info * Returns information about this plugin * @return array Plugin info array **/ public function info() { return array ( 'name' => 'Admin Theme', 'url' => 'http://redalt.com/plugins/habari/admin', 'author' => '<NAME>', 'authorurl' => 'http://asymptomatic.net/', 'version' => '1.0', 'description' => 'A replacement admin for Habari - put the required admin files and directories in the directory with this plugin', 'license' => 'Apache License 2.0', ); } public function filter_admin_theme_dir( $theme_dir ) { $theme_dir = dirname( __FILE__ ) . '/'; return $theme_dir; } public function action_add_template_vars( $theme ) { $theme->admin_url = Site::get_url('user', TRUE) . 'plugins/' . basename(dirname(__FILE__)) . '/'; } } ?><file_sep><?php class Quoticious extends Plugin { public function action_init() { Post::add_new_type('quote'); } public function action_form_publish ($form, $post) { if($post->content_type == Post::type('quote') || $form->content_type->value == Post::type('quote')) { $quote = $form->publish_controls->append('fieldset', 'quote', _t('Quote')); $quote->append('text', 'quote_author', 'null:null', _t('Author'), 'tabcontrol_text'); $quote->quote_author->value = $post->info->quote_author; $quote->append('text', 'quote_url', 'null:null', _t('URL'), 'tabcontrol_text'); $quote->quote_url->value = $post->info->quote_url; return $form; } } public function action_publish_post ( $post, $form ) { if($post->content_type == Post::type('quote') || $form->content_type->value == Post::type('quote')) { if( strlen( $form->quote->quote_author->value ) ) { $post->info->quote_author = $form->quote->quote_author->value; } if( strlen( $form->quote->quote_url->value ) ) { $post->info->quote_url = $form->quote->quote_url->value; } } } } ?> <file_sep><?php class unButtonAdmin extends Plugin { public function action_admin_header( $theme ) { // This is such a hack it's not even funny // But I am laughing inside. Laughing in a bad way. Stack::remove('admin_stylesheet', 'admin'); $css = file_get_contents(Site::get_dir('admin_theme') . '/css/admin.css'); $css = preg_replace( '@#page input\[type=button\], #page input\[type=submit\], #page button {([^}]+)}@', '', $css, 1 ); $css = preg_replace( '@#page input\[type=button\]:hover, #page input\[type=submit\]:hover, #page button:hover {([^}]+)}@', '', $css, 1 ); Stack::add( 'admin_stylesheet', array( preg_replace('@../images/@', Site::get_url('admin_theme') . '/images/', $css), 'screen' ), 'admin', 'jquery' ); } } ?><file_sep><?php $theme->display( 'header'); ?> <div id="page_content"> <h1><?php _e('Error'); ?></h1> <p><?php _e('The requested post was not found.'); ?></p> </div> <div id="footer"><p>This site is powered by <a href="http://habariproject.org/en/" title="Habari Project">Habari</a></p></div> </div> </div> </body> </html><file_sep>Plugin: Maintenance Mode URL: http://habariproject.org Version: 0.3 Author: <NAME> Purpose The purpose of Maintenance Mode is to block access to your site while it is undergoing changes. When the site is in maintenance mode, anyone who is not a logged in user will see only a message saying the site is undergoing maintenance. There are three exceptions to this: 1. If a user is logged in, they will be able to view any page on the site. 2. In order to be able to log in, the login page is still accessible. 3. If the option is set to continue to supply feeds, all feeds will be viewable by all readers. Requirements There are no special requirements. Installation 1. Copy the plugin directory into your user/plugins directory or the site's plugins directory. 2. Go to the plugins page of your Habari admin panel. 3. Click on the Activate button for Maintenance Mode. Usage To configure Maintenance Mode, click on its configure button on the admin plugins page. You will see three options. 1. The text readers will see if they come to your site while it is maintenance mode. You can change this to anything you like. It can be styled in your theme's CSS (h2#maintenance_text). If you would prefer, you can also create a page named maintenance.php in your theme directory containing anything you like. If such a page is found, Maintenance Mode will display that page rather than using the text entered in the configuration options. That text is also accessible from the template should you want to use it, just use echo $theme->maintenance_text within maintenance.php. 2. A checkbox to put the site into maintenance mode and to take it out of maintenance mode. 3. A checkbox to set whether or not feeds will be available to all readers, even if the site is in maintenance mode. Uninstallation 1. Got to the plugins page of your Habari admin panel. 2. Click on the Deactivate button. 3. Delete the maintenance_mode directory from your user/plugins directory. Cleanup None. Maintenance Mode deletes all options it creates on deactivation. Changelog Version 0.3 Changed: Added an option to allow feeds to be accessible to all readers, even if the site is in maintenance mode. Changed: On deactivation, all options created by the plugin are removed from the database. Fixed: Updated to allow for anonymous users. Version 0.2 Changed default header from h1 to h2 and added an ID to make CSS styling easier. Version 0.1 Initial release <file_sep><?php /* * Pays homage to the 2008-09-25 cisco hack. * More here: http://h0bbel.p0ggel.org/cisco-and-missing-t-s * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ class Cisco extends Plugin { public function info() { return array( 'name' => 'Cisco', 'url' => 'http://habariproject.org', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org', 'version' => "0.1", 'description' => 'Pays homage to the 2008-09-25 cisco hack.', 'license' => 'Apache License 2.0' ); } public function filter_final_output( $buffer ) { return str_replace( 't', '', $buffer ); } } ?> <file_sep><?php /* Interwiki for Habari Revision: $Id$ Head URL: $URL$ */ // include Interwiki Parser require_once('interwiki_parser.php'); class Interwiki extends Plugin { private $parser; /** * action: init * * @access public * @retrun void */ public function action_init() { // Interwiki Parser $this->parser = new InterwikiParser(); $this->parser->setEncoding( 'UTF-8' ); } public function action_plugin_activation( $file ) { if ( $file != $this->get_file() ) return; // Interwiki Parser $this->parser = new InterwikiParser(); $this->parser->setEncoding( 'UTF-8' ); Options::set( 'interwiki:interwiki', serialize( $this->parser->getInterwiki() ) ); Options::set( 'interwiki:lang_default', 'en' ); Options::set( 'interwiki:wiki_default', $this->parser->getDefaultWiki() ); } public function action_plugin_ui($plugin_id, $action) { if ( $plugin_id != $this->plugin_id() ) return; if ( $action == _t( 'Configure' ) ) { $interwiki = unserialize(Options::get('interwiki:interwiki')); $ui = new FormUI( strtolower( get_class( $this ) ) ); $wiki_default = $ui->add( 'select', 'wiki_default', _t('Default Wiki'), array_keys( $interwiki ), Options::get('interwiki:wiki_default') ); $lang_default = $ui->add( 'select', 'lang_default', _t('Default Language'), $this->parser->getISO639(), Options::get('interwiki:lang_default') ); $ui->on_success( array( $this, 'updated_config' ) ); $ui->out(); } } /** * FormUI callback * * @access public * @return boolean */ public function updated_config($ui) { return true; } /** * action: update_check * * @access public * @return void */ public function action_update_check() { Update::add( 'Interwiki', 'df59c0ab-1e6d-11dd-b5d6-001b210f913f', $this->info->version ); } /** * filter: post_content_out * * @access public * @return string */ public function filter_post_content_out($content) { preg_match_all( "/\[\[(.*?)\]\]/", $content, $match ); for ( $i = 0; $i < count( $match[1] ); $i++ ) { if ( ( $result = $this->parser->parse( $match[1][$i] ) ) === false ) continue; $content = str_replace( $match[0][$i], "<a href=\"{$result['url']}\" onlick=\"window.open('{$result['url']}'); return false;\" target=\"_blank\">{$result['word']}</a>", $content ); } return $content; } /** * filter: plugin_config * * @access public * @return array */ public function filter_plugin_config($actions, $plugin_id) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t('Configure'); } return $actions; } } ?><file_sep><h2><?php _e( 'Incoming Links' ); ?> (<a href="http://blogsearch.google.com/?scoring=d&amp;num=10&amp;q=link:<?php Site::out_url( 'habari' ) ?>" title="<?php _e( 'More incoming links' ); ?>"><?php _e( 'more' ); ?></a> &raquo;)</h2><div class="handle">&nbsp;</div> <ul class="items"> <?php if ( array_key_exists( 'error', $incoming_links ) ): ?> <li class="item clear"> <span class="pct100"><?php _e( 'Oops, there was a problem with the links.', 'incoming_links' ) ?></span> </li> <li class="item clear"> <span class="pct100"><?php echo $incoming_links['error']; ?></span> </li> <?php elseif ( count( $incoming_links ) == 0 ): ?> <li class="item clear"> <span class="pct100"><?php _e( 'No incoming links were found to this site.', 'incoming_links' ) ?></span> </li> <?php else: ?> <?php foreach ( $incoming_links as $link ) : ?> <li class="item clear"> <span class="pct100"><a href="<?php echo $link['href']; ?>" title="<?php echo $link['title']; ?>"><?php echo $link['title']; ?></a></span> </li> <?php endforeach; ?> <?php endif; ?> </ul> <file_sep><?php /** * Photozou silo * * @package photozousilo * @version $Id$ * @author ayunyan <<EMAIL>> * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 */ class PhotozouSilo extends Plugin implements MediaSilo { const SILO_NAME = 'Photozou'; /** * info * * @access public * @return array */ function info() { return array( 'name' => 'Photozou Silo', 'version' => '0.02-alpha', 'url' => 'http://ayu.commun.jp/', 'author' => 'ayunyan', 'authorurl' => 'http://ayu.commun.jp/', 'license' => 'Apache License 2.0', 'description' => 'Photozou silo (http://photozou.jp/)', 'guid' => 'a290a808-1fc2-11dd-b5d6-001b210f913f' ); } /** * action: plugin_activation * * @access public * @param string $file */ public function action_plugin_activation($file) { if (Plugins::id_from_file($file) != Plugins::id_from_file(__FILE__)) return; Options::set('photozousilo__username', ''); Options::set('photozousilo__password', ''); } /** * action: update_check * * @access public * @return void */ public function action_update_check() { Update::add('Photozou Silo', $this->info->guid, $this->info->version); } /** * action: plugin_ui * * @access public * @param string $plugin_id * @param string $action * @return void */ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id != $this->plugin_id()) return; if ($action == _t('Configure')) { $form = new FormUI(strtolower(get_class($this))); $form->append('text', 'username', 'photozousilo__username', _t('Photozou Username: ')); $form->append('text', 'password', '<PASSWORD>', _t('Photozou Password: ')); $form->append('submit', 'save', _t('Save')); $form->out(); } } /** * actuin: admin_footer * * @access public * @param string $theme * @return void */ public function action_admin_footer($theme) { if ($theme->page != 'publish') return; ?> <script type="text/javascript"> habari.media.output.photozou = { display: function(fileindex, fileobj) { habari.editor.insertSelection('<a href="' + fileobj.photozou_url + '"><img src="' + fileobj.url + '" alt="' + fileobj.title + '" /></a>'); } } </script> <?php } /** * filter: plugin_config * * @access public * @return array */ public function filter_plugin_config($actions, $plugin_id) { if ( $plugin_id == $this->plugin_id() ) { $actions[] = _t('Configure'); } return $actions; } /** * silo info * * @access public * @return string */ public function silo_info() { $photozou = new PhotozouAPI(Options::get('photozousilo__username'), Options::get('photozousilo__password')); if ( $photozou->nop() ) { return array( 'name' => self::SILO_NAME, 'icon' => $this->get_url() . '/img/icon.png' ); } else { Session::error(_t('Photozou Silo: Authencation Error', 'photozousilo')); return array(); } } /** * silo dir * * @access public * @return */ public function silo_dir($path) { $photozou = new PhotozouAPI(Options::get('photozousilo__username'), Options::get('photozousilo__password')); $paths = explode('/', $path); $results = array(); if ( empty ( $paths[0] ) ) { $albums = $photozou->photo_album(); @reset( $albums ); while ( list( $album_id, $album_name ) = @each ( $albums ) ) { $results[] = new MediaAsset( self::SILO_NAME . '/albums/' . $album_id, true, array( 'title' => $album_name ) ); } } else { list( $user_id, $album_id ) = explode( ':', $paths[1] ); $photos = $photozou->photo_list_public( array( 'type' => 'album', 'album_id' => $album_id, 'user_id' => $user_id ) ); if ( $photos === false ) return array(); for ( $i = 0; $i < count( $photos ); $i++ ) { $props = array(); $props['title'] = (string)$photos[$i]->photo_title; $props['url'] = (string)$photos[$i]->image_url; $props['thumbnail_url'] = (string)$photos[$i]->thumbnail_image_url; $props['photozou_url'] = (string)$photos[$i]->url; $props['filetype'] = 'photozou'; $results[] = new MediaAsset( self::SILO_NAME . '/albums/albums/' . $user_id . ':' . $album_id . '/' . (string)$photos[$i]->photo_id, false, $props); } } return $results; } /** * silo get * * @access public */ public function silo_get($path, $qualities = null) { } /** * silo_put * * @access public */ public function silo_put($path, $filedata) { // TODO: built-in file uploading mechanism is not implemented? } /** * silo_url * * @access public * @param string $path * @param string $qualities */ public function silo_url($path, $qualities = null) { } /** * silo_delete * * @access public * @param string $path */ public function silo_delete($path) { } /** * silo highlights * * @access public */ public function silo_highlights() { } /** * silo permissions * * @access public * @param string $path */ public function silo_permissions($path) { } /** * silo contents * * @access public */ public function silo_contents() { } } class PhotozouAPI { var $base_url = 'http://api.photozou.jp/rest/'; var $username; var $password; /** * PhotozouAPI: constructer * * @access public * @param string $username * @param string $password */ public function __construct($username, $password) { $this->username = $username; $this->password = $password; } /** * PhotozouAPI: nop for authentication test * * @access public * @return boolean */ public function nop() { $request = new RemoteRequest( $this->base_url . 'nop', 'GET' ); $request->add_header('Authorization: Basic ' . rtrim( base64_encode( $this->username . ':' . $this->password ), '=' )); $result = $request->execute(); if ( $result !== true ) return false; return true; } /** * PhotozouAPI: photo_album * * @access public * @return object */ public function photo_album() { $request = new RemoteRequest( $this->base_url . 'photo_album', 'GET' ); $request->add_header( 'Authorization: Basic ' . rtrim( base64_encode( $this->username . ':' . $this->password ), '=' ) ); $result = $request->execute(); if ( $result !== true ) return false; $xml = simplexml_load_string( $request->get_response_body() ); if ($xml['stat'] != 'ok') return false; $albums = array(); for ( $i = 0; $i < count( $xml->info->album ); $i++ ) { $albums[ (string)$xml->info->album[$i]->user_id . ':' . (string)$xml->info->album[$i]->album_id ] = (string)$xml->info->album[$i]->name; } return $albums; } /** * PhotozouAPI: photo_list_public * * @access public * @param array $params * @return object */ public function photo_list_public($params) { $param = array(); @reset( $params ); while ( list ( $name, $value ) = @each( $params ) ) { $param[] = $name . '=' . urlencode($value); } $request = new RemoteRequest( $this->base_url . 'photo_list_public?' . join( '&', $param ) , 'GET' ); $result = $request->execute(); if ( $result !== true ) return false; $xml = simplexml_load_string( $request->get_response_body() ); if ($xml['stat'] != 'ok') return false; return $xml->info->photo; } } ?><file_sep><?php /** * Defalut form template for the Jambo contact form plugin for Habari * * @package jambo */ ?> <div id="jambo"> <form method="post" action="<?php echo $jambo->form_action; ?>"> <?php if ( $jambo->success ) { ?> <p class="success"><?php echo $jambo->success_msg; ?></p> <?php } ?> <?php if ( $jambo->error ) { ?> <div class="warning"> <?php echo $jambo->error_msg; ?> <ul> <?php foreach ( $jambo->errors as $jambo_error ) { ?> <li><?php echo $jambo_error; ?></li> <?php } ?> </ul> </div> <?php } ?> <?php if ( $jambo->show_form ) { ?> <p> <label> Your Name: (required)<br /> <?php echo $jambo->name; ?> </label> </p> <p> <label> Your Email: (required)<br /> <?php echo $jambo->email; ?> </label> </p> <p> <label> Subject: (optional)<br /> <?php echo $jambo->subject; ?> </label> </p> <p> <label> Your Remarks: (required)<br /> <?php echo $jambo->message; ?> </label> </p> <p> <?php echo $jambo->osa; ?> <input type="submit" value="Send It!" name="submit" class="button" /> </p> <?php } ?> </form> </div><file_sep><div class="head"><a class="help" href="#help">?</a></div> <div class="content"><?php echo $help; ?></div><file_sep><?php class InlineEdit extends Plugin { public function action_update_check() { Update::add( $this->info->name, 'BFEA4AD0-F4BA-11DE-A09B-1B9856D89593', $this->info->version ); } public function action_admin_header( $theme ) { if( 'comments' == $theme->page ) { $edit_url = URL::get( 'auth_ajax', array( 'context' => 'in_edit' ) ); $urls = <<< AJAX_URLS habari.url.ajaxInEdit='$edit_url'; AJAX_URLS; Stack::add( 'admin_header_javascript', $urls, 'inline_edit_urls', array( 'jquery' ) ); Stack::add( 'admin_header_javascript', $this->get_url( true ) . 'inline_edit.js', 'inline_edit', array( 'jquery' ) ); Stack::add( 'admin_stylesheet', array( $this->get_url( true ) . 'inline_edit.css', 'screen' ), 'inline_edit' ); } } /** * Add inline edit items to the dropdown menu on the comments page */ public function filter_comment_actions( $baseactions, $comments ) { $baseactions['submit'] = array('url' => 'javascript:inEdit.update();', 'title' => _t('Submit changes'), 'label' => _t('Update'), 'nodisplay' => TRUE, 'access' => 'edit' ); $baseactions['cancel'] = array('url' => 'javascript:inEdit.deactivate();', 'title' => _t('Cancel changes'), 'label' => _t('Cancel'), 'nodisplay' => TRUE); return $baseactions; } /** * Handles AJAX from /comments. * Used to edit comments inline. */ public function action_auth_ajax_in_edit( ActionHandler $handler ) { Utils::check_request_method( array( 'POST' ) ); $handler_vars = $handler->handler_vars; $wsse = Utils::WSSE( $handler_vars['nonce'], $handler_vars['timestamp'] ); if ( $handler_vars['digest'] != $wsse['digest'] ) { Session::error( _t('WSSE authentication failed.') ); echo Session::messages_get( true, array( 'Format', 'json_messages' ) ); return; } $comment = Comment::get($handler_vars['id']); if ( !ACL::access_check( $comment->get_access(), 'edit' ) ) { Session::error( _t('You do not have permission to edit this comment.') ); echo Session::messages_get( true, array( 'Format', 'json_messages' ) ); return; } if ( isset($handler_vars['author']) && $handler_vars['author'] != '' ) { $comment->name = $handler_vars['author']; } if ( isset($handler_vars['url']) ) { $comment->url = $handler_vars['url']; } if ( isset($handler_vars['email']) && $handler_vars['email'] != '' ) { $comment->email = $handler_vars['email']; } if ( isset($handler_vars['content']) && $handler_vars['content'] != '' ) { $comment->content = $handler_vars['content']; } if ( isset($handler_vars['time']) && $handler_vars['time'] != '' && isset($handler_vars['date']) && $handler_vars['date'] != '' ) { $seconds = date('s', strtotime($comment->date)); $date = date('Y-m-d H:i:s', strtotime($handler_vars['date'] . ' ' . $handler_vars['time'] . ':' . $seconds)); $comment->date = $date; } $comment->update(); Session::notice( _t('Updated 1 comment.') ); echo Session::messages_get( true, array( 'Format', 'json_messages' ) ); } } ?> <file_sep><!-- To customize this template, copy it to your currently active theme directory and edit it --> <div id="deliciousfeed"> <ul> <?php if (is_array($deliciousfeed)) { foreach ($deliciousfeed as $post) { printf('<li class="delicious-post"><a href="%1$s" title="%2$s">%3$s</a></li>', $post->url, $post->desc, $post->title); } } else // Exceptions { echo '<li class="delicious-error">' . $deliciousfeed . '</li>'; } ?> </ul> </div><file_sep> <div id="primary" class="sidebar"> <ul class="xoxo"> <?php Plugins::act( 'theme_sidebar_top' ); ?> <?php if ( Plugins::is_loaded('Twitter') ) $theme->twitter(); ?> <?php $theme->display('recentcomments.widget'); ?> <?php if ( $this->request->display_home || $this->request->display_404 ) { ?> <?php if ( Plugins::is_loaded('Blogroll') ) $theme->show_blogroll(); ?> <?php } ?> <?php if ( Plugins::is_loaded('TagCloud') ) $theme->display('tagcloud.widget'); ?> <?php Plugins::act( 'theme_sidebar_bottom' ); ?> </ul> </div> <file_sep><?php /** * Geo Location plugin for Habari * * Adds geo location information to posts and provides a simple interface for finding * location information. * * To add support into your theme, use something along the lines of this: * * <?php if ( $post->info->geolocation_enabled ) { ?> * <p> * <a href="http://maps.google.com/maps?q=<?php echo $post->info->geolocation_coords; ?>&t=h"> * <?php echo $post->info->geolocation_coords; ?> * </a> * </p> * <?php } ?> * * @author <NAME> **/ class GeoLocations extends Plugin { private $config = array(); private $class_name; private $arrMapTypeId = array( 'ROADMAP' => 'Road Map', 'HYBRID' => 'Hybrid Map', 'SATELLITE' => 'Satellite Map', 'TERRAIN' => 'Terrain Map' ); private $arrMapControlType = array( 'DROPDOWN_MENU' => 'Dropdown Menu', 'HORIZONTAL_BAR' => 'Horizontal Bar', 'DEFAULT' => 'Default Style' ); private $arrMapNavControlStyle = array( 'SMALL' => 'Small, Zoom Only', 'ANDROID' => 'Android look alike', 'DEFAULT' => 'Default style', 'ZOOM_PAN' => 'Zoom and Pan' ); /** * default_options() * * Set the default options for the plugin **/ private static function default_options() { return array ( 'coords' => '43.05183,-87.913971', 'zoom' => '10', 'jumptoZoom' => '15', 'mapTypeId' => 'ROADMAP', 'mapControlType' => 'DROPDOWN_MENU', 'mapNavControl' => true, 'mapNavControlStyle' => 'SMALL' ); } /** * Add update beacon support. **/ public function action_update_check() { Update::add( 'GeoLocation', '0bab4cb5-f236-40d3-bed1-f4ea56c00ede', $this->info->version ); } /** * On plugin activation, set the default options **/ public function action_plugin_activation( $file ) { if ( realpath( $file ) === __FILE__ ) { $this->class_name = strtolower( get_class( $this ) ); foreach ( self::default_options() as $name => $value ) { $current_value = Options::get( $this->class_name . '__' . $name ); if ( is_null( $current_value ) ) { Options::set( $this->class_name . '__' . $name, $value ); } } } } /** * On plugin init **/ public function action_init() { $this->class_name = strtolower( get_class( $this ) ); foreach ( self::default_options() as $name => $value ) { $this->config[$name] = Options::get( $this->class_name . '__' . $name ); } } /** * Respond to the user selecting configure on the plugin page **/ public function configure() { $ui = new FormUI( $this->class_name ); $ui->append( 'text', 'coords', 'option:' . $this->class_name . '__coords', _t( 'Default Coordinates', $this->class_name ) ); $ui->append( 'text', 'zoom', 'option:' . $this->class_name . '__zoom', _t( 'Default Zoom', $this->class_name ) ); $ui->append( 'text', 'jumptoZoom', 'option:' . $this->class_name . '__jumptoZoom', _t( 'Jump to Zoom', $this->class_name ) ); $ui->append( 'select', 'mapTypeId', 'option:' . $this->class_name . '__mapTypeId', _t( 'Map Type' ), 'optionscontrol_select' ); $ui->mapTypeId->options = $this->arrMapTypeId; $ui->append( 'select', 'mapControlType', 'option:' . $this->class_name . '__mapControlType', _t( 'Map Control Type' ) ); $ui->mapControlType->options = $this->arrMapControlType; $ui->append( 'checkbox', 'mapNavControl', 'option:' . $this->class_name . '__mapNavControl', _t( 'Show Navigation Controls?' ) ); $ui->append( 'select', 'mapNavControlStyle', 'option:' . $this->class_name . '__mapNavControlStyle', _t( 'Navigation Control Style' ) ); $ui->mapNavControlStyle->options = $this->arrMapNavControlStyle; $ui->append( 'submit', 'save', _t( 'Save', $this->class_name ) ); $ui->set_option( 'success_message', _t( 'Options saved', $this->class_name ) ); return $ui; } /** * Create our form for the publish page **/ public function action_form_publish( $form, $post ) { $form->publish_controls->append( 'fieldset', 'geoloc_controls', _t('Geo Location') ); $coords = $form->geoloc_controls->append( 'wrapper', 'coords_form' ); $coords->class = 'container'; $coords->append( 'checkbox', 'geolocation_enabled', 'null:null', 'Use GeoLocation?' ); $coords->geolocation_enabled->template = 'tabcontrol_checkbox'; $coords->geolocation_enabled->value = $post->info->geolocation_enabled; $coords->append( 'text', 'geolocation_coords', 'null:null', 'Coordinates:' ); $coords->geolocation_coords->template = 'tabcontrol_text'; $coords->geolocation_coords->value = $post->info->geolocation_coords; $html = '<p class="pct80"><input type="text" style="width: 100%" class="geoDefaultText" name="geo_address" title="Enter an address, hit the search button, and then drag the marker to tweak the location." /></p><p class="pct20"><input type="button" id="geo_search_button" class="button" value="Search Location" /></p>'; $geo_search = $form->geoloc_controls->append( 'wrapper', 'geotags_form' ); $geo_search->class = 'container formcontrol'; $geo_search->append('static', 'geo_form', $html ); $geo_map = $form->geoloc_controls->append( 'wrapper', 'geotags_map' ); $geo_map->class = 'container formcontrol'; $geo_map->append( 'static', 'geo_map_canvas', '<p class="pct100"><div id="geolocation_map_canvas"></div></p>' ); } /** * Now we need to save our custom entries */ public function action_publish_post( $post, $form ) { $post->info->geolocation_enabled = $form->geolocation_enabled->value; // Only save coords if we are using them, otherwise clear them out if ( $form->geolocation_enabled->value ) { $post->info->geolocation_coords = $form->geolocation_coords->value; } else { $post->info->geolocation_coords = ''; } } /** * Add additional components to the admin header output. **/ public function action_admin_header($theme) { /** * Google maps requires some dimensional computation for it's initialization. It won't work inside a 'display: none' panel as * those elements will report themselves as 0. * * As an easy work around, we use the off-left technique for hiding the inactive tab panels. **/ if ( $theme->page == 'publish' ) { Stack::add('admin_stylesheet', array( '.ui-tabs-hide { position: absolute; left: -10000px; display:block }', 'screen') ); } // @todo: move this to external css? if ( $theme->page == 'publish' ) { Stack::add('admin_stylesheet', array( '#geolocation_map_canvas { width:750px; height:300px; }', 'screen') ); Stack::add('admin_stylesheet', array( '.geoDefaultText { width: 300px; } .geoDefaultTextActive { color: #a1a1a1; font-style: italic; }', 'screen' ) ); } if ( $theme->page == 'publish' ) { // Load Google Maps API after jquery Stack::add('admin_header_javascript', 'http://maps.google.com/maps/api/js?sensor=false', 'googlemaps_api_v3', 'jquery' ); // Now create our page ready javascript $coords = preg_split( '/,/', $this->config['coords'] ); $js_defaults = sprintf( "$(function(){ defaults = { lat: %s, long: %s, zoom: %s, jumptoZoom: %s, mapTypeControlOptions: %s, mapTypeId: %s, navigationControl: %s, navigationControlOptions: %s }; });", $coords[0], $coords[1], $this->config['zoom'], $this->config['jumptoZoom'], '{ style: google.maps.MapTypeControlStyle.' . $this->config['mapControlType'] . ' }', 'google.maps.MapTypeId.' . $this->config['mapTypeId'], ( $this->config['mapNavControl'] ) ? 'true' : 'false', '{ style: google.maps.NavigationControlStyle.' . $this->config['mapNavControlStyle'] . '}' ); // Load defaults after google api Stack::add('admin_header_javascript', $js_defaults, 'geolocation_defaults', 'googlemaps_api_v3' ); // Load our other javascript after the defaults Stack::add('admin_header_javascript', $this->get_url(true) . 'geolocations.js', 'geolocations', 'geolocation_defaults' ); /* You can also load after a list by passing: Stack::add( 'admin_header_javascript', $myscript, 'myscript_name', array( 'required1', required2 ) ); */ } } } ?><file_sep><?php $theme->display('header');?> <div id="options_edit" class="container settings"> <h2><?php _e( 'Option name: [%s]', array($option['name'] ) ); ?></h2> <h3><?php _e( 'Genre: [%s]', array($option['genre'] ) ); ?></h3> <h3><?php _e( 'Plugin: [%s]', array($option['plugin_name'] ) ); ?></h3> <?php echo $form; ?> </div> <?php if ( isset( $option['value_unserialized'] ) && count( $option['value_unserialized'] ) > 0): ?> <div class="container settings"> <h2>Unserialized version of the value</h2> <ul> <?php foreach ( $option['value_unserialized'] as $name => $value ): ?> <li class="item clear"> <span class="message pct20 minor"><?php echo $name; ?></span> <span class="message pct80 minor"><?php echo $value; ?></span> </li> <?php endforeach; ?> </ul> </div> <?php endif; ?> <?php $theme->display('footer');?> <file_sep><?php /* The Xapian PHP bindings need to be in the path, and the extension loaded */ include_once "xapian.php"; include_once dirname(__FILE__) . "/pluginsearchinterface.php"; /** * An implementation of a Xapian search backend for the * search plugin. * * @todo Support for remote backends so Xapian can be elsewhere (via FormUI config) * @todo Add weighting for tags in index * @todo Handle error from opening database * * @link http://xapian.org */ class XapianSearch implements PluginSearchInterface { /* Xapian's field values need to be numeric, so we define some constants to help them be a bit more readable. */ const XAPIAN_FIELD_URL = 0; const XAPIAN_FIELD_TITLE = 1; const XAPIAN_FIELD_PUBDATE = 2; const XAPIAN_FIELD_CONTENTTYPE = 3; const XAPIAN_FIELD_USERID = 4; const XAPIAN_FIELD_ID = 5; /* Std prefix from Xapian docs */ const XAPIAN_PREFIX_UID = 'Q'; /** * The handle for the Xapian DB * @var XapianDatabase */ private $_database; /** * The current stemming locale */ private $_locale; /** * The spelling correction, if needed */ private $_spelling = ''; /** * Map of locales to xapian stemming files */ private $_stem_map = array( 'da' => 'danish', 'de' => 'german', 'en' => 'english', 'es' => 'spanish', 'fi' => 'finnish', 'fr' => 'french', 'hu' => 'hungarian', 'it' => 'italian', 'nl' => 'dutch', 'no' => 'norwegian', 'pt' => 'portuguese', 'ro' => 'romanian', 'ru' => 'russian', 'sv' => 'swedish', 'tr' => 'turkish', ); /** * The default stemmer to be used if not * matching locale is found. If false, * no stemming will be performed. */ private $_default_stemmer = false; /** * The path to the index file */ private $_index_path; /** * The path to the index file directory */ private $_root_path; /** * Create the object, requires the index location. * * @param string $path */ public function __construct( $path ) { $this->_root_path = $path; $this->_index_path = $this->_root_path . (substr($this->_root_path, -1) == '/' ? '' : '/') . 'xapian.db'; } /** * Null the Xapian database to cause it to flush */ public function __destruct() { $this->_database = null; // flush } /** * Check whether the preconditions for the plugin are installed * * @return boolean */ public function check_conditions() { $ok = true; if( !is_writable( $this->_root_path ) ) { Session::error( 'Init failed, Search index directory is not writeable. Please update configuration with a writeable directiory.', 'Multi Search' ); $ok = false; } if( !class_exists("XapianTermIterator") ) { Session::error( 'Init failed, Xapian extension or php file not installed.', 'Multi Search' ); $ok = false; } return $ok; } /** * Open the database for reading */ public function open_readable_database() { if( !isset($this->_database) ) { if( strlen($this->_index_path) == 0 ) { Session::error('Received a bad index path in the database opening', 'Xapian Search'); return false; } $this->_database = new XapianDatabase( $this->_index_path ); } } /** * Initialise a writable database for updating the index * * @param int flag allow setting the DB to be initialised with PluginSearchInterface::INIT_DB */ public function open_writable_database( $flag = 0 ) { // Open the database for update, creating a new database if necessary. if( isset($this->_database) ) { if( $this->_database instanceof XapianWritableDatabase ) { return; } else { $this->_database = null; } } if( strlen($this->_index_path) == 0 ) { Session::error('Received a bad index path in the database opening', 'Xapian Search'); return false; } // Create/Open or Create/Overwrite depending on whether the module is being init /* * NB: Helpfully, if you pass the Xapian create database null you get the error * "No matching function for overloaded 'new_WritableDatabase'" * rather than anything helpful! */ if( $flag == PluginSearchInterface::INIT_DB ) { $this->_database = new XapianWritableDatabase( $this->_index_path, (int)Xapian::DB_CREATE_OR_OVERWRITE ); } else { $this->_database = new XapianWritableDatabase( $this->_index_path, (int)Xapian::DB_CREATE_OR_OPEN ); } $this->_indexer = new XapianTermGenerator(); // enable spelling correction $this->_indexer->set_database( $this->_database ); $this->_indexer->set_flags( XapianTermGenerator::FLAG_SPELLING ); // enable stemming if($this->get_stem_locale()) { // Note, there may be a problem if this is different than at search time! $stemmer = new XapianStem( $this->get_stem_locale() ); $this->_indexer->set_stemmer( $stemmer ); } } /** * Return a list of IDs for the given search criters * * @param string $criteria * @param int $limit * @param int $offset * @return array */ public function get_by_criteria( $criteria, $limit, $offset ) { $qp = new XapianQueryParser(); $enquire = new XapianEnquire( $this->_database ); if($this->get_stem_locale()) { // Note, there may be a problem if this is different than at indexing time! $stemmer = new XapianStem( $this->get_stem_locale() ); $qp->set_stemmer( $stemmer ); $qp->set_stemming_strategy( XapianQueryParser::STEM_SOME ); } $qp->set_database( $this->_database ); $query = $qp->parse_query( $criteria, XapianQueryParser::FLAG_SPELLING_CORRECTION ); $enquire->set_query( $query ); $this->_spelling = $qp->get_corrected_query_string(); $matches = $enquire->get_mset( $offset, $limit ); // TODO: get count from $matches->get_matches_estimated() instead of current method $i = $matches->begin(); $ids = array(); while ( !$i->equals($matches->end()) ) { $n = $i->get_rank() + 1; $ids[] = $i->get_document()->get_value( self::XAPIAN_FIELD_ID ); $i->next(); } return $ids; } /** * Return the spelling correction, if this exists. * * @return string */ public function get_corrected_query_string() { return $this->_spelling; } /** * Updates a post. * * @param Post $post */ public function update_post( $post ) { return $this->index_post( $post ); } /** * Add a post to the index. Adds more metadata than may be strictly * required! * * @param Post $post the post being inserted */ public function index_post( $post ) { $doc = new XapianDocument(); // Store some useful stuff with the post $doc->set_data( $post->content); $doc->add_value( self::XAPIAN_FIELD_URL, $post->permalink ); $doc->add_value( self::XAPIAN_FIELD_TITLE, $post->title ); $doc->add_value( self::XAPIAN_FIELD_USERID, $post->user_id ); $doc->add_value( self::XAPIAN_FIELD_PUBDATE, $post->pubdate ); $doc->add_value( self::XAPIAN_FIELD_CONTENTTYPE, $post->content_type ); $doc->add_value( self::XAPIAN_FIELD_ID, $post->id ); // Index title and body $this->_indexer->set_document( $doc ); $this->_indexer->index_text( $post->title, 50 ); // add weight to titles $this->_indexer->index_text( $post->content, 1 ); // Add terms $tags = $post->tags; foreach( $tags as $id => $tag ) { $tag = (string)$tag; $this->_indexer->index_text( $tag, 1, 'XTAG' ); // with index for filter $this->_indexer->index_text( $tag, 2 ); // without prefix for index } // Add uid $id = $this->get_uid( $post ); $doc->add_term( $id ); return $this->_database->replace_document( $id, $doc ); } /** * Remove a post from the index * * @param Post $post the post being deleted */ public function delete_post( $post ) { $this->_database->delete_document( $this->get_uid($post) ); } /** * Return a list of posts that are similar to the current post */ public function get_similar_posts( $post, $max_recommended = 5 ) { $guid = $this->get_uid($post); $posting = $this->_database->postlist_begin( $guid ); $enquire = new XapianEnquire( $this->_database ); $rset = new XapianRset(); $rset->add_document( $posting->get_docid() ); $eset = $enquire->get_eset(20, $rset); $i = $eset->begin(); $terms = array(); while ( !$i->equals($eset->end()) ) { $terms[] = $i->get_term(); $i->next(); } $query = new XapianQuery( XapianQuery::OP_OR, $terms ); $enquire->set_query( $query ); $matches = $enquire->get_mset( 0, $max_recommended+1 ); $ids = array(); $i = $matches->begin(); while ( !$i->equals($matches->end()) ) { $n = $i->get_rank() + 1; if( $i->get_document()->get_value(self::XAPIAN_FIELD_ID) != $post->id ) { $ids[] = $i->get_document()->get_value( self::XAPIAN_FIELD_ID ); } $i->next(); } return $ids; } /** * Prefix the UID with the xapian GUID prefix. * * @param Post $post the post to extract the ID from */ protected function get_uid( $post ) { return self::XAPIAN_PREFIX_UID . $post->id; } /** * Return the current locale based on options * * @return string */ protected function get_stem_locale() { if(isset($this->_locale)) { return $this->_locale; } if ( Options::get('locale') ) { $locale = Options::get('locale'); } else if ( Options::get( 'system_locale' ) ) { $locale = Options::get( 'system_locale' ); } else { $locale = 'en-us'; } $locale = substr($locale, 0, 2); $this->_locale = isset($this->_stem_map[$locale]) ? $this->_stem_map[$locale] : $this->_default_stemmer; return $this->_locale; } }<file_sep><?php class SpamCronDelete extends Plugin { public function action_plugin_activation( $file ) { if ( Plugins::id_from_file( $file ) == Plugins::id_from_file( __FILE__ ) ) { CronTab::add_daily_cron('spamcrondelete', 'cron_delete_spam', 'Deletes spam comments that are old.'); } } public function action_plugin_deactivation( $file ) { if ( Plugins::id_from_file( $file ) == Plugins::id_from_file( __FILE__ ) ) { CronTab::delete_cronjob('spamcrondelete'); } } private function delete_old_spam() { // The inline values are safe and used this way for a reason $comments = Comments::get(array('where' => 'date < ' . strtotime('yesterday') . ' AND {comments}.status = ' . Comment::STATUS_SPAM)); if($comments->count == 0) { $message = _t( 'No old spam to delete.' ); } else { $total = $comments->count(); $comments->delete(); $message = _t( 'Deleted all %s spam comments.', array($total)); } return $message; } public function filter_cron_delete_spam($result, $params) { $message = $this->delete_old_spam(); EventLog::log($message); return true; } public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions['delete_old_spam'] = _t( 'Delete Old Spam Now' ); } return $actions; } public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case 'delete_old_spam' : echo $this->delete_old_spam(); break; } } } } ?><file_sep><?php include 'header.php'; ?> <div id="primary" class="twocol-stories"> <div class="inside"> <div class="story first"> <h3>Unfortunately, I couldn't find the post you're looking for.</h3> </div> <div class="story"> <?php $has_tags = ( count($tags) > 0 ); $has_pages = ( count($pages) > 0 ); ?> <?php if ( $has_tags || $has_pages ): ?> <h3>Here are some other things to try.</h3> <?php if ( $has_tags ): ?> <h4>Tags</h4> <?php foreach ( $tags as $tag ) { echo "<a href=\"{$habari}/tag/{$tag->slug}/\">{$tag->tag}</a> "; } ?> <?php endif; ?> <?php if ( $has_pages ): ?> <h4>Pages</h4> <?php foreach ( $pages as $page ) { echo "<a href=\"{$habari}/{$page->slug}/\">{$page->title}</a>"; } ?> <?php endif; ?> <?php endif; ?> </div> <div class="clear"></div> </div> </div> <?php include 'sidebar.php'; ?> <?php include 'footer.php'; ?> <file_sep><?php // TinyURL helper module for the Habari Lilliputian plugin { function shrink( $url ) { $service= 'http://tinyurl.com/api-create.php?url='; $request = new RemoteRequest( $service . urlencode($url), 'GET' ); $result = $request->execute(); if ( Error::is_error( $result ) ) { throw $result; } $data= $request->get_response_body(); if ( Error::is_error( $data ) ) { throw $data; } return $data; } } <file_sep><?php class comment_notifier extends Plugin { const VERSION = '1.2'; public function info() { return array( 'name' => 'Comment Notifier', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'version' => self::VERSION, 'description' => 'Send an email to the author of a post whenever a non-spam comment is moderated for one of their posts.', 'license' => 'Apache License 2.0' ); } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Comment Notifier', '91175a80-38f6-11dd-ae16-0800200c9a66', $this->info->version ); } private function mh_utf8($str) { return '=?UTF-8?B?' . base64_encode($str) . '?='; } public function action_comment_insert_after( $comment ) { // we should only execute on comments, not pingbacks // and don't bother if the comment is know to be spam if ( ( $comment->type != Comment::COMMENT ) || ( $comment->status == Comment::STATUS_SPAM ) ) { return; } $post = Post::get( array('id' => $comment->post_id ) ); $author = User::get_by_id( $post->user_id ); $status = $comment->status == Comment::STATUS_UNAPPROVED ? ' UNAPPROVED' : ' approved'; $title = sprintf(_t('[%1$s] New%3$s comment on: %2$s'), Options::get('title'), $post->title, $status); $message = <<< MESSAGE The following comment was added to the post "%1\$s". %2\$s Author: %3\$s <%4\$s> URL: %5\$s %6\$s ----- Moderate comments: %7\$s MESSAGE; $message = _t($message); $message = sprintf( $message, $post->title, $post->permalink, $comment->name, $comment->email, $comment->url, $comment->content, URL::get('admin', 'page=comments') ); $headers = array( 'MIME-Version: 1.0', 'Content-type: text/plain; charset=utf-8', 'Content-Transfer-Encoding: 8bit', 'From: ' . $this->mh_utf8($comment->name) . ' <' . $comment->email . '>', ); mail ($author->email, $this->mh_utf8($title), $message, implode("\r\n", $headers)); } } ?> <file_sep><?php /** * Fire Eagle * Fire Eagle for Habari * * @package fireeagle * @version $Id$ * @author ayunyan <<EMAIL>> * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * @link http://ayu.commun.jp/habari-fireeagle */ require('lib/fireeagle.php'); class FireEagle extends Plugin { private $consumer_key = 'GKDcUJOEuDvX'; private $consumer_secret = '<KEY>'; private $level_zoom_map = array( 0 => 16, // exact 1 => 14, // postal 3 => 11, // city 4 => 8, // region 5 => 5, // state 6 => 2, // country ); /** * plugin information * * @access public * @retrun void */ public function info() { return array( 'name' => 'Fire Eagle', 'version' => '0.01-beta', 'url' => 'http://ayu.commun.jp/habari-fireeagle', 'author' => 'ayunyan', 'authorurl' => 'http://ayu.commun.jp/', 'license' => 'Apache License 2.0', 'description' => 'Displays current location on your blog.', 'guid' => '84708e24-6de5-11dd-b14a-001b210f913f' ); } /** * action: plugin_activation * * @access public * @param string $file * @return void */ public function action_plugin_activation($file) { if (Plugins::id_from_file($file) != Plugins::id_from_file(__FILE__)) return; Options::set('fireeagle__refresh_interval', 3600); Modules::add(_t('Fire Eagle', 'fireeagle')); } /** * action: init * * @access public * @return void */ public function action_init() { $this->load_text_domain('fireeagle'); $this->add_template('fireeagle', dirname(__FILE__) . '/templates/fireeagle.php'); } /** * action: update_check * * @access public * @return void */ public function action_update_check() { Update::add($this->info->name, $this->info->guid, $this->info->version); } /** * action: plugin_ui * * @access public * @param string $plugin_id * @param string $action * @return void */ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id != $this->plugin_id()) return; if ($action == _t('Configure')) { $form = new FormUI(strtolower(get_class($this))); $form->on_success(array($this, 'on_success')); $refresh_interval = $form->append('text', 'refresh_interval', 'fireeagle__refresh_interval', _t('Refresh Interval (sec): ', 'fireeagle')); $refresh_interval->add_validator('validate_regex', '/^[0-9]+$/'); $form->append('submit', 'save', _t('Save')); $form->out(); } elseif ($action == _t('Authorize', 'fireeagle')) { // get request token $fireeagle = new FireEagleAPI($this->consumer_key, $this->consumer_secret); $token = $fireeagle->getRequestToken(); if (!$token || empty($token['oauth_token'])) { echo 'Invalid Response'; return; } $_SESSION['fireeagle']['req_token'] = $token['oauth_token']; $_SESSION['fireeagle']['req_token_secret'] = $token['oauth_token_secret']; $_SESSION['fireeagle']['state'] = 1; $oauth_callback = URL::get('admin', array('page' => 'plugins', 'configure' => $plugin_id, 'configaction' => '_callback')) . '#plugin_' . $plugin_id; ob_end_clean(); header('Location: ' . $fireeagle->getAuthorizeURL($token) . '&oauth_callback=' . urlencode($oauth_callback)); exit; } elseif ($action == _t('De-Authorize', 'fireeagle')) { Options::set('fireeagle__access_token_' . User::identify()->id, ''); Options::set('fireeagle__access_token_secret_' . User::identify()->id, ''); echo 'Fire Eagle De-authorization successfully.'; } elseif ($action == '_callback') { if (empty($_GET['oauth_token']) || $_GET['oauth_token'] != $_SESSION['fireeagle']['req_token']) { echo 'Invalid Token'; return; } // get access token $fireeagle = new FireEagleAPI($this->consumer_key, $this->consumer_secret, $_SESSION['fireeagle']['req_token'], $_SESSION['fireeagle']['req_token_secret']); $token = $fireeagle->getAccessToken(); if (!$token || empty($token['oauth_token'])) { echo 'Invalid Response'; return; } Options::set('fireeagle__access_token_' . User::identify()->id, $token['oauth_token']); Options::set('fireeagle__access_token_secret_' . User::identify()->id, $token['oauth_token_secret']); echo 'Fire Eagle Authorization successfully.'; } } public function on_success($form) { $form->save(); $params = array( 'name' => 'fireeagle:refresh', 'callback' => 'fireeagle_refresh', 'increment' => Options::get('fireeagle__refresh_interval'), 'description' => 'Refreshing Fire Eagle Location' ); CronTab::delete_cronjob($params['name']); CronTab::add_cron($params); return false; } /** * action: admin_header * * @access public * @param object $theme * @return void */ public function action_admin_header($theme) { if ($theme->page != 'dashboard') return; Stack::add('admin_header_javascript', $this->get_url() . '/js/admin.js'); Stack::add('admin_stylesheet', array($this->get_url() . '/css/admin.css', 'screen')); } /** * action: before_act_admin_ajax * * @access public * @return void */ public function action_before_act_admin_ajax() { $handler_vars = Controller::get_handler_vars(); switch ($handler_vars['context']) { case 'fireeagle_update': $user = User::identify(); $access_token = Options::get('fireeagle__access_token_' . $user->id); $access_token_secret = Options::get('fireeagle__access_token_secret_' . $user->id); if (empty($access_token) || empty($access_token_secret)) { echo json_encode(array('errorMessage' => _t('Authorize is not done!', 'fireeagle'))); die(); } $fireeagle = new FireEagleAPI($this->consumer_key, $this->consumer_secret, $access_token, $access_token_secret); try { $result = $fireeagle->update(array('address' => $handler_vars['location'])); } catch (FireEagleException $e) { echo json_encode(array('errorMessage' => $e->getMessage())); die(); } if (!is_object($result) || $result->stat != 'ok') { echo json_encode(array('errorMessage' => _t('Update failed.', 'fireeagle'))); die(); } // refresh location if (!$this->update((int)$user->id)) { echo json_encode(array('errorMessage' => _t('Update failed.', 'fireeagle'))); die(); } $location = ''; if (isset($user->info->fireeagle_location)) { $location = $user->info->fireeagle_location; } echo json_encode(array('location' => $location, 'message' => sprintf(_t('Your present place was updated to "%s".', 'fireeagle'), $location))); die(); default: break; } } /** * filter: plugin_config * * @access public * @return array */ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id == $this->plugin_id()) { $actions[] = _t('Configure'); $access_token = Options::get('fireeagle__access_token_' . User::identify()->id); $access_token_secret = Options::get('fireeagle__access_token_secret_' . User::identify()->id); if (empty($access_token) || empty($access_token_secret)) { $actions[] = _t('Authorize', 'fireeagle'); } else { $actions[] = _t('De-Authorize', 'fireeagle'); } } return $actions; } /** * filter: dash_modules * * @access public * @param array $modules * @return array */ public function filter_dash_modules($modules) { $modules[] = _t('Fire Eagle', 'fireeagle'); $this->add_template('dash_fireeagle', dirname(__FILE__) . '/dash_fireeagle.php'); return $modules; } /** * filter: dash_module_fire_eagle * * @access public * @param array $module * @param string $module_id * @param object $theme * @return array */ public function filter_dash_module_fire_eagle($module, $module_id, $theme) { $module['title'] = _t('Fire Eagle', 'fireeagle') . '<img src="' . $this->get_url() . '/img/fireeagle.png" alt= "Fire Eagle" />'; $form = new FormUI('dash_fireeagle'); $form->append('text', 'location', 'null:unused', _t('Location: ', 'fireeagle')); $user = User::identify(); if (isset($user->info->fireeagle_location)) { $form->location->value = $user->info->fireeagle_location; } $form->append('submit', 'submit', _t('Update', 'fireeagle')); $form->properties['onsubmit'] = 'fireeagle.update(); return false;'; $theme->fireeagle_form = $form->get(); $module['content'] = $theme->fetch('dash_fireeagle'); return $module; } /** * filter: fireeagle_refresh * * @access public * @param boolean $result * @return boolean */ public function filter_fireeagle_refresh($result) { $users = Users::get_all(); foreach ($users as $user) { $location = $this->update((int)$user->id); if (!$location) continue; } $result = true; return $result; } /** * theme: show_fireeagle * * @access public * @param object $theme * @param mixed $who user ID, username, or e-mail address * @return string */ public function theme_show_fireeagle($theme, $who) { $user = User::get($who); if (!$user) return ''; $theme->fireeagle_longitude = $user->info->fireeagle_longitude; $theme->fireeagle_latitude = $user->info->fireeagle_latitude; $theme->fireeagle_level = $user->info->fireeagle_level; if (isset($user->info->fireeagle_location)) { $theme->fireeagle_location = $user->info->fireeagle_location; } $theme->zoom = 1; if (isset($this->level_zoom_map[$user->info->fireeagle_level])) { $theme->zoom = $this->level_zoom_map[$user->info->fireeagle_level]; } return $theme->fetch('fireeagle'); } /** * refresh location * * @access private * @param mixed $who user ID, username, or e-mail address * @return boolean */ private function update($who) { $user = User::get($who); if (!$user) return false; $access_token = Options::get('fireeagle__access_token_' . $user->id); $access_token_secret = Options::get('fireeagle__access_token_secret_' . $user->id); if (empty($access_token) || empty($access_token_secret)) return; $fireeagle = new FireEagleAPI($this->consumer_key, $this->consumer_secret, $access_token, $access_token_secret); try { $result = $fireeagle->user(); } catch (FireEagleException $e) { return false; } if (!isset($result->user->best_guess)) return false; $location = $result->user->best_guess; $user->info->fireeagle_longitude = $location->longitude; $user->info->fireeagle_latitude = $location->latitude; $user->info->fireeagle_level = $location->level; if (isset($location->name)) { $user->info->fireeagle_location = $location->name; } else { $user->info->fireeagle_location = ''; } $user->info->commit(); Plugins::act('fireeagle_after_update', $user); return true; } } ?><file_sep><?php $theme->display( 'header'); ?> <?php foreach( $posts as $post ){ ?> <div id="post_content"> <div id="prev_post"><?php echo $theme->prev_post_link( $post ) ?></div> <?php echo $post->content_out; ?> <div id="next_post"><?php echo $theme->next_post_link( $post ); ?></div> </div> <div id="post_details_link"><a href="<?php echo $post->permalink; ?>?show_details=true" title="View details and comments about <?php echo $post->title_out; ?>">[Details / Comments]</a></div> <?php } ?> <div id="footer"><p>This site is powered by <a href="http://habariproject.org/en/" title="Habari Project">Habari</a></p></div> </div> </div> </body> </html><file_sep>$(document).ready(function() { $('.spoiler-message').bind( 'click', function() { $(this).parent().find('.spoiler-text').show(); $(this).hide(); return false; }); }); <file_sep><?php class dateNinja extends Plugin { public function info() { return array( 'name' => 'Date Ninja', 'version' => '1.0', 'url' => 'http://www.chrisjdavis.org', 'author' => '<NAME>', 'authorurl' => 'http://www.chrisjdavis.org', 'license' => 'MIT', 'description' => 'Allows you to use plain language when selecting publishing dates. Based on datejs.', 'copyright' => '2008', ); } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'DateNinja', 'e64e02e0-38f8-11dd-ae16-0800200c9a66', $this->info->version ); } public function action_init() { // add some js to the admin header Stack::add( 'admin_header_javascript', $this->get_url() . '/date_ninja.js', 'dateninja' ); Stack::add( 'admin_header_javascript', $this->get_url() . '/date.js', 'datejs' ); } } ?> <file_sep><ul> <?php $posts = $content->popular_posts; foreach( $posts as $post): ?> <li> <a href="<?php echo $post->permalink; ?>"> <?php echo $post->title; ?> </a> </li> <?php endforeach; ?> </ul><file_sep><div id="sidebar"> <?php Plugins::act( 'theme_sidebar_top' ); ?> <div class="block" id="search"> <?php include 'searchform.php'; ?> </div> <div class="block" id="desc"> <p><?php $theme->colophon(); ?></p> </div> <div class="block" id="menu"> <h3>Pages</h3> <ul> <li><a href="<?php Site::out_url( 'habari' ); ?>" title="<?php Options::out( 'title' ); ?>">Home</a></li> <?php foreach ( $pages as $tab ) { ?> <li><a href="<?php echo $tab->permalink; ?>" title="<?php echo $tab->title; ?>"><?php echo $tab->title; ?></a></li> <?php } if ( $loggedin ) { ?> <li><a href="<?php Site::out_url( 'admin' ); ?>" title="Admin area">Admin</a></li> <?php } ?> </ul> </div> <?php $theme->flickrfeed(); ?> <?php $theme->switcher(); ?> <div class="block" id="recent_comments"> <h3>Recent comments</h3> <ul> <?php foreach($recent_comments as $recent_comment): ?> <li><span class="user"><a href="<?php echo $recent_comment->url; ?>"><?php echo $recent_comment->name; ?></a></span> on <a href="<?php echo $recent_comment->post->permalink; ?>"><?php echo $recent_comment->post->title; ?></a></li> <?php endforeach; ?> </ul> </div> <?php $theme->twitter (); ?> <?php $theme->show_blogroll(); ?> <div class="block" id="recent_posts"> <h3>Recent posts</h3> <ul> <?php foreach($recent_posts as $recent_post): ?> <li><a href="<?php echo $recent_post->permalink; ?>"><?php echo $recent_post->title; ?></a></li> <?php endforeach; ?> </ul> </div> <div class="block" id="login"> <h3>User</h3> <?php include 'loginform.php'; ?> </div> <?php Plugins::act( 'theme_sidebar_bottom' ); ?> </div> <div id="content"> <h1 id="blog_title"><a href="<?php Site::out_url( 'habari' ); ?>"><?php Options::out( 'title' ); ?></a></h1> <file_sep><!-- footer --> <div id="footer" class="push-4 span-16"> <?php Options::out('title'); _e(' is powered by'); ?> <a href="http://www.habariproject.org/" title="Habari">Habari</a> &mdash; <a href="http://stygiandaze.com/" title="sd">Lace by sd</a> </div> <!-- /footer --><file_sep><?php $theme->display( 'header'); ?> <?php foreach( $posts as $post ) { ?> <div class="entry span-24"> <div class="left column span-6 first"> &nbsp; </div> <div class="center column span-13"> <?php if( !in_array( 'quote', $post->tags ) ) { ?> <h2><?php echo $post->title_out; ?></h2> <?php } ?> <?php echo $post->content_out; ?> </div> <div class="right column span-5 last"> <h2><a href="<?php echo $post->permalink; ?>" rel="bookmark" title='<?php echo $post->title; ?>'><img src="<?php Site::out_url( 'theme' ); ?>/images/types/entry.png" alt="entry"><?php echo $post->pubdate_out; ?></a></h2> <span class="comments"> <a href="<?php echo $post->permalink; ?>#comments" title="Comments on this post" ><?php echo $post->comments->approved->count; ?> <?php echo _n( 'Comment', 'Comments', $post->comments->approved->count ); ?></a> </span> </div> </div> <?php } ?> <?php $theme->display( 'footer'); ?><file_sep>(function () { $(document).ready(function () { $('#pubdate').after('<input type="text" id="pubdatejs" name="pubdatejs" class="styledformelement">'); $('#pubdatejs').after('<span id="pubdate_preview" type="text" class="empty" style="margin-left: 10px;"></span>'); $('#pubdate').hide(); var messages = ''; var input = $("#pubdatejs"); var date_string = $("#pubdate_preview"); var date_parsed = $("#pubdate"); var date = null; var input_empty = "Enter your pubdate date"; var empty_string = ""; input.val(input_empty); date_string.text(empty_string); date_parsed.text(empty_string); input.keyup( function (e) { date_string.removeClass(); date_parsed.removeClass(); if (input.val().length > 0) { date = Date.parse(input.val()); if (date !== null) { input.removeClass(); date_string.text(date.toString("dddd, MMMM dd, yyyy h:mm:ss tt")); date_parsed.val(date.toString("yyyy-MM-dd HH:mm:ss")); } else { // } } else { date_string.text(empty_string).addClass("empty"); date_parsed.text(empty_string).addClass("empty"); } } ); input.focus( function (e) { if (input.val() === input_empty) { input.val(""); } } ); input.blur( function (e) { if (input.val() === "") { input.val(input_empty).removeClass(); } } ); }); }());<file_sep><?php /** * DeliciousFeed Plugin: Show the posts from Delicious feed */ class DeliciousFeed extends Plugin { private static function default_options( ) { return array( 'user_id' => '', 'bookmark_tags' => '', 'bookmark_count' => '15', 'cache_expiry' => 1800 ); } public function action_block_form_deliciousfeed( $form, $block ) { // Load defaults foreach ( self::default_options( ) as $k => $v ) { if ( !isset( $block->$k ) ) $block->$k = $v; } $form->append( 'text', 'user_id', $block, _t( 'Delicious Username', 'deliciousfeed' ) ); $form->user_id->add_validator( 'validate_username' ); $form->user_id->add_validator( 'validate_required' ); $form->append( 'text', 'bookmark_tags', $block, _t( 'Tags (seperate by space)', 'deliciousfeed' ) ); $form->append( 'text', 'bookmark_count', $block, _t( '&#8470; of Posts', 'deliciousfeed' ) ); $form->bookmark_count->add_validator( 'validate_uint' ); $form->bookmark_count->add_validator( 'validate_required' ); $form->append( 'text', 'cache_expiry', $block, _t( 'Cache Expiry (in seconds)', 'deliciousfeed' ) ); $form->cache_expiry->add_validator( 'validate_uint' ); $form->cache_expiry->add_validator( 'validate_required' ); } public function validate_username( $username ) { if ( preg_match( '/[A-Za-z0-9._]+/', $username ) === false ) { return array( _t( 'Your Delicious username is not valid.', 'deliciousfeed' ) ); } return array( ); } public function validate_uint( $value ) { if ( !ctype_digit( $value ) || strstr( $value, '.' ) || $value < 0 ) { return array( _t( 'This field must be positive integer.', 'deliciousfeed' ) ); } return array( ); } private static function build_api_url( $block ) { $url = 'http://feeds.delicious.com/v2/json/' . $block->user_id; if ( $block->bookmark_tags ) { $url .= '/' . urlencode( $block->bookmark_tags ); } $url .= '?count=' . $block->bookmark_count; return $url; } private static function get_external_content( $url ) { // Get JSON content via Delicious API $call = new RemoteRequest( $url ); $call->set_timeout( 5 ); $result = $call->execute( ); if ( Error::is_error( $result ) ) { throw new Exception( _t( 'Unable to contact Delicious.', 'deliciousfeed' ) ); } return $call->get_response_body( ); } private static function parse_data( $block, $data ) { // Decode JSON $feed = json_decode( $data ); if ( !is_array( $feed ) ) { // Response is not JSON throw new Exception( _t( 'Response is not correct, maybe Delicious server is down or API is changed.', 'deliciousfeed' ) ); } else { $deliciousfeed = array( ); foreach( $feed as $i => $link ) { $delicious_post = new DeliciousPost( $link ); $deliciousfeed[ ] = $delicious_post; } } return $deliciousfeed; } public function action_block_content_deliciousfeed( $block, $theme ) { // Load defaults foreach ( self::default_options( ) as $k => $v ) { if ( !isset( $block->$k ) ) $block->$k = $v; } $cache_name = 'deliciousfeed_' . md5( serialize( array( $block->user_id, $block->bookmark_tags, $block->bookmark_count, ) ) ); if ( $block->user_id != '' ) { if ( Cache::has( $cache_name ) ) { $block->bookmarks = Cache::get( $cache_name ); } else { try { $url = self::build_api_url( $block ); $data = self::get_external_content( $url ); $bookmarks = self::parse_data( $block, $data ); $block->bookmarks = $bookmarks; // Do cache Cache::set( $cache_name, $block->bookmarks, $block->cache_expiry ); } catch ( Exception $e ) { $block->error = $e->getMessage( ); } } } else { $block->error = _t( 'DeliciousFeed Plugin is not configured properly.', 'deliciousfeed' ); } } /** * On plugin init, add the template included with this plugin to the available templates in the theme */ public function action_init( ) { $this->load_text_domain( 'deliciousfeed' ); $this->add_template( 'block.deliciousfeed', dirname( __FILE__ ) . '/block.deliciousfeed.php' ); } public function filter_block_list( $block_list ) { $block_list[ 'deliciousfeed' ] = _t( 'DeliciousFeed', 'deliciousfeed' ); return $block_list; } } class DeliciousPost { public $data = array( ); public function __construct( stdClass $data ) { foreach( $data as $name => $value ) { $this->data[ $name ] = $value; } } public function __get( $name ) { switch ( $name ) { case 'url': return $this->data[ 'u' ]; break; case 'title': return htmlspecialchars( $this->data[ 'd' ] ); break; case 'desc': return htmlspecialchars( $this->data[ 'n' ] ); break; case 'tags': return htmlspecialchars( $this->data[ 't' ] ); break; case 'tags_text': return htmlspecialchars( implode( ' ', $this->data[ 't' ] ) ); break; case 'timestamp': return $this->data[ 'dt' ]; break; default: return FALSE; break; } } public function __set( $name, $value ) { $this->data[ $name ] = $value; return $this->data[ $name ]; } } ?> <file_sep><div> <label class="hidden" for="<?php echo $field; ?>"><?php echo $this->caption; ?></label> <textarea id="<?php echo $field; ?>" class="commentbox" <?php echo "rows=\"" . ( isset( $rows ) ? $rows : 10 ) . "\" cols=\"" . ( isset( $cols ) ? $cols : 100 ). "\""; if ( isset( $tabindex ) ) { ?> tabindex="<?php echo $tabindex; ?>"<?php } ?>> <?php echo htmlspecialchars( $value ); ?></textarea> <?php if ( $message != '' ) : ?> <p class="error"><?php echo $message; ?></p> <?php endif; ?> </div> <file_sep><?php /* * Monthly Archives Plugin * Usage: <?php $theme->monthly_archives(); ?> * * Modified / fixed from the original by <NAME> (a.k.a. tinyau): http://blog.tinyau.net * http://blog.tinyau.net/archives/2007/09/22/habari-rn-monthly-archives-plugin */ class Monthly_Archives extends Plugin { const VERSION= '0.9'; private $monthly_archives= ''; // stores the actual archives list private $config= array(); // stores our config options private $cache_expiry= 604800; // one week, in seconds: 60 * 60 * 24 * 7 public function info ( ) { return array( 'name' => 'Monthly Archives', 'url' => 'http://habariproject.org', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org', 'version' => self::VERSION, 'description' => 'Shows archives grouped by month.', 'license' => 'Apache License 2.0' ); } public function action_update_check ( ) { Update::add( 'MonthlyArchives', '726F35A4-16C2-11DD-AF4E-A64656D89593', self::VERSION ); } public function action_plugin_deactivation ( $file = '' ) { if ( Plugins::id_from_file( $file ) == Plugins::id_from_file( __FILE__ ) ) { $class_name= strtolower( get_class( $this ) ); // dump our cached list Cache::expire( $class_name . ':list' ); } } public function __get( $name ) { $options= array( 'num_month' => 'archives__num__month', 'display_month' => 'archives__display__month', 'show_count' => 'archives__show__count', 'detail_view' => 'archives__detail__view', 'delimiter' => 'archives__delimiter' ); return Options::get( $options[$name] ); } public function filter_plugin_config ( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions[]= _t( 'Configure' ); } return $actions; } /* * Rebuilds the archives structure when a post is updated. * @todo Perhaps this should be a cron. With lots of posts, it could take longer than we'd like to wait. */ public function action_post_update_after ( ) { $this->update_cache(); } /* * Rebuilds the archives structure when a post is published. * @todo Perhaps this should be a cron. With lots of posts, it could take longer than we'd like to wait. */ public function action_post_insert_after ( ) { $this->update_cache(); } private function update_cache ( ) { $archives= $this->get_monthly_archives(); $class_name= strtolower( get_class( $this ) ); Cache::set( $class_name . ':list', $archives, $this->cache_expiry ); $this->monthly_archives= $archives; } public function theme_get_monthly_archives ( ) { return $this->get_monthly_archives(); } protected function get_monthly_archives ( ) { set_time_limit( ( 5 * 60 ) ); if ( !empty( $this->num_month ) ) { $limit= 'LIMIT 0, ' . $this->num_month; } else { $limit= ''; } $q= 'SELECT YEAR( p.pubdate ) AS year, MONTH( p.pubdate ) AS month, COUNT( p.id ) AS cnt FROM ' . DB::table( 'posts' ) . ' p WHERE p.content_type = ? AND p.status = ? GROUP BY year, month ORDER BY p.pubdate DESC ' . $limit; $p[]= Post::type( 'entry' ); $p[]= Post::status( 'published' ); $results= DB::get_results( $q, $p ); if ( empty( $results ) ) { $archives[]= '<ul id="monthly_archives">'; $archives[]= ' <li>No Archives Found</li>'; $archives[]= '</ul>'; } else { $archives[]= '<ul id="monthly_archives">'; foreach ( $results as $result ) { // make sure the month has a 0 on the front, if it doesn't $result->month= str_pad( $result->month, 2, 0, STR_PAD_LEFT ); $result->month_ts= mktime( 0, 0, 0, $result->month ); // what format do we want to show the month in? switch ( $this->display_month ) { // Full name case 'F': $result->display_month= date( 'F', $result->month_ts ); break; // Abbreviation case 'A': $result->display_month= date( 'M', $result->month_ts ); break; // Number case 'N': default: $result->display_month= $result->month; break; } // do we want to show the count of posts? if ( $this->show_count == 'Y' ) { $result->the_count= ' (' . $result->cnt . ')'; } else { $result->the_count= ''; } $archives[]= ' <li>'; $archives[]= ' <a href="' . URL::get( 'display_entries_by_date', array( 'year' => $result->year, 'month' => $result->month ) ) . '" title="View entries in ' . $result->display_month . '/' . $result->year . '">' . $result->display_month . ' ' . $result->year . '</a>' . $result->the_count; // do we want to show all the posts as well? if ( $this->detail_view == 'Y' ) { $psts= Posts::get( array( 'content_type' => Post::type( 'entry' ), 'status' => Post::status( 'published' ), 'year' => $result->year, 'month' => $result->month, 'nolimit' => true ) ); if ( $psts ) { $archives[]= ' <ul class="archive_entry">'; foreach ( $psts as $pst ) { $day= date( 'd', strtotime( $pst->pubdate ) ); if ( empty( $this->delimiter ) ) { $delimiter= '&nbsp;&nbsp;'; } else { $delimiter= $this->delimiter; } $archives[]= ' <li>'; $archives[]= ' ' . $day . $delimiter . '<a href="' . $pst->permalink . '" title="View ' . $pst->title . '">' . $pst->title . '</a>'; $archives[]= ' </li>'; } $archives[]= ' </ul>'; } } $archives[]= ' </li>'; } $archives[]= '</ul>'; } return implode( "\n", $archives ); } public function action_plugin_ui ( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { if ( $action == _t( 'Configure' ) ) { $class_name= strtolower( get_class( $this ) ); $form= new FormUI( $class_name ); $form->append( 'text', 'num_month', 'archives__num__month', _t( 'Number of most recent months to be shown (Blank for show all)' ) ); $form->append( 'select', 'display_month', 'archives__display__month', _t( 'Month displayed as' ) ); $form->display_month->options= array( '' => '', 'F' => 'Full name', 'A' => 'Abbreviation', 'N' => 'Number' ); $form->append( 'select', 'show_count', 'archives__show__count', _t( 'Show Monthly Entries Count?' ) ); $form->show_count->options= array( '' => '', 'Y' => 'Yes', 'N' => 'No' ); $form->show_count->add_validator( 'validate_required' ); $form->append( 'select', 'detail_view', 'archives__detail__view', _t( 'Detail View?' ) ); $form->detail_view->options= array( '' => '', 'Y' => 'Yes', 'N' => 'No' ); $form->detail_view->add_validator( 'validate_detail_view' ); $form->append( 'text', 'delimiter', 'archives__delimiter', _t( 'Delimiter to separate day and post title in detail view (optional)' ) ); $form->delimiter->add_validator( 'validate_delimiter' ); $form->append( 'submit', 'save', _t( 'Save' ) ); $form->on_success( array( $this, 'updated_config' ) ); $form->out(); } } } public function updated_config ( $form ) { // Save the form data so it's used in the cached data we're about to generate $form->save(); // when the config has been updated, we need to update our cache - things could have changed $this->update_cache(); } public function filter_validate_detail_view ( $valid, $value ) { if ( empty( $value ) || $value == '' ) { return array( _t( 'A value for this field is required. ' ) ); } Options::set('archives__detail__view', $value); return array(); } public function theme_monthly_archives ( $theme ) { $class_name= strtolower( get_class( $this ) ); // first, see if we have the list already cached if ( Cache::has( $class_name . ':list' ) ) { $this->monthly_archives= Cache::get( $class_name . ':list' ); return $this->monthly_archives; } else { // update the cache $this->update_cache(); return $this->monthly_archives; } } } ?> <file_sep><?php include 'header.php'; ?> <!-- search --> <div id="content"> <?php if ( $posts ): ?> <h3>Search Results for '<?php echo htmlspecialchars( $criteria ); ?>'</h3> <div class="post-info">Did you find what you wanted?</div> <?php foreach ( $posts as $post ): ?> <div id="post-<?php echo $post->id; ?>" class="<?php echo $post->statusname; ?>"> <div class="post"> <p class="post-date"><?php echo $post->pubdate_out; ?></p> <div class="post-info"> <h2 class="post-title"> <a href="<?php echo $post->permalink; ?>" title="<?php echo $post->title; ?>"> <?php echo $post->title_out; ?> </a> </h2> Posted by <?php echo $post->author->username; ?> <?php if ( is_array( $post->tags ) ) : ?> <span class="entry-tags"><?php echo ' tagged ' . $post->tags_out; ?></span> <?php endif; ?> <?php if ( $loggedin ) : ?> <span class="entry-edit"> <a href="<?php echo $post->editlink; ?>" title="Edit post"> (edit)</a> </span> <?php endif; ?><br/> <?php if ( $post->content_type == Post::type('entry') ): ?> <span class="commentslink"> <a href="<?php echo $post->permalink; ?>" title="Comments on this post"><?php echo $post->comments->approved->count; ?> <?php echo _n( 'Comment', 'Comments', $post->comments->approved->count ); ?> </a> </span> <?php endif; ?> </div> <!-- post-info --> <div class="postentry"> <?php echo $post->content_excerpt; ?> </div> <!-- .post-content --> </div> <!-- .post --> </div> <!-- #post-id .status --> <?php endforeach; ?> <div class="navigation"> Page: <?php $theme->page_selector(); ?> </div> <?php else: ?> <h2 class="center">Not Found</h2> <p><?php _e('Sorry, no posts matched your criteria.'); ?></p> <?php endif; ?> </div> <!-- #content --> <?php include 'sidebar.php'; ?> <!-- /entry.single --> <?php include 'footer.php'; ?> <file_sep>(function($){ $(function(){ // Energize Breezy Archives $("#breezyarchives").addClass("energized"); // Create spinner $(document.body).append('<div id="breezyarchives-indicator"></div>'); var spinner = { start: function() { $("#breezyarchives-indicator").spinner({height:32,width:32,speed:50,image:"<?php echo $spinner_img; ?>"}); $("#breezyarchives-indicator").show(); }, stop: function() { $("#breezyarchives-indicator").spinner("stop"); $("#breezyarchives-indicator").hide(); } } var bapos = $("#breezyarchives").position(); $("#breezyarchives-indicator").css({position:"absolute",top:bapos.top,left:bapos.left+$("#breezyarchives").width()-32}) // Do this when click Next/Previous function pagination(){ var ul = $(this).parent().parent(); $.ajax({ url: $(this).attr("href"), beforeSend: function(){ spinner.start(); }, success: function(response){ ul.replaceWith(response); }, complete: function(){ spinner.stop(); $("#breezyarchives li.pagination a").click(pagination); } }); return false; } $("#breezyarchives li.type > h3,#breezy-chronology-archive li.year > a,#breezy-chronology-archive li.month > a,#breezy-taxonomy-archive li.tag > a").click(function(){ $(this).parent().siblings().removeClass("selected").find("ul:first").hide(); $(this).parent().addClass("selected").find("ul:first").show(); return false; }); $("#breezy-chronology-archive li.month > a,#breezy-taxonomy-archive li.tag > a").one("click", function(){ var link = $(this); $.ajax({ url: link.attr("href").replace("<?php echo $habari_url; ?>", "<?php echo $habari_url . $class_name; ?>/"), beforeSend: function(){ spinner.start(); }, success: function(response){ link.parent().append(response); }, complete: function(){ spinner.stop(); $("#breezyarchives li.pagination a").click(pagination); } }); }); $("#breezyarchives li.type > h3:first,#breezy-chronology-archive li.year > a:first,#breezy-chronology-archive li.month > a:first").click(); }); })(jQuery);<file_sep><?php if (empty($post2date)) { $prevpost = $posts->ascend($post); if (empty($prevpost)) { $post1date = date('Y-m-d'); } else { $post1date = $prevpost->pubdate->format('Y-m-d'); } } else { $post1date = $post2date; } $post2date = $post->pubdate->format('Y-m-d'); /*$theme->flickrfill( $post1date, $post2date );*/ ?><file_sep> <div id="bottom"> <div class="column"> <h3>Recent Comments</h3> <?php $theme->show_recentcomments(); ?> </div> <div class="column"> <h3>Monthly Archives</h3> <?php $theme->monthly_archives(5, 'N'); ?> <a href="<?php Site::out_url( 'habari' ); ?>/archives">More...</a> </div> <div class="column"> <h3>Tags</h3> <?php $theme->tag_cloud(5); ?> <a href="<?php Site::out_url( 'habari' ); ?>/tag">More...</a> </div> <br> <div id="footer"> <p>&copy; Copyright 2002 - <?php echo date('Y');?>. All Rights Reserved. Subscribe to <a href="<?php URL::out( 'atom_feed', array( 'index' => '1' ) ); ?>">Entries</a> or <a href="<?php URL::out( 'atom_feed_comments', array( 'index' => '1' ) ); ?>">Comments</a></p> </div> </div> </body> <?php $theme->footer(); ?> </html><file_sep><?php /** * TermMenus * * @todo add domain to all _t() calls * @todo style everything so it looks good */ class TermMenus extends Plugin { // define values to be stored as $object_id in Terms of type 'menu' private $item_types = array( 'url' => 0, 'spacer' => 1, // a spacer is an item that goes nowhere. ); public function __get($name) { switch ( $name ) { case 'vocabulary': if ( !isset($this->_vocabulary) ) { $this->_vocabulary = Vocabulary::get(self::$vocabulary); } return $this->_vocabulary; } } /** * Create an admin token for editing menus **/ public function action_plugin_activation($file) { // create default access token ACL::create_token( 'manage_menus', _t( 'Manage menus', 'termmenus' ), 'Administration', false ); $group = UserGroup::get_by_name( 'admin' ); $group->grant( 'manage_menus' ); // register a menu type Vocabulary::add_object_type( 'menu' ); } /** * Register the templates - one for the admin page, the other for the block. **/ public function action_init() { $this->add_template( 'menus_admin', dirname( __FILE__ ) . '/menus_admin.php' ); $this->add_template( 'menu_iframe', dirname( __FILE__ ) . '/menu_iframe.php' ); $this->add_template( 'block.menu', dirname( __FILE__ ) . '/block.menu.php' ); // formcontrol for tokens $this->add_template( 'text_tokens', dirname( __FILE__ ) . '/formcontrol_tokens.php' ); } /** * Remove the admin token **/ public function action_plugin_deactivation( $file ) { // delete default access token ACL::destroy_token( 'manage_menus' ); // delete menu vocabularies that were created $vocabs = DB::get_results( 'SELECT * FROM {vocabularies} WHERE name LIKE "menu_%"', array(), 'Vocabulary' ); foreach( $vocabs as $vocab ) { // This should only delete the ones that are menu vocabularies, unless others have been named 'menu_xxxxx' $vocab->delete(); } // delete blocks that were created $blocks = DB::get_results( 'SELECT * FROM {blocks} WHERE type = "menu"', array(), 'Block') ; foreach( $blocks as $block ) { $block->delete(); } } /** * Add to the list of possible block types. **/ public function filter_block_list($block_list) { $block_list['menu'] = _t( 'Menu', 'termmenus' ); return $block_list; } /** * Produce the form to configure a menu **/ public function action_block_form_menu( $form, $block ) { $form->append('select', 'menu_taxonomy', $block, _t( 'Menu Taxonomy', 'termmenus' ), $this->get_menus( true ) ); $form->append('checkbox', 'div_wrap', $block, _t( 'Wrap each menu link in a div', 'termmenus' ) ); $form->append('text', 'list_class', $block, _t( 'Custom class for the tree ordered list element', 'termmenus' ) ); } /** * Populate the block with some content **/ public function action_block_content_menu( $block, $theme ) { $vocab = Vocabulary::get_by_id($block->menu_taxonomy); $block->vocabulary = $vocab; if($block->div_wrap) { $wrapper = '<div>%s</div>'; } else { $wrapper = '%s'; } // preprocess some things $tree = $vocab->get_tree(); $block->content = Format::term_tree( $tree, //$vocab->get_tree(), $vocab->name, array( //'linkcallback' => array($this, 'render_menu_link'), 'itemcallback' => array($this, 'render_menu_item'), 'linkwrapper' => $wrapper, 'treeattr' => array( 'class' => $block->list_class, ), 'theme' => $theme, ) ); } /** * Add menus to the publish form **/ public function action_form_publish ( $form, $post ) { $menus = $this->get_menus(); $menulist = array(); foreach($menus as $menu) { $menulist[$menu->id] = $menu->name; } $settings = $form->publish_controls->append( 'fieldset', 'menu_set', _t( 'Menus', 'termmenus' ) ); $settings->append( 'checkboxes', 'menus', 'null:null', _t( 'Menus', 'termmenus' ), $menulist ); // If this is an existing post, see if it has categories already if ( 0 != $post->id ) { // Get the terms associated to this post $object_terms = Vocabulary::get_all_object_terms( 'post', $post->id ); $menu_ids = array_keys( $menulist ); $value = array(); // if the term is in a menu vocab, enable that checkbox foreach( $object_terms as $term ) { if( in_array( $term->vocabulary_id, $menu_ids ) ) { $value[] = $term->vocabulary_id; } } $form->menus->value = $value; } } /** * Process menus when the publish form is received * **/ public function action_publish_post( $post, $form ) { // might not hurt to turn this into a function to be more DRY $term_title = $post->title; $selected_menus = $form->menus->value; foreach( $this->get_menus() as $menu ) { if(in_array( $menu->id, $selected_menus ) ) { $terms = $menu->get_object_terms( 'post', $post->id ); if( count( $terms ) == 0 ) { $term = new Term(array( 'term_display' => $post->title, 'term' => $post->slug, )); $menu->add_term( $term ); $menu->set_object_terms( 'post', $post->id, array( $term->term ) ); } } } } /** * Add creation and management links to the main menu * **/ public function filter_adminhandler_post_loadplugins_main_menu( $menu ) { // obtain existing last submenu item $last_used = end( $menu[ 'create' ][ 'submenu' ]); // add a menu item at the bottom $menu[ 'create' ][ 'submenu' ][] = array( 'title' => _t( 'Create a new Menu', 'termmenus' ), 'url' => URL::get( 'admin', array( 'page' => 'menus', 'action' => 'create' ) ), 'text' => _t( 'Menu', 'termmenus' ), 'hotkey' => $last_used[ 'hotkey' ] + 1, // next available hotkey is last used + 1 ); $last_used = end( $menu[ 'manage' ][ 'submenu' ]); $menu[ 'manage' ][ 'submenu' ][] = array( 'title' => _t( 'Manage Menus', 'termmenus' ), 'url' => URL::get( 'admin', 'page=menus' ), // might as well make listing the existing menus the default 'text' => _t( 'Menus', 'termmenus' ), 'hotkey' => $last_used[ 'hotkey' ] + 1, ); return $menu; } /** * Handle GET and POST requests * **/ public function alias() { return array( 'action_admin_theme_get_menus' => 'action_admin_theme_post_menus', 'action_admin_theme_get_menu_iframe' => 'action_admin_theme_post_menu_iframe', ); } /** * Restrict access to the admin page * **/ public function filter_admin_access_tokens( array $require_any, $page ) { switch ( $page ) { case 'menu_iframe': case 'menus': $require_any = array( 'manage_menus' => true ); break; } return $require_any; } /** * Minimal modal forms * **/ public function action_admin_theme_get_menu_iframe( AdminHandler $handler, Theme $theme ) { $action = isset($_GET[ 'action' ]) ? $_GET[ 'action' ] : 'list'; $form_action = URL::get( 'admin', array( 'page' => 'menu_iframe', 'menu' => $handler->handler_vars[ 'menu' ], 'action' => $action ) ); switch( $action ) { case 'create_link': $form = new FormUI( 'create_link' ); $form->class[] = 'tm_db_action'; $form->append( 'text', 'link_name', 'null:null', _t( 'Link Title', 'termmenus' ) ) ->add_validator( 'validate_required', _t( 'A name is required.', 'termmenus' ) ); $form->append( 'text', 'link_url', 'null:null', _t( 'Link URL', 'termmenus' ) ) ->add_validator( 'validate_required' ) ->add_validator( 'validate_url', _t( 'You must supply a valid URL.', 'termmenus' ) ); $form->append( 'hidden', 'menu' )->value = $handler->handler_vars[ 'menu' ]; $form->append( 'submit', 'submit', _t( 'Add link', 'termmenus' ) ); $form->on_success( array( $this, 'create_link_form_save' ) ); $form->set_option( 'form_action', $form_action ); break; case 'create_spacer': $form = new FormUI( 'create_spacer' ); $form->class[] = 'tm_db_action'; $form->append( 'text', 'spacer_text', 'null:null', _t( 'Item text (leave blank for blank space)', 'termmenus' ) ); $form->append( 'hidden', 'menu' )->value = $handler->handler_vars[ 'menu' ]; $form->append( 'submit', 'submit', _t( 'Add spacer', 'termmenus' ) ); $form->on_success( array( $this, 'create_spacer_form_save' ) ); $form->set_option( 'form_action', $form_action ); break; case 'link_to_posts': $form = new FormUI( 'link_to_posts' ); $form->class[] = 'tm_db_action'; $post_ids = $form->append( 'text', 'post_ids', 'null:null', _t( 'Posts', 'termmenus' ) ); $post_ids->template = 'text_tokens'; $post_ids->ready_function = "$('#{$post_ids->field}').tokenInput( habari.url.ajaxPostTokens )"; $form->append( 'hidden', 'menu' )->value = $handler->handler_vars[ 'menu' ]; $form->append( 'submit', 'submit', _t( 'Add post(s)', 'termmenus' ) ); $form->on_success( array( $this, 'link_to_posts_form_save' ) ); $form->set_option( 'form_action', $form_action ); break; } $form->properties['onsubmit'] = "$.post($('#{$action}').attr('action'), $('.tm_db_action').serialize(), function(data){\$('#menu_popup').html(data);});return false;"; $theme->page_content = $form->get(); if(isset($_GET['result'])) { switch($_GET['result']) { case 'added': $treeurl = URL::get('admin', array('page' => 'menus', 'menu' => $handler->handler_vars[ 'menu' ], 'action' => 'edit')) . ' #edit_menu>*'; $msg = _t('Menu item added.'); $theme->page_content .= <<< JAVSCRIPT_RESPONSE <script type="text/javascript"> human_msg.display_msg('{$msg}'); $('#edit_menu').load('{$treeurl}'); </script> JAVSCRIPT_RESPONSE; } } $theme->display( 'menu_iframe' ); exit; } /** * Prepare and display admin page * **/ public function action_admin_theme_get_menus( AdminHandler $handler, Theme $theme ) { $theme->page_content = ''; $action = isset($_GET[ 'action' ]) ? $_GET[ 'action' ] : 'list'; switch( $action ) { case 'edit': $vocabulary = Vocabulary::get_by_id( intval( $handler->handler_vars[ 'menu' ] ) ); if ( $vocabulary == false ) { $theme->page_content = _t( '<h2>Invalid Menu.</h2>', 'termmenus' ); // that's it, we're done. Maybe we show the list of menus instead? break; } $top_url = URL::get( 'admin', 'page=menus' ); $theme->page_content = _t( "<h2><a href='$top_url'>Menus</a>: Editing <b>{$vocabulary->name}</b></h2><hr>", 'termmenus' ); $form = new FormUI( 'edit_menu' ); if ( !$vocabulary->is_empty() ) { $form->append( 'tree', 'tree', $vocabulary->get_tree(), _t( 'Menu', 'termmenus') ); $form->tree->config = array( 'itemcallback' => array( $this, 'tree_item_callback' ) ); // $form->tree->value = $vocabulary->get_root_terms(); // append other needed controls, if there are any. $form->append( 'submit', 'save', _t( 'Apply Changes', 'termmenus' ) ); } else { $form->append( 'static', 'message', _t( '<h3>No links yet.</h3>', 'termmenus' ) ); } $edit_items = '<div class="edit_menu_dropbutton"><ul class="dropbutton">' . '<li><a class="modal_popup_form" href="' . URL::get('admin', array( 'page' => 'menu_iframe', 'action' => 'link_to_posts', 'menu' => $vocabulary->id, ) ) . '">' . _t( 'Link to post(s)', 'termmenus' ) . '</a></li>' . '<li><a class="modal_popup_form" href="' . URL::get('admin', array( 'page' => 'menu_iframe', 'action' => 'create_link', 'menu' => $vocabulary->id, ) ) . '">' . _t( 'Add a link URL', 'termmenus' ) . '</a></li>' . '<li><a class="modal_popup_form" href="' . URL::get('admin', array( 'page' => 'menu_iframe', 'action' => 'create_spacer', 'menu' => $vocabulary->id, ) ) . '">' . _t( 'Add a spacer', 'termmenus' ) . '</a></li>' . '</ul></div><script type="text/javascript">' . '$("a.modal_popup_form").click(function(){$("#menu_popup").load($(this).attr("href")).dialog({title:$(this).text()}); return false;});</script>'; $theme->page_content .= $form->get() . $edit_items; break; case 'create': $form = new FormUI('create_menu'); $form->append('text', 'menuname', 'null:null', _t( 'Menu Name', 'termmenus' ) ) ->add_validator('validate_required', _t( 'You must supply a valid menu name', 'termmenus' ) ) ->add_validator(array($this, 'validate_newvocab') ); $form->append('submit', 'submit', _t( 'Create Menu', 'termmenus' ) ); $form->on_success(array($this, 'add_menu_form_save') ); $theme->page_content = $form->get(); break; case 'list': $menu_list = ''; foreach ( $this->get_menus() as $menu ) { $edit_link = URL::get( 'admin', array( 'page' => 'menus', 'action' => 'edit', 'menu' => $menu->id, ) ); $menu_name = $menu->name; // @TODO _t() this line or replace it altogether $menu_list .= "<li><a href='$edit_link'><b>$menu_name</b> {$menu->description} - {$menu->count_total()} items</a></li>"; } if ( $menu_list != '' ) { $theme->page_content = _t( "<h2>Menus</h2><hr><ul>$menu_list</ul>", 'termmenus' ); } else { $edit_url = URL::get( 'admin', array( 'page' => 'menus', 'action' => 'create' ) ); $theme->page_content = _t( '<h2>No Menus have been created.</h2><hr><p><a href="$edit_url">Create a Menu</a></p>', 'termmenus' ); } break; case 'delete_term': $term = Term::get( intval( $handler->handler_vars[ 'term' ] ) ); $menu_vocab = $term->vocabulary_id; $term->delete(); // log that it has been deleted? Session::notice( _t( 'Item deleted.', 'termmenus' ) ); Utils::redirect( URL::get( 'admin', array( 'page' => 'menus', 'action' => 'edit', 'menu' => $menu_vocab ) ) ); break; case 'edit_term': $term = Term::get( intval( $handler->handler_vars[ 'term' ] ) ); $menu_vocab = $term->vocabulary_id; $term_type = ''; foreach( $term->object_types() as $object_id => $type ) { // render_menu_item() does this as a foreach. I'm assuming there's only one type here, but I could be wrong. Is there a better way? $term_type = $object_id; } $form = new FormUI( 'edit_term' ); $form->append( 'text', 'title', 'null:null', _t( 'Item Title', 'termmenus' ) ) ->add_validator( 'validate_required' ) ->value = $term->term_display; if ( $term_type == 'url' ) { $form->append( 'text', 'link_url', 'null:null', _t( 'Link URL', 'termmenus' ) ) ->add_validator( 'validate_required' ) ->add_validator( 'validate_url', _t( 'You must supply a valid URL.', 'termmenus' ) ) ->value = $term->info->url; } $form->append( 'submit', 'submit', _t( 'Apply Changes', 'termmenus' ) ); $form->on_success( array( $this, 'edit_term_form_save' ) ); $theme->page_content = $form->get(); break; /* // moved to iframe above case 'create_link': $form = new FormUI( 'create_link' ); $form->append( 'text', 'link_name', 'null:null', _t( 'Link Title', 'termmenus' ) ) ->add_validator( 'validate_required', _t( 'A name is required.', 'termmenus' ) ); $form->append( 'text', 'link_url', 'null:null', _t( 'Link URL', 'termmenus' ) ) ->add_validator( 'validate_required' ) ->add_validator( 'validate_url', _t( 'You must supply a valid URL.', 'termmenus' ) ); $form->append( 'hidden', 'menu' )->value = $handler->handler_vars[ 'menu' ]; $form->append( 'submit', 'submit', _t( 'Add link', 'termmenus' ) ); $form->on_success( array( $this, 'create_link_form_save' ) ); $theme->page_content = $form->get(); break; case 'create_spacer': $form = new FormUI( 'create_spacer' ); $form->append( 'text', 'spacer_text', 'null:null', _t( 'Item text (leave blank for blank space)', 'termmenus' ) ); $form->append( 'hidden', 'menu' )->value = $handler->handler_vars[ 'menu' ]; $form->append( 'submit', 'submit', _t( 'Add spacer', 'termmenus' ) ); $form->on_success( array( $this, 'create_spacer_form_save' ) ); $theme->page_content = $form->get(); break; case 'link_to_posts': $form = new FormUI( 'link_to_posts' ); $post_ids = $form->append( 'text', 'post_ids', 'null:null', _t( 'Posts', 'termmenus' ) ); $post_ids->template = 'text_tokens'; $post_ids->ready_function = "$('#{$post_ids->field}').tokenInput( habari.url.ajaxPostTokens )"; $form->append( 'hidden', 'menu' )->value = $handler->handler_vars[ 'menu' ]; $form->append( 'submit', 'submit', _t( 'Add post(s)', 'termmenus' ) ); $form->on_success( array( $this, 'link_to_posts_form_save' ) ); $theme->page_content = $form->get(); break; */ default: Utils::debug( $_GET, $action ); die(); } $theme->display( 'menus_admin' ); // End everything exit; } public function add_menu_form_save( $form ) { $params = array( 'name' => $form->menuname->value, 'description' => _t( 'A vocabulary for the "%s" menu', array( $form->menuname->value ), 'termmenus' ), 'features' => array( 'term_menu' ), // a special feature that marks the vocabulary as a menu ); $vocab = Vocabulary::create($params); Session::notice( _t( 'Created menu "%s".', array( $form->menuname->value ), 'termmenus' ) ); Utils::redirect( URL::get( 'admin', 'page=menus' )); } public function edit_term_form_save( $form ) { Utils::debug( $form ); } public function link_to_posts_form_save( $form ) { $menu_vocab = intval( $form->menu->value ); // create a term for the link, store the URL $menu = Vocabulary::get_by_id( $menu_vocab ); $post_ids = explode( ',', $form->post_ids->value ); foreach( $post_ids as $post_id ) { $post = Post::get( array( 'id' => $post_id ) ); $term_title = $post->title; $terms = $menu->get_object_terms( 'post', $post->id ); if( count( $terms ) == 0 ) { $term = new Term( array( 'term_display' => $post->title, 'term' => $post->slug ) ); $menu->add_term( $term ); $menu->set_object_terms( 'post', $post->id, array( $term->term ) ); } } Session::notice( _t( 'Link(s) added.', 'termmenus' ) ); Utils::redirect(URL::get( 'admin', array( 'page' => 'menu_iframe', 'action' => 'link_to_posts', 'menu' => $menu_vocab, 'result' => 'added', ) ) ); } public function create_link_form_save( $form ) { $menu_vocab = intval( $form->menu->value ); // create a term for the link, store the URL $menu = Vocabulary::get_by_id( $menu_vocab ); $term = new Term( array( 'term_display' => $form->link_name->value, 'term' => Utils::slugify( $form->link_name->value ), )); $term->info->url = $form->link_url->value; $menu->add_term( $term ); $term->associate( 'menu', $this->item_types[ 'url' ] ); Session::notice( _t( 'Link added.', 'termmenus' ) ); Utils::redirect(URL::get( 'admin', array( 'page' => 'menu_iframe', 'action' => 'create_link', 'menu' => $menu_vocab, 'result' => 'added', ) ) ); } public function create_spacer_form_save( $form ) { $menu_vocab = intval( $form->menu->value ); $menu = Vocabulary::get_by_id( $menu_vocab ); $term = new Term( array( 'term_display' => $form->spacer_text->value, 'term' => Utils::slugify( ($form->spacer_text->value !== '' ? $form->spacer_text->value : 'menu_spacer' ) ), )); $menu->add_term( $term ); $term->associate( 'menu', $this->item_types[ 'spacer' ] ); Session::notice( _t( 'Spacer added.', 'termmenus' ) ); Utils::redirect(URL::get( 'admin', array( 'page' => 'menu_iframe', 'action' => 'create_spacer', 'menu' => $menu_vocab, 'result' => 'added', ) ) ); } public function validate_newvocab( $value, $control, $form ) { if(Vocabulary::get( $value ) instanceof Vocabulary) { return array( _t( 'Please choose a vocabulary name that does not already exist.', 'termmenus' ) ); } return array(); } public function get_menus($as_array = false) { $vocabularies = Vocabulary::get_all(); $outarray = array(); foreach ( $vocabularies as $index => $menu ) { if( !$menu->term_menu ) { // check for the term_menu feature we added. unset( $vocabularies[ $index ] ); } else { if( $as_array ) { $outarray[ $menu->id ] = $menu->name; } } } if( $as_array ) { return $outarray; } else { return $vocabularies; } } /** * Provide a method for listing the types of menu items that are available * @return array List of item types, keyed by name and having integer index values **/ public function get_item_types() { return Plugins::filter( 'get_item_types', $this->item_types ); } /** * * Callback for Format::term_tree to use with $config['linkcallback'] * * @param Term $term * @param array $config * @return array $config modified with the new wrapper div **/ public function tree_item_callback( Term $term, $config ) { // coming into this, default $config['wrapper'] is "<div>%s</div>" // make the links $edit_link = URL::get( 'admin', array( 'page' => 'menus', 'action' => 'edit_term', 'term' => $term->id, ) ); $delete_link = URL::get( 'admin', array( 'page' => 'menus', 'action' => 'delete_term', 'term' => $term->id, ) ); // insert them into the wrapper // @TODO _t() this line or replace it altogether. $links = "<a class='menu_item_edit' href='$edit_link'>edit</a> <a class='menu_item_delete' title='Delete this' href='$delete_link'>delete</a>"; $config[ 'wrapper' ] = "<div>%s $links</div>"; return $config; } /** * Callback function for block output of menu list item **/ public function render_menu_item( Term $term, $config ) { $title = $term->term_display; $link = ''; $objects = $term->object_types(); $active = false; $spacer = false; foreach( $objects as $object_id => $type ) { switch( $type ) { case 'post': $post = Post::get( array( 'id' => $object_id ) ); if( $post instanceof Post ) { $link = $post->permalink; if( $config[ 'theme' ]->posts instanceof Post && $config[ 'theme' ]->posts->id == $post->id ) { $active = true; } } else { // The post doesn't exist or the user does not have access to it } break; case 'menu': $item_types = $this->get_item_types(); switch( $object_id ) { case $item_types[ 'url' ]: $link = $term->info->url; break; case $item_types[ 'spacer' ]: if ( empty( $term->term_display ) ) { $title = '&nbsp;'; } $spacer = true; // no need to break, default below is just fine. default: $link = null; $link = Plugins::filter( 'get_item_link', $link, $term, $object_id, $type ); break; } break; } } if( empty( $link ) ) { $config[ 'wrapper' ] = sprintf($config[ 'linkwrapper' ], $title); } else { $config[ 'wrapper' ] = sprintf( $config[ 'linkwrapper' ], "<a href=\"{$link}\">{$title}</a>" ); } if( $active ) { $config[ 'itemattr' ][ 'class' ] = 'active'; } else { $config[ 'itemattr' ][ 'class' ] = 'inactive'; } if( $spacer ) { $config[ 'itemattr' ][ 'class' ] .= ' spacer'; } return $config; } /** * Add required Javascript and, for now, CSS. */ public function action_admin_header( $theme ) { if ( $theme->page == 'menus' ) { // Ideally the plugin would reuse reusable portions of the existing admin CSS. Until then, let's only add the CSS needed on the menus page. Stack::add( 'admin_stylesheet', array( $this->get_url() . '/admin.css', 'screen' ), 'admin-css' ); // Load the plugin and its css Stack::add( 'admin_header_javascript', Site::get_url( 'vendor' ) . "/jquery.tokeninput.js", 'jquery-tokeninput', 'jquery.ui' ); Stack::add( 'admin_stylesheet', array( Site::get_url( 'admin_theme' ) . '/css/token-input.css', 'screen' ), 'admin_tokeninput' ); // Add the callback URL. $url = "habari.url.ajaxPostTokens = '" . URL::get( 'ajax', array( 'context' => 'post_tokens' ) ) . "';"; Stack::add( 'admin_header_javascript', $url, 'post_tokens_url', 'post_tokens' ); } } /** * Respond to Javascript callbacks * The name of this method is action_ajax_ followed by what you passed to the context parameter above. */ public function action_ajax_post_tokens( $handler ) { // Get the data that was sent $response = $handler->handler_vars[ 'q' ]; // Wipe anything else that's in the buffer ob_end_clean(); $new_response = Posts::get( array( "title_search" => $response ) ); $final_response = array(); foreach ( $new_response as $post ) { $final_response[] = array( 'id' => $post->id, 'name' => $post->title, ); } // Send the response echo json_encode( $final_response ); } } ?> <file_sep><?php class Silencer extends Plugin { /** * Required plugin information * @return array The array of information **/ public function info() { return array( 'name' => 'Silencer', 'version' => '0.01', 'url' => 'http://habariproject.org/', 'author' => 'Habari Community', 'authorurl' => 'http://habariproject.org/', 'license' => 'Apache License 2.0', 'description' => 'Disables comments for all newly published posts', 'copyright' => '2009' ); } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Silencer', 'fdb7e18c-f883-4456-a55d-b8e5c8c9ffaa', $this->info->version ); } /** * Add help text to plugin configuration page **/ public function help() { $help = _t( 'Once this is enabled, "Comments Allowed" will be deselected in the settings of all newly published posts and pages.' ); return $help; } /** **/ public function action_plugin_activation( $file ) { if(Plugins::id_from_file($file) == Plugins::id_from_file(__FILE__)) { // for now, do nothing. Someday global postinfo changes may go here. } } /** * Update the setting prior to displaying the form. **/ public function action_form_publish( $form, $post, $context ) { $form->settings->comments_enabled->value = false; } } ?> <file_sep><?php class NoWebsites extends Plugin { /** * Check comment for honeypot field and qualify as spam accordingly * * @param float $spam_rating The spamminess of the comment as detected by other plugins * @param Comment $comment The submitted comment object * @param array $handlervars An array of handlervars passed in via the comment submission URL * @param array $extra An array of all fields passed to the comment form * @return float The original spam rating */ function filter_spam_filter( $spam_rating, $comment, $handlervars, $extra ) { // This plugin ignores non-comments if( $comment->type != Comment::COMMENT ) { return $spam_rating; } if ( isset( $comment->url ) && ! empty( $comment->url ) ) { // mark as spam. $comment->status = Comment::STATUS_SPAM; $spamcheck[] = _t( 'Website field filled.', 'nowebsites' ); } // store spamcheck reason if ( isset( $comment->info->spamcheck ) && is_array( $comment->info->spamcheck ) ) { $comment->info->spamcheck = array_unique( array_merge( $comment->info->spamcheck, $spamcheck ) ); } else { $comment->info->spamcheck = $spamcheck; } // note this just passes along the same spam rating after changing the status. return $spam_rating; } } ?> <file_sep><div class="block" id="flickr"> <div class="images clearfix"> <?php if (is_array($flickrfeed)) { foreach ($flickrfeed as $flickrimage) { printf('<a href="%1$s" title="%2$s"><img src="%3$s" alt="%4$s" /></a>', $flickrimage['url'], strip_tags($flickrimage['description_raw']), $flickrimage['image_url'], htmlspecialchars($flickrimage['title'])); } } else // Exceptions { echo '<div class="flickr-error">' . $flickrfeed . '</div>'; } ?> </div> </div><file_sep>CREATE TABLE {rateit_log} ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, post_id INT NOT NULL, rating TINYINT NOT NULL, timestamp DATETIME NOT NULL, ip INT( 10 ) NOT NULL ); CREATE UNIQUE INDEX IF NOT EXISTS post_id_ip ON {rateit_log}( post_id, ip ); <file_sep><!-- To customize this template, copy it to your currently active theme directory and edit it --> <div id="flickrfeed"> <ul> <?php if (is_array($flickrfeed)) { foreach ($flickrfeed as $flickrimage) { printf('<li class="flickr-image"><a href="%1$s" title="%2$s"><img src="%3$s" alt="%4$s" /></a></li>', $flickrimage['url'], strip_tags($flickrimage['description_raw']), $flickrimage['image_url'], htmlspecialchars($flickrimage['title'])); } } else // Exceptions { echo '<li class="flickr-error">' . $flickrfeed . '</li>'; } ?> </ul> </div><file_sep><?php /** * @package Habari * @subpackage StyleSwitcher * * For this plugin to work, you need to add each stylesheet to the stack 'template_stylesheet_with_title' * Do not put the <link> yourself in the header, unless they are vital basics. * * Place at the location you want the select list the following call: * $theme->styleswitcher() * * Example of stack calls to put in your theme's theme.php: * Stack::add( 'template_stylesheet_with_title', array( 'style.css', 'screen', 'Default' ) ); * Stack::add( 'template_stylesheet_with_title', array( 'style2.css', 'screen', 'Alternative' ) ); * */ /** * All plugins must extend the Plugin class to be recognized. */ class StyleSwitcher extends Plugin { /** * Add the Javascript file needed by this plugin to the theme's header. */ public function action_add_template_vars() { $jq_js_file = Site::get_url('scripts', TRUE) . 'jquery.js'; $ss_js_file = Site::get_url('user', TRUE) . 'plugins/' . basename(dirname(__FILE__)) . '/styleswitcher.js'; Stack::add( 'template_header_javascript', $jq_js_file, 'jquery' ); Stack::add( 'template_header_javascript', $ss_js_file, 'styleswitcher' ); } public function theme_header() { $link = '<link rel="stylesheet" type="text/css" href="' . Site::get_url('theme', true) . '%s" media="%s" title="%s">'; $output = Stack::get( 'template_stylesheet_with_title', $link."\r\n" ); return $output; } public function theme_styleswitcher() { $output = array( '<select id="styleswitcher">' ); $stacks = Stack::get_named_stack( 'template_stylesheet_with_title' ); foreach( $stacks as $stack ) { $output[]= '<option value="' . $stack[2] . '">' . $stack[2] . '</option>'; } $output[]= '</select>'; print implode( "\r\n", $output ); } } ?> <file_sep> <script src="<?php Site::out_url('habari'); ?>/user/plugins/fileman/jqueryFileTree/jqueryFileTree.js" type="text/javascript"></script> <link rel="stylesheet" href="<?php Site::out_url('habari'); ?>/user/plugins/fileman/jqueryFileTree/jqueryFileTree.css" type="text/css" /> <script type="text/javascript"> $(document).ready( function() { $('#jQueryFileTree').fileTree({ root: '<?php site::out_dir("user"); ?>/', script: '<?php Site::out_url("habari"); ?>/user/plugins/fileman/jqueryFileTree/jqueryFileTree.php', expandSpeed: 1000, collapseSpeed: 1000, multiFolder: true, loadMessage: 'Loading...' }, function(file) { window.location="?file="+file; }); $('form.fileman').submit(function(){ $.post( '<?php Site::out_url("habari"); ?>/user/plugins/fileman/save.php', 'file='+$('form.fileman input.file').val()+'&contents='+$('form.fileman textarea').val(), function(data) { $('form.fileman p.status span').html(data); } ) return false; }); }); </script> <file_sep><?php class BlogInfo extends InfoRecords { function __construct ( $blog_id ) { parent::__construct ( DB::table('blogrollinfo'), 'blog_id', $blog_id ); // call parent with appropriate parameters } } ?><file_sep> <li id="widget-admin" class="widget"> <h3><?php _e('Admin', 'demorgan'); ?></h3> <ul> <?php if ($loggedin) { ?> <li><?php printf(_t('You are logged in as %s.', 'demorgan'), '<a href="' . URL::get('admin', 'page=user&user=' . $user->username) . '" title="' . _t('Edit Your Profile', 'demorgan') . '">' . $user->username . '</a>'); ?></li> <li><a href="<?php Site::out_url('admin'); ?>"><?php _e('Admin', 'demorgan'); ?></a></li> <li><a href="<?php URL::out('user', array('page' => 'logout')); ?>"><?php _e('Logout', 'demorgan'); ?></a></li> <?php } else { ?> <li><a href="<?php URL::out('user', array('page' => 'login')); ?>"><?php _e('Login', 'demorgan'); ?></a></li> <?php } ?> </ul> </li> <file_sep><?php class ProfilerPlugin extends Plugin { /** * Display profiler information on dshboard **/ function filter_dashboard_status($statuses) { $statuses[_t('Average Page Creation Time')] = _t('%f seconds', array(Options::get('profiler_avg'))); return $statuses; } /** * Log page creation times **/ function filter_final_output($output) { global $profile_start; $pagetime = microtime(true) - $profile_start; $avgtime = Options::get('profiler_avg'); $hits = Options::get('profiler_hits'); $newavg = ($avgtime * $hits + $pagetime) / ($hits + 1); $hits++; Options::set('profiler_avg', $newavg); Options::set('profiler_hits', $hits); return $output; } /** * Add an option to reset the profiler stats **/ public function filter_plugin_config( $actions, $plugin_id ) { if ( $plugin_id == $this->plugin_id() ) { $actions['reset']= _t( 'Reset Stats' ); } return $actions; } /** * Reset the stats **/ public function action_plugin_ui( $plugin_id, $action ) { if ( $plugin_id == $this->plugin_id() ) { switch ( $action ) { case 'reset': echo '<b>' . _t('Profiler stats have been reset') . '</b>'; Options::set('profiler_avg', 0); Options::set('profiler_hits', 0); break; } } } } ?><file_sep>{hi:display:header} <div id="content"> <div id="primaryContent"> <h2 class="pageTitle">{hi:"Search results for: "}<?php echo htmlspecialchars( $criteria ); ?></h2> {hi:posts} <div class="post {hi:statusname}"> <div class="entry"> <h2><a href="{hi:permalink}" rel="bookmark" title="{hi:title}">{hi:title_out}</a></h2> <div class="entryContent"> {hi:content_excerpt} </div> </div> <div class="entryMeta"> <p>Entry Details</p> <p class="timestamp">{hi:pubdate_out}</p> <p class="author">{hi:"By"} {hi:author.displayname}</p> <p class="tags">{hi:"Tagged"}—{hi:?count(tags)}{hi:tags_out}{/hi:?}</p> <p class="comments"><a href="{hi:permalink}#comments" title="{hi:"Comments on this post"}">{hi:"{hi:comments.approved.count} Comment" "{hi:comments.approved.count} Comments" comments.approved.count}</a></p> </div> </div> <div class="clear divider"></div> {/hi:posts} </div> {hi:display:sidebar} <div id="pagenav" class="clear"> <p>{hi:@prev_page_link} {hi:@page_selector} {hi:@next_page_link} </div> </div> {hi:display:footer} <file_sep><?php class RequireSlug extends Plugin { /** * Add update beacon support **/ public function action_update_check() { Update::add( $this->info->name, 'f0c38256-b6cb-aa94-bdaf-1e156cc3d8bf', $this->info->version ); } /** * Change publish form **/ public function action_form_publish($form, $post) { $form->move_after($form->newslug, $form->content); $form->newslug->template= 'admincontrol_text'; $form->newslug->caption= _t('Slug'); } } ?><file_sep><?php class MicroID extends Plugin { function info() { return array( 'name' => 'MicroID Generator Plugin', 'version' => '1.1.1', 'url' => 'http://digitalspaghetti.me.uk/', 'author' => '<NAME> (includes code by <NAME>)', 'authorurl' => 'http://digitalspaghetti.me.uk/', 'license' => 'Apache License 2.0', 'description' => 'Generates a MicroID for services such as ClaimID. Includes generation code based on Will Norris\'s origional release.', ); } public function action_plugin_activation( $file ) { if ( realpath( $file ) == __FILE__ ) { Modules::add( 'MicroID' ); } } public function action_plugin_deactivation( $file ) { if ( realpath( $file ) == __FILE__ ) { Modules::remove_by_name( 'MicroID' ); } } function action_update_check() { Update::add( 'MicroID', '0B8CC720-9057-11DD-A39C-BA6355D89593', $this->info->version ); } function theme_header( $theme ) { if ($theme->request->display_404 == false) { $count = 0; Stack::create_stack('microid'); foreach ($theme->posts as $post) { $user = User::get_by_id($post->user_id); $microid = $this->generate('mailto:' . $user->email, $this->currentURL(true)); Stack::add('microid', $microid); $count++; } // FIXME: This seems to be a bug in Habari, where there is only one post on the page // it isn't picked up by the forloop above. if ($count == 0) { $user = User::get_by_id($theme->posts->user_id); $microid = $this->generate('mailto:' . $user->email, $this->currentURL(true)); Stack::add('microid', $microid); foreach($theme->posts->comments->moderated as $comment) { $microidc = $this->generate('mailto:' . $comment->email, $this->currentURL(true)); Stack::add('microid', $microidc); } } Stack::Out('microid', '<meta name="microid" content="%s" />'); } } function generate($identity, $service, $algorithm = 'sha1') { $microid = ""; $microid .= substr($identity, 0, strpos($identity, ':')) . "+" . substr($service, 0, strpos($service, ':')) . ":" . strtolower($algorithm) . ":"; // try message digest engine if (function_exists('hash')) { if (in_array(strtolower($algorithm), hash_algos())) { return $microid .= hash($algorithm, hash($algorithm, $identity) . hash($algorithm, $service)); } } // try mhash engine if (function_exists('mhash')) { $hash_method = @constant('MHASH_' . strtoupper($algorithm)); if ($hash_method != null) { $identity_hash = bin2hex(mhash($hash_method, $identity)); $service_hash = bin2hex(mhash($hash_method, $service)); return $microid .= bin2hex(mhash($hash_method, $identity_hash . $service_hash)); } } // direct string function if (function_exists($algorithm)) { return $microid .= $algorithm($algorithm($identity) . $algorithm($service)); } echo "MicroID: unable to find adequate function for algorithm '$algorithm'"; } function currentURL($trim) { $pageURL = 'http'; if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {$pageURL .= "s";} $pageURL .= "://"; $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; if ($trim == true) {$pageURL = rtrim($pageURL, '/');} return $pageURL; } } ?> <file_sep><?php class Register extends Plugin { const VERSION= '0.1'; /** * Return plugin metadata for this plugin * * @return array Plugin metadata */ public function info() { return array( 'url' => 'http://habariproject.org', 'name' => 'Register', 'license' => 'Apache License 2.0', 'author' => 'Habari Community', 'version' => self::VERSION, 'description' => 'Lets people register to become blog users, and be placed in a group specified by the admin.' ); } /** * Add update beacon support **/ public function action_update_check() { Update::add( 'Register', '57281af4-f709-46d0-8089-6bb327bab3e5', $this->info->version ); } /** * Add help text to plugin configuration page **/ public function help() { $help = _t( 'Lets people register to become blog users. Administrators can specify which group new users should be placed in. Registration forms can exist on their own page or can be added to an existing theme template using, for example $theme->signup(\'registered\') to add users to the \'registered\' group.'); return $help; } /** * Add the registration content type **/ public function action_plugin_activation( $plugin_file ) { if ( Plugins::id_from_file(__FILE__) == Plugins::id_from_file($plugin_file) ) { // Store a secret key for hashing group names Options::set('register_secret', UUID::get()); } } public function get_form( $group ) { $form = new FormUI('registration'); $form->class[] = 'registration'; $form->append('text', 'email', 'null:null', _t('Email'), 'formcontrol_text'); $form->email->add_validator('validate_email'); $form->append('text', 'username', 'null:null', _t('Username'), 'formcontrol_text'); $form->username->add_validator('validate_required'); $form->username->add_validator('validate_username'); $form->append('text', 'password', 'null:null', _t('Password'), 'formcontrol_text'); $form->password->add_validator('validate_required'); // Store the group to be added. This is stored locally, not retrieved from unsafe data. $form->set_option('group_name', $group); // Create the Register button $form->append('submit', 'register', _t('Register'), 'formcontrol_submit'); $form->on_success( array( $this, 'register_user' ) ); // Return the form object return $form; } public function register_user( $form ) { $group = UserGroup::get($form->get_option('group_name')); $user = new User( array( 'username' => $form->username, 'email' => $form->email, 'password' => Utils::crypt( $form->password ) ) ); if ( $user->insert() ) { $group->add($user); Session::notice( sprintf( _t( "Added user '%s'" ), $form->username ) ); } else { $dberror = DB::get_last_error(); Session::error( $dberror[2], 'adduser' ); } } public function theme_registration( $theme, $group ) { $this->get_form($group)->out(); } } ?> <file_sep>habari.media.preview.note = function(fileindex, fileobj) { return '<div class="mediatitle">' + fileobj.title + '</div><p class="mediasummary" style="width: 100px; height: 100px; color: #555555;">' + fileobj.summary + '</p>'; } habari.media.output.note = { view: function(fileindex, fileobj) { notes.key.val( fileobj.key ); notes.input.val( fileobj.content ).focus(); notes.show(); // $('#mediatabs').parent().tabs('select', -1); }, insert: function(fileindex, fileobj) { habari.editor.insertSelection(fileobj.content); } } var notes = { init: function() { notes.input = $('#notes'); notes.key = $('input[name=note_key]'); notes.container = notes.input.parents('.container'); notes.tabs = $('#mediatabs').parent(); notes.container.hide(); notes.tabs.bind('tabsselect', function(event, ui) { notes.hide(); }); notes.tabs.bind('tabsshow', function(event, ui) { // console.log(notes.tabs.tabs('option', 'selected')); if( $(ui.panel).children('#silo_simplenote').length > 0 ) { notes.show(); } }); }, show: function() { notes.container.slideDown('slow'); }, hide: function() { notes.container.slideUp('slow'); } } $(document).ready(function() { notes.init(); });<file_sep><?php /** * DeliciousFeed Plugin: Show the posts from Delicious feed * Usage: <?php $theme->deliciousfeed(); ?> */ class DeliciousFeed extends Plugin { private $config = array(); private $class_name = ''; private $default_options = array( 'user_id' => '', 'tags' => '', 'num_item' => '15', 'cache_expiry' => 1800 ); /** * Required plugin information * @return array The array of information **/ public function info() { return array( 'name' => 'DeliciousFeed', 'version' => '0.5-0.3', 'url' => 'http://code.google.com/p/bcse/wiki/DeliciousFeed', 'author' => '<NAME>', 'authorurl' => 'http://blog.bcse.info/', 'license' => 'Apache License 2.0', 'description' => 'Display your latest bookmarks on your blog.', 'copyright' => '2008' ); } /** * Add update beacon support **/ public function action_update_check() { Update::add('DeliciousFeed', 'b0a81efa-c59a-41f2-b71e-b2f41d0885f1', $this->info->version); } /** * Add actions to the plugin page for this plugin * @param array $actions An array of actions that apply to this plugin * @param string $plugin_id The string id of a plugin, generated by the system * @return array The array of actions to attach to the specified $plugin_id **/ public function filter_plugin_config($actions, $plugin_id) { if ($plugin_id === $this->plugin_id()) { $actions[] = _t('Configure', $this->class_name); } return $actions; } /** * Respond to the user selecting an action on the plugin page * @param string $plugin_id The string id of the acted-upon plugin * @param string $action The action string supplied via the filter_plugin_config hook **/ public function action_plugin_ui($plugin_id, $action) { if ($plugin_id === $this->plugin_id()) { switch ($action) { case _t('Configure', $this->class_name): $ui = new FormUI($this->class_name); $user_id = $ui->append('text', 'user_id', 'option:' . $this->class_name . '__user_id', _t('Delicious Username', $this->class_name)); $user_id->add_validator('validate_username'); $user_id->add_validator('validate_required'); $tags = $ui->append('text', 'tags', 'option:' . $this->class_name . '__tags', _t('Tags (seperate by space)', $this->class_name)); $num_item = $ui->append('text', 'num_item', 'option:' . $this->class_name . '__num_item', _t('&#8470; of Posts', $this->class_name)); $num_item->add_validator('validate_uint'); $num_item->add_validator('validate_required'); $cache_expiry = $ui->append('text', 'cache_expiry', 'option:' . $this->class_name . '__cache_expiry', _t('Cache Expiry (in seconds)', $this->class_name)); $cache_expiry->add_validator('validate_uint'); $cache_expiry->add_validator('validate_required'); // When the form is successfully completed, call $this->updated_config() $ui->append('submit', 'save', _t('Save', $this->class_name)); $ui->set_option('success_message', _t('Options saved', $this->class_name)); $ui->out(); break; } } } public function validate_username($username) { if (!ctype_alnum($username)) { return array(_t('Your Delicious username is not valid.', $this->class_name)); } return array(); } public function validate_uint($value) { if (!ctype_digit($value) || strstr($value, '.') || $value < 0) { return array(_t('This field must be positive integer.', $this->class_name)); } return array(); } private function plugin_configured($params = array()) { if (empty($params['user_id']) || empty($params['num_item']) || empty($params['cache_expiry'])) { return false; } return true; } private function load_feeds($params = array()) { $cache_name = $this->class_name . '__' . md5(serialize($params)); if (Cache::has($cache_name)) { // Read from cache return Cache::get($cache_name); } else { $url = 'http://feeds.delicious.com/v2/json/' . $params['user_id']; if ($params['tags']) { $url .= '/' . urlencode($params['tags']); } $url .= '?count=' . $params['num_item']; try { // Get JSON content via Delicious API $call = new RemoteRequest($url); $call->set_timeout(5); $result = $call->execute(); if (Error::is_error($result)) { throw Error::raise(_t('Unable to contact Delicious.', $this->class_name)); } $response = $call->get_response_body(); // Decode JSON $deliciousfeed = json_decode($response); if (!is_array($deliciousfeed)) { // Response is not JSON throw Error::raise(_t('Response is not correct, maybe Delicious server is down or API is changed.', $this->class_name)); } else { // Transform to DeliciousPost objects $serial = serialize($deliciousfeed); $serial = str_replace('O:8:"stdClass":', 'O:13:"DeliciousPost":', $serial); $deliciousfeed = unserialize($serial); } // Do cache Cache::set($cache_name, $deliciousfeed, $params['cache_expiry']); return $deliciousfeed; } catch (Exception $e) { return $e->getMessage(); } } } /** * Add Delicious posts to the available template vars * @param Theme $theme The theme that will display the template **/ public function theme_deliciousfeed($theme, $params = array()) { $params = array_merge($this->config, $params); if ($this->plugin_configured($params)) { $theme->deliciousfeed = $this->load_feeds($params); } else { $theme->deliciousfeed = _t('DeliciousFeed Plugin is not configured properly.', $this->class_name); } return $theme->fetch('deliciousfeed'); } /** * On plugin activation, set the default options */ public function action_plugin_activation($file) { if (realpath($file) === __FILE__) { $this->class_name = strtolower(get_class($this)); foreach ($this->default_options as $name => $value) { $current_value = Options::get($this->class_name . '__' . $name); if (is_null($current_value)) { Options::set($this->class_name . '__' . $name, $value); } } } } /** * On plugin init, add the template included with this plugin to the available templates in the theme */ public function action_init() { $this->class_name = strtolower(get_class($this)); foreach ($this->default_options as $name => $value) { $this->config[$name] = Options::get($this->class_name . '__' . $name); } $this->load_text_domain($this->class_name); $this->add_template('deliciousfeed', dirname(__FILE__) . '/deliciousfeed.php'); } } class DeliciousPost extends stdClass { public $u = ''; public $d = ''; public $t = array(); public $dt = ''; public $n = ''; public function __get($name) { switch ($name) { case 'url': return $this->u; break; case 'title': return htmlspecialchars($this->d); break; case 'desc': return htmlspecialchars($this->n); break; case 'tags': return htmlspecialchars($this->t); break; case 'tags_text': return htmlspecialchars(implode(' ', $this->t)); break; case 'timestamp': return $this->dt; break; default: return FALSE; break; } } } ?> <file_sep><?php $theme->display ('header'); ?> <div class="entry span-24"> <div class="left column span-6 first"> <h2></h2> </div> <div class="center column span-13"> <h2>Error! Houston, we have a problem.</h2> <p>It seems that the content you were looking for wasn't found. Sorry.</p> </div> <div class="right column span-5 last"> </div> </div> <?php $theme->display ('footer'); ?>
5fa113568d3744be29e9ddae09396a159294779f
[ "SQL", "JavaScript", "Text", "PHP", "Shell" ]
561
PHP
somefool/habari-extras
5ec6e1b41ffbc23ac6e92962c18585fbcaedf894
211fd46e0645fafbb1e66bc9367896d05796991f
refs/heads/master
<file_sep>import openpyxl input_file = "input.xlsx" output_file = "output.xlsx" # Required headers, case insensitive xls_headers = [["first name",False,-1],["spouse/partner name",False,-1],["last name",False,-1]] def validate_names(names): name_list = [] for name in names: if name != None: name_strip = name.strip() if len(name_strip) > 0: name_list.append(name_strip) # If list contains 3+ items, insert "and" if len(name_list) >= 3: name_list.insert(1, "and") # Return combined names return " ".join(name_list) print("Loading xls file...") # Load input file wb = openpyxl.load_workbook(input_file) # Active workbook tab ws = wb.active print("Checking headers...") # Find matching headers in xls file for row_cells in ws.iter_rows(min_row=1, max_row=1): for pos, cell in enumerate(row_cells): for item in xls_headers: if cell.value.lower() == item[0].lower(): item[1] = True item[2] = pos # Check for any missing headers if False in [i[1] for i in xls_headers]: for item in [i[0] for i in xls_headers if i[1] == False]: print(f"Missing header: {item}") raise SystemExit() print("Combining names...") # Find new column position new_column_num = ws.max_column + 1 # Add header for new column ws.cell(row=1, column=new_column_num, value="Combined Names") # Loop through rows in workbook for row_num, row in enumerate(ws[2:ws.max_row], start=2): # Get names from row, based on header index [first, spouse, last] combined_names = validate_names([row[xls_headers[0][2]].value, row[xls_headers[1][2]].value, row[xls_headers[2][2]].value]) # Add new value to worksheet ws.cell(row=row_num, column=new_column_num, value=combined_names) print("Saving file...") # Save file wb.save(output_file) <file_sep># Combine XLS Name Columns Combines names in separate columns (John, Jane, Doe) and appends a new column to the spreadsheet containing "John and <NAME>". ## Installation 1. Install `openpyxl` ```bash pip3 install openpyxl ``` ## Usage 1. Edit the input file and header columns to match your spreadsheet, and the output file to whatever you want: ```python input_file = "input.xlsx" output_file = "output.xlsx" xls_headers = [["first name",False,-1],["spouse/partner name",False,-1],["last name",False,-1]] ``` 2. Run the script: ```bash python3 xls-combine-name-cols.py ```
ae60eb89cfd1477bfcd1b093a0f3085a0a6a1ee0
[ "Markdown", "Python" ]
2
Python
sirken/xls-combine-name-columns
4cb603cd25ba049d667f5fe2884aa6ffb9e334c3
fd0ff27704234418d45db8b6550488b48d5d51bf
refs/heads/master
<file_sep>ComplexGamingSystem -Documentation ~https://brionnafranklin.github.io/ComplexGamingSystem/ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ How to Add to a Project - Step one ~ Download the contents of the Scource folder https://github.com/brionnafranklin/ComplexGamingSystem/tree/master/Source - step two ~ Place in scource folder of the project you wish to add to ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <file_sep>var searchData= [ ['carnivorecharacter_2ecpp_46',['CarnivoreCharacter.cpp',['../_carnivore_character_8cpp.html',1,'']]], ['carnivorecharacter_2eh_47',['CarnivoreCharacter.h',['../_carnivore_character_8h.html',1,'']]], ['complexgamingsystem_2ebuild_2ecs_48',['ComplexGamingSystem.Build.cs',['../_complex_gaming_system_8_build_8cs.html',1,'']]], ['complexgamingsystem_2ecpp_49',['ComplexGamingSystem.cpp',['../_complex_gaming_system_8cpp.html',1,'']]], ['complexgamingsystem_2eh_50',['ComplexGamingSystem.h',['../_complex_gaming_system_8h.html',1,'']]] ]; <file_sep>var searchData= [ ['complexgamingsystem_43',['ComplexGamingSystem',['../class_complex_gaming_system.html',1,'']]] ]; <file_sep>var searchData= [ ['herbivorecharacter_2ecpp_51',['HerbivoreCharacter.cpp',['../_herbivore_character_8cpp.html',1,'']]], ['herbivorecharacter_2eh_52',['HerbivoreCharacter.h',['../_herbivore_character_8h.html',1,'']]] ]; <file_sep>var searchData= [ ['acarnivorecharacter_55',['ACarnivoreCharacter',['../class_a_carnivore_character.html#a9dbd12e815862a50f032050fc8b842a4',1,'ACarnivoreCharacter']]], ['aherbivorecharacter_56',['AHerbivoreCharacter',['../class_a_herbivore_character.html#a727ba610267df04b139a25a4229ab4e8',1,'AHerbivoreCharacter']]], ['aplant_57',['APlant',['../class_a_plant.html#a9aebb46f435fac3b35da8e05dd181ffd',1,'APlant']]] ]; <file_sep>[/Script/EngineSettings.GeneralProjectSettings] ProjectID=57C9CB9D4C8B366FDEF47CA829E88F4F ProjectName=Top Down BP Game Template <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "AIController.h" #include "AIMovementController.generated.h" /** * */ DECLARE_DYNAMIC_MULTICAST_DELEGATE(FReachedDesination); UCLASS() class COMPLEXGAMINGSYSTEM_API AAIMovementController : public AAIController { GENERATED_BODY() public: /// set radius float m_radius = 600.0f; /// set offset float m_offset = 1.0f; /// set jitter float m_jitter = 1.0f; /// set previous target to be 0 FVector m_prevTarget = { 0.0f, 0.0f, 0.0f }; /// The owner of this controller AActor* Owner; /// The random posistion generated FVector targetPos = { 0.0f, 0.0f, 0.0f }; /// Called when the game starts or when spawned virtual void BeginPlay() override; /// Calculte new random location FVector CalculateRandomVector( float z ); /// Moves to a random location UFUNCTION(BlueprintCallable) void Wander(); /// Checks to see if target position in within a given range bool CheckTargetInRange(float range); /// An event that is broadcast when Character has reached the targetPos. On this event Wander is called UPROPERTY(BlueprintAssignable, Category = "AIMovement") FReachedDesination OnReachedDesination; }; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "AIMovementController.h" #include "NavigationSystem.h" #include "Engine.h" /// Called when the game starts or when spawned void AAIMovementController::BeginPlay() { Super::BeginPlay(); Owner = GetPawn(); OnReachedDesination.AddDynamic(this, &AAIMovementController::Wander); targetPos = Owner->GetActorLocation(); } /// Calculte new random location FVector AAIMovementController::CalculateRandomVector( float z ) { float randX = (float)rand() - ((float)RAND_MAX) / 2; float randY = (float)rand() - ((float)RAND_MAX) / 2; return FVector{ randX, randY, z }; } /// Moves to a random location void AAIMovementController::Wander() { /// Start with a random target on the edge of a circle with a set radius around the agent targetPos = CalculateRandomVector(Owner->GetActorLocation().Z).GetSafeNormal() * m_radius; /// Add a randomized vector to the target, with a magnitude specified by a jitter amount targetPos *= m_jitter; /// Bring the target back to the radius of the sphere by normalizing it and scaling by the radius targetPos = targetPos.GetSafeNormal() * m_radius; targetPos *= m_offset; /// Add the previous target targetPos += m_prevTarget; GEngine->AddOnScreenDebugMessage(-1, 500.0f, FColor::Blue, targetPos.ToString()); MoveToLocation(targetPos); return; } /// Checks to see if target position in within a given range bool AAIMovementController::CheckTargetInRange(float range) { return (FVector::Distance(Owner->GetActorLocation(), targetPos) <= range); } <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "HerbivoreCharacter.h" #include "Engine.h" void AHerbivoreCharacter::OnOverlapBegin(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) { if (OtherActor && (OtherActor != this) && OtherComp && OtherActor->IsA(APlant::StaticClass()) && CheckIfHungry()) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("Overlap Begin")); Controller->MoveToLocation(OtherActor->GetActorLocation()); GetWorld()->DestroyActor(OtherActor); Controller->Wander(); } } void AHerbivoreCharacter::OnOverlapEnd(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex) { if (OtherActor && (OtherActor != this) && OtherComp && OtherActor->IsA(APlant::StaticClass()) && CheckIfHungry()) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("Overlap End")); } } /// Sets default values AHerbivoreCharacter::AHerbivoreCharacter() { /// Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; /// declare trigger capsule TriggerCapsule = CreateDefaultSubobject<UCapsuleComponent>(TEXT("Trigger Capsule")); TriggerCapsule->InitCapsuleSize(300.0f, 100.0f);; TriggerCapsule->SetCollisionProfileName(TEXT("Trigger")); TriggerCapsule->SetupAttachment(RootComponent); /// declare overlap events TriggerCapsule->OnComponentBeginOverlap.AddDynamic(this, &AHerbivoreCharacter::OnOverlapBegin); TriggerCapsule->OnComponentEndOverlap.AddDynamic(this, &AHerbivoreCharacter::OnOverlapEnd); AIControllerClass = AAIMovementController::StaticClass(); } /// Called when the game starts or when spawned void AHerbivoreCharacter::BeginPlay() { Super::BeginPlay(); } /// Called every frame void AHerbivoreCharacter::Tick(float DeltaTime) { Super::Tick(DeltaTime); Controller = CastChecked<AAIMovementController>(GetController()); if (!Controller) { return; } if (Controller->CheckTargetInRange(300)) { Controller->OnReachedDesination.Broadcast(); } /// Slowly decrease current hunger currentHunger--; } /// Called to bind functionality to input void AHerbivoreCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); } /// Checks to see if current hunger is below the the threshold of hungry bool AHerbivoreCharacter::CheckIfHungry() { return currentHunger <= hungry; } /// returns true if food is in range bool AHerbivoreCharacter::CheckIfObjectfIsInRange(float range, FVector foodPos) { return (FVector::Distance(GetActorLocation(), foodPos) <= range); } <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "CarnivoreCharacter.h" #include "Engine.h" /// Determinds how the character behaves when overlapping with another hitbox void ACarnivoreCharacter::OnOverlapBegin(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) { if (OtherActor && (OtherActor != this) && OtherComp && OtherActor->IsA(AHerbivoreCharacter::StaticClass()) && CheckIfHungry()) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Orange, TEXT("Overlap Begin")); Controller->MoveToLocation(OtherActor->GetActorLocation()); GetWorld()->DestroyActor(OtherActor); Controller->Wander(); } if (OtherActor && (OtherActor != this) && OtherComp && OtherActor->IsA(ACarnivoreCharacter::StaticClass())) { /*FVector SpawnLocation = (GetActorLocation() + OtherActor->GetActorLocation()) / 2; FRotator SpawnRotation = (GetActorRotation()); FActorSpawnParameters SpawnParams; GetWorld()->SpawnActor<ACarnivoreCharacter>(SpawnLocation, SpawnRotation, SpawnParams);*/ GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Purple, TEXT("Overlap Begin")); } } /// Determinds how the character behaves when no longer overlapping with another hitbox void ACarnivoreCharacter::OnOverlapEnd(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex) { if (OtherActor && (OtherActor != this) && OtherComp && OtherActor->IsA(AHerbivoreCharacter::StaticClass()) && CheckIfHungry()) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Orange, TEXT("Overlap End")); } } // Sets default values ACarnivoreCharacter::ACarnivoreCharacter() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; /// declare trigger capsule TriggerCapsule = CreateDefaultSubobject<UCapsuleComponent>(TEXT("Trigger Capsule")); TriggerCapsule->InitCapsuleSize(300.0f, 100.0f);; TriggerCapsule->SetCollisionProfileName(TEXT("Trigger")); TriggerCapsule->SetupAttachment(RootComponent); /// declare overlap events TriggerCapsule->OnComponentBeginOverlap.AddDynamic(this, &ACarnivoreCharacter::OnOverlapBegin); TriggerCapsule->OnComponentEndOverlap.AddDynamic(this, &ACarnivoreCharacter::OnOverlapEnd); AIControllerClass = AAIMovementController::StaticClass(); } // Called when the game starts or when spawned void ACarnivoreCharacter::BeginPlay() { Super::BeginPlay(); } // Called every frame void ACarnivoreCharacter::Tick(float DeltaTime) { Super::Tick(DeltaTime); Controller = CastChecked<AAIMovementController>(GetController()); if (!Controller) { return; } if (Controller->CheckTargetInRange(300)) { Controller->OnReachedDesination.Broadcast(); } /// Slowly decrease current hunger currentHunger--; } // Called to bind functionality to input void ACarnivoreCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); } /// Checks to t see if current hunger is belong the the threshold of hungry bool ACarnivoreCharacter::CheckIfHungry() { return currentHunger <= hungry; } /// returns true if food is in range bool ACarnivoreCharacter::CheckIfObjectfIsInRange(float range, FVector foodPos) { return (FVector::Distance(GetActorLocation(), foodPos) <= range); } <file_sep>var searchData= [ ['tick_69',['Tick',['../class_a_carnivore_character.html#a3b27983dc2848832e784ec67d2d2f456',1,'ACarnivoreCharacter::Tick()'],['../class_a_herbivore_character.html#aa9d68e8a938603fff466fc9787558adc',1,'AHerbivoreCharacter::Tick()'],['../class_a_plant.html#a7b874f96ad7e3fc770e5fdf575c8f5b5',1,'APlant::Tick()']]] ]; <file_sep>var searchData= [ ['onreacheddesination_79',['OnReachedDesination',['../class_a_a_i_movement_controller.html#a772b2c6ed7e2319b8e5c76e5cc57db37',1,'AAIMovementController']]], ['owner_80',['Owner',['../class_a_a_i_movement_controller.html#a5a72dc4114e71dc509b2e0b434f4bd54',1,'AAIMovementController']]] ]; <file_sep>var searchData= [ ['hungry_73',['hungry',['../class_a_carnivore_character.html#ae300b1b9c28714c9a9d39f2878dc7f45',1,'ACarnivoreCharacter::hungry()'],['../class_a_herbivore_character.html#a9c52510b3569c2dffa937bef4bde9b72',1,'AHerbivoreCharacter::hungry()']]] ]; <file_sep>var searchData= [ ['aimovementcontroller_2ecpp_44',['AIMovementController.cpp',['../_a_i_movement_controller_8cpp.html',1,'']]], ['aimovementcontroller_2eh_45',['AIMovementController.h',['../_a_i_movement_controller_8h.html',1,'']]] ]; <file_sep>var searchData= [ ['declare_5fdynamic_5fmulticast_5fdelegate_19',['DECLARE_DYNAMIC_MULTICAST_DELEGATE',['../_a_i_movement_controller_8h.html#a5a69eba9e388008c6a520d2f5be8dfbb',1,'AIMovementController.h']]] ]; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "Components/CapsuleComponent.h" #include "Plant.generated.h" UCLASS() class COMPLEXGAMINGSYSTEM_API APlant : public AActor { GENERATED_BODY() /// create trigger capsule UPROPERTY(VisibleAnywhere, Category = "Trigger Capsule") class UCapsuleComponent* TriggerCapsule; /// create mesh UPROPERTY(VisibleAnywhere, Category = "Mesh") class UStaticMesh* Mesh; public: /// Sets default values for this actor's properties APlant(); protected: /// Called when the game starts or when spawned virtual void BeginPlay() override; public: /// Called every frame virtual void Tick(float DeltaTime) override; }; <file_sep>var searchData= [ ['setupplayerinputcomponent_35',['SetupPlayerInputComponent',['../class_a_carnivore_character.html#af9f848173a971bc621dd00ba2109e3ff',1,'ACarnivoreCharacter::SetupPlayerInputComponent()'],['../class_a_herbivore_character.html#a1994f7b76a07c7d73349ceab4e54278d',1,'AHerbivoreCharacter::SetupPlayerInputComponent()']]] ]; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Character.h" #include "AIMovementController.h" #include "Plant.h" #include "Components/CapsuleComponent.h" #include "HerbivoreCharacter.generated.h" UCLASS() class COMPLEXGAMINGSYSTEM_API AHerbivoreCharacter : public ACharacter { GENERATED_BODY() /// create trigger capsule UPROPERTY(VisibleAnywhere, Category = "Trigger Capsule") class UCapsuleComponent* TriggerCapsule; public: /// declare overlap begin function UFUNCTION() void OnOverlapBegin(class UPrimitiveComponent* OverlappedComp, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult); /// declare overlap end function UFUNCTION() void OnOverlapEnd(class UPrimitiveComponent* OverlappedComp, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex); /// Sets default values for this character's properties AHerbivoreCharacter(); /// Decreases over time and refils after eating float currentHunger = 100.0f; /// The max hunger can be at any given time float maxHunger = 100.0f; /// How low the hunger must be until food can be consumed float hungry = 75.0f; /// The AI Controller using this AAIMovementController* Controller; protected: /// Called when the game starts or when spawned virtual void BeginPlay() override; public: /// Called every frame virtual void Tick(float DeltaTime) override; /// Called to bind functionality to input virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; /// Checks to see if current hunger is below the the threshold of hungry bool CheckIfHungry(); /// returns true if food is in range bool CheckIfObjectfIsInRange(float range, FVector foodPos); }; <file_sep>var searchData= [ ['targetpos_36',['targetPos',['../class_a_a_i_movement_controller.html#aeddd9adae249a1ea5b6914ceb41fd8b4',1,'AAIMovementController']]], ['tick_37',['Tick',['../class_a_carnivore_character.html#a3b27983dc2848832e784ec67d2d2f456',1,'ACarnivoreCharacter::Tick()'],['../class_a_herbivore_character.html#aa9d68e8a938603fff466fc9787558adc',1,'AHerbivoreCharacter::Tick()'],['../class_a_plant.html#a7b874f96ad7e3fc770e5fdf575c8f5b5',1,'APlant::Tick()']]] ]; <file_sep>var searchData= [ ['plant_2ecpp_53',['Plant.cpp',['../_plant_8cpp.html',1,'']]], ['plant_2eh_54',['Plant.h',['../_plant_8h.html',1,'']]] ]; <file_sep>var searchData= [ ['aaimovementcontroller_39',['AAIMovementController',['../class_a_a_i_movement_controller.html',1,'']]], ['acarnivorecharacter_40',['ACarnivoreCharacter',['../class_a_carnivore_character.html',1,'']]], ['aherbivorecharacter_41',['AHerbivoreCharacter',['../class_a_herbivore_character.html',1,'']]], ['aplant_42',['APlant',['../class_a_plant.html',1,'']]] ]; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "Plant.h" /// Sets default values APlant::APlant() { /// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; /// declare trigger capsule TriggerCapsule = CreateDefaultSubobject<UCapsuleComponent>(TEXT("Trigger Capsule")); TriggerCapsule->InitCapsuleSize(100.0f, 100.0f);; TriggerCapsule->SetCollisionProfileName(TEXT("Trigger")); TriggerCapsule->SetupAttachment(RootComponent); } /// Called when the game starts or when spawned void APlant::BeginPlay() { Super::BeginPlay(); } /// Called every frame void APlant::Tick(float DeltaTime) { Super::Tick(DeltaTime); }
43c688620261c656d2323029c213f865de886bbb
[ "Markdown", "JavaScript", "C++", "INI" ]
22
Markdown
brionnafranklin/ComplexGamingSystem
6e366e6fd184430e7e1f44f3ee44344cce2f68d9
d217cddb7b2725373e013f5395de6638fb9c60eb
refs/heads/master
<repo_name>Sieyk/CompilerScanner<file_sep>/src/CD15.java import java.util.Scanner; //<NAME> 3184660 public class CD15 { public static void main(String[]args){ System.out.println("Please input the file name for scanning"); Scanner reader = new Scanner(System.in); COMPScanner scan = new COMPScanner(reader.next()); reader.close(); Token token = scan.scan(); scan.printToken(token); while (!token.EOFChecker()) { token = scan.scan(); scan.printToken(token); } } } <file_sep>/src/COMPScanner.java import java.io.*; /** * Created by <NAME> on 20/08/15. */ public class COMPScanner { final String [] keywords = {"program", "end", "arrays", "procedure", "var", "val", "loop", "exit", "when", "if", "then", "else", "elsif", "call", "with", "input", "print", "not", "and", "or", "xor", "div", "length"}; enum states {S, operator, zero, intLit, flLit, identOrKey, blockComment, comment, string, undef} private String holder; private String outputLine; private int currLine; private int currCol; private boolean nextIgnore; private boolean currIgnore; private boolean undfTokenDelimited; private boolean lexErrMsgFallback; states currState; boolean escape; boolean floatValidator; int tokenID; int i; boolean dontRead; Reader read; COMPScanner(String fileIn){ holder = ""; currLine = 1; currCol = 0; outputLine = ""; dontRead = false; tokenID = 5; undfTokenDelimited = false; lexErrMsgFallback = false; currIgnore = false; nextIgnore = false; floatValidator = false; currState = states.S; escape = false; i = -1; try { File f = new File(fileIn); FileInputStream fis = new FileInputStream(f); read = new InputStreamReader(fis); }catch(FileNotFoundException o){} } public Token scan(){ try { //System.out.println("scanning"); holder = ""; escape = false; floatValidator = false; //tokenID = 0; currIgnore = nextIgnore; nextIgnore = false; /*if (holder.equals(";") || holder.equals("[") || holder.equals("]") || holder.equals("\"") || holder.equals("(") || holder.equals(")")) //If a delimiter delimited, this allows instant tokenization of it {escape = true;}*/ while ((!escape || undfTokenDelimited) && ((dontRead) || (i = read.read()) != -1)) { //char input = (char) i; //System.out.print(input); if (!dontRead) currCol++; dontRead= false; if (undfTokenDelimited) { System.out.println(); System.out.print("TUNDF " + holder); System.out.println(); currIgnore = true; //nextIgnore = true; holder = ""; } undfTokenDelimited = false; lexErrMsgFallback = false; switch (currState) { case S: if (i==48){ //i == 0 holder+=(char)i; currState = states.zero; } else if(i>48&&i<58){ //i is an int other than 0 holder+=(char)i; tokenID = 2; currState = states.intLit; } else if(Character.isLetter((char)i)){ //i is any letter holder+=(char)i; tokenID = 1; currState = states.identOrKey; } else if ((char)i == '.' || (char)i == ',' || (char)i == ';') { holder+=(char)i; escape = true; } else if ((char)i == '/') { currCol++; holder+=(char)i; if ((char)(i = read.read()) == '/') { holder = ""; currState = states.comment; } else if((char)i == '=') { holder+=(char)i; escape = true; } else { dontRead = true; escape = true; } } else if ((char)i == '\"') { currState = states.string; } else if ((char)i == '+') { holder+=(char)i; currCol++; if ((char)(i = read.read()) == '=') { holder+="="; escape=true; } else if (currCol == 2 && (char)i == '/') { currCol++; holder+=(char)i; if ((char)(i = read.read()) == '+') { holder+=(char)i; if(currCol == 3) { holder=""; currState = states.blockComment; } else { lexErr("Block comments must start at the beginning of a line."); tokenID = 0; dontRead = true; escape = true; } } else { lexErr("Unrecognised token \'+/\'"); tokenID = 0; dontRead = true; escape = true; } } else { dontRead = true; escape = true; } } else if ((char)i == '*' || (char)i == '+' || (char)i == '-' || (char)i == '<' || (char)i == '>') { holder+=(char)i; currState = states.operator; } else if((char)i == '!' || (char)i == '=') { holder+=(char)i; currCol++; if ((char)i == '!') { if ((char)(i = read.read()) == '=') { holder+=(char)i; escape=true; } else { dontRead = true; lexErr("NOT '!' operator requires '=' to follow it to be a valid symbol"); escape = true; } } else if((char)i == '=') { if((char)(i = read.read()) == '=') { holder+=(char)i; escape = true; } else if ((char)i == ' ' || (char)i == '\n' || (char)i == '\t'|| (char)i == '\r') { newLineSpace(i); currState = states.S; escape = true; } else { dontRead = true; escape = true; } } } else if ((char)i == ';' || (char)i == '[' || (char)i == ']' || (char)i == '(' || (char)i == ')') { //Delimiters holder += (char)i; escape = true; } else if ((char)i == ' ' || (char)i == '\n' || (char)i == '\t' || (char)i == '\r'){ //Delimiters and line/column counting newLineSpace(i); } else { holder+=(char)i; tokenID = 0; escape = true; lexErr("Unknown Character."); } break; case comment: if ((char)i != '\n') { } else { currState = states.S; currLine++; currCol = 0; } break; case string: tokenID = 4; if ((char)i != '\"' && (char)i != '\n' && (char)i != '\r') { holder+=(char)i; } else if ((char)i == '\n' || (char)i == '\r') { tokenID = 0; currState = states.S; lexErr("Strings may not be delimited by new lines."); escape = true; } else { currState = states.S; escape = true; } break; case identOrKey: tokenID = 1; if (Character.isLetter((char)i) || (i>=48&&i<58)) { holder+=(char)i; } else if((char)i == ' ' || (char)i == '\n' || (char)i == '\t' || (char)i == '\r') { newLineSpace(i); escape = true; currState = states.S; } else { dontRead = true; escape = true; currState = states.S; } break; case blockComment: if ((char)i == '\n') { currCol = 0; currLine ++; } if ((char)i == '+') { currCol++; if ((char)(i = read.read()) == '/') { currCol++; if ((char)(i = read.read()) == '+' && currCol == 3) { currState = states.S; } } } break; case operator: if ((char)i == '=') { holder+=(char)i; currState = states.S; escape = true; } else if ((char)i == ' ' || (char)i == '\n' || (char)i == '\t' || (char)i == '\r') { newLineSpace(i); currState = states.S; escape = true; } else { dontRead = true; currState = states.S; escape = true; } break; case zero: tokenID = 2; if ((char)i == '.'){ holder+=(char)i; tokenID = 3; currState = states.flLit; } else if (i>=48&&i<58) { dontRead = true; escape = true; tokenID = 0; lexErr("Integers containing more than one digit cannot start with 0"); currState = states.S; } else if ((char)i == ' ' || (char)i == '\n' || (char)i == '\t' || (char)i == '\r') { tokenID = 2; newLineSpace(i); currState = states.S; escape = true; } else if (Character.isLetter((char)i)) { currState = states.undef; holder+=(char)i; } else { dontRead = true; escape = true; currState = states.S; } break; case intLit: tokenID = 2; if (i>=48&&i<58) //i is an int { holder+=(char)i; } else if ((char)i == '.') { holder+=(char)i; tokenID = 3; currState = states.flLit; } else if((char)i == ' ' || (char)i == '\n' || (char)i == '\t' || (char)i == '\r') { newLineSpace(i); currState = states.S; escape = true; } else if (Character.isLetter((char)i)) { currState = states.undef; holder+=(char)i; } else { currState = states.S; escape = true; dontRead = true; } break; case undef: tokenID = 0; if (!Character.isLetter((char)i) && !(i>=48&&i<58) && !((char)i == '.')) { lexErr("Undefined Token"); dontRead = true; //escape = true; undfTokenDelimited = true; currState = states.S; } else { lexErrMsgFallback = true; holder += (char)i; } break; case flLit: tokenID = 3; if (i>=48&&i<58) //i is an int { holder+=(char)i; floatValidator = true; } else if((char)i == '.') { lexErr("Floats can not contain more than one dot '.'"); dontRead = true; escape = true; } else if (Character.isLetter((char)i)) { currState = states.undef; holder += (char)i; } else if (!(i>=48&&i<58) && !floatValidator) { lexErr("Unexpected end of float."); tokenID = 0; dontRead = true; escape = true; } else if ((char)i == ' ' || (char)i == '\n' || (char)i == '\t' || (char)i == '\r') { newLineSpace(i); currState = states.S; escape = true; } else { currState = states.S; escape = true; dontRead = true; } break; } } }catch(Throwable e){ //System.out.println("End of file reached."); } if (lexErrMsgFallback) { lexErr("Undefined Token"); System.out.println(); lexErrMsgFallback = false; } return new Token(holder, tokenID); } public void printToken(Token tokIn){ if (!tokIn.getTokenID().equals("TUNDF") && !tokIn.getTokenID().equals("TIDNT") && !tokIn.getTokenID().equals("TILIT") && !tokIn.getTokenID().equals("TFLIT") && !tokIn.getTokenID().equals("TSTRG")) { if(outputLine.length() <= 60) { System.out.print(tokIn.getTokenID()+" "); outputLine += tokIn.getTokenID()+" "; } else { System.out.println(); outputLine = ""; System.out.print(tokIn.getTokenID()+" "); outputLine += tokIn.getTokenID()+" "; } } else if(tokIn.getTokenID().equals("TUNDF")) { if (!currIgnore) System.out.println(); nextIgnore = true; outputLine = ""; System.out.print(tokIn.getTokenID()+" "+tokIn.getContents()); System.out.println(); } else if(tokIn.getTokenID().equals("TUNDF")) { if(outputLine.length() <= 60) { System.out.print(tokIn.getTokenID()+" \""+tokIn.getContents()+"\" "); outputLine += tokIn.getTokenID()+" \""+tokIn.getContents()+"\" "; } else { System.out.println(); outputLine = ""; System.out.print(tokIn.getTokenID()+" \""+tokIn.getContents()+"\" "); outputLine += tokIn.getTokenID()+" \""+tokIn.getContents()+"\" "; } } else if (tokIn.getTokenID().equals("TSTRG")) { if(outputLine.length() <= 60) { System.out.print(tokIn.getTokenID()+" \""+tokIn.getContents()+"\" " + addSpaces((holder.length()+2) % 6)); outputLine += tokIn.getTokenID()+" \""+tokIn.getContents()+"\" " + addSpaces((holder.length()+2) % 6); } else { System.out.println(); outputLine = ""; System.out.print(tokIn.getTokenID()+" \""+tokIn.getContents()+"\" " + addSpaces((holder.length()+2) % 6)); outputLine += tokIn.getTokenID()+" \""+tokIn.getContents()+"\" " + addSpaces((holder.length()+2) % 6); } } else { if(outputLine.length() <= 60) { System.out.print(tokIn.getTokenID()+" "+tokIn.getContents()+" " + addSpaces(holder.length() % 6)); outputLine += tokIn.getTokenID()+" "+tokIn.getContents()+" " + addSpaces(holder.length() % 6); } else { System.out.println(); outputLine = ""; System.out.print(tokIn.getTokenID()+" "+tokIn.getContents()+" " + addSpaces(holder.length() % 6)); outputLine += tokIn.getTokenID()+" "+tokIn.getContents()+" " + addSpaces(holder.length() % 6); } } } private void newLineSpace(int i) { if ((char)i == '\n') { currLine++; currCol=0; } } private void lexErr(String errorMsg) { if (!currIgnore) System.out.println(); System.out.print("Lexical Error:" + " (Line: " + currLine + ", Column: " + (currCol - holder.length()) + ")" + " " + errorMsg + " \"" + holder + "\""); if (currIgnore && nextIgnore) System.out.println(); } private String addSpaces(int i) { String str = ""; for (;i<5;i++) { str += ' '; } return str; } } <file_sep>/src/TreeNode.java public class TreeNode { private static int count = 0; private static int index = 0; private Node nodeValue; private int idx; private TreeNode left,middle,right; private String name; //private String type; //String was originally StRec private Token tok; public enum Node { NUNDEF, NPROG, NARRYL, NPROCL, NMAIN, NPROC, NPLIST, NSIMPAR, NARRPAR, NDLIST, NSIMDEC, NARRDEC, NARRVAR, NSIMVAR, NSLIST, NLOOP, NEXIT, NIFT, NIFTE, NINPUT, NPRINT, NPRLN, NCALL, NELIST, NASGN, NPLEQ, NMNEQ, NSTEQ, NDVEQ, NADD, NSUB, NMUL, NDIV, NIDIV, NNOT, NAND, NOR, NXOR, NEQL, NNEQ, NGTR, NLESS, NGEQ, NLEQ, NILIT, NFLIT, NIDLST, NVLIST, NPRLIST, NLEN, NSTRG }; public TreeNode () { nodeValue = Node.NUNDEF; index++; idx = index; left = null; middle = null; right = null; name = null; //type = null; } public TreeNode (Node value) { this(); nodeValue = value; } public TreeNode (Node value, String st) { this(value); name = st; } public TreeNode (Node value, TreeNode l, TreeNode r) { this(value); left = l; right = r; } public TreeNode (Node value, TreeNode l, TreeNode m, TreeNode r) { this(value,l,r); middle = m; } public Node getValue() { return nodeValue; } public TreeNode getLeft() { return left; } public TreeNode getMiddle() { return middle; } public TreeNode getRight() { return right; } public String getName() { return name; } //public String getType() { return type; } public Token getToken() { return tok; } public void setValue(Node value) { nodeValue = value; } public void setLeft(TreeNode l) { left = l; } public void setMiddle(TreeNode m) { middle = m; } public void setRight(TreeNode r) { right = r; } public void setName(String st) { name = st; } //public void setType(String st) { type = st; } public void setTokenContents(String in) { tok.setContents(in); } public static void resetIndex() { index = 0; } }
60b47636be4dd079cf54aa48a7d505e254b84702
[ "Java" ]
3
Java
Sieyk/CompilerScanner
fae5351ce42839bd33c76a9d762429a4a6b443ab
b8ff22fc31fb37d15091234441c47ddc19146afd
refs/heads/main
<repo_name>MichaelSana/SingletonDesignPattern<file_sep>/Library.java /** * The singelton class to sort through the library * @author <NAME> */ package SingletonDesignPattern; import java.util.HashMap; public class Library{ private HashMap<String, Integer> books = new HashMap<>(); private static Library library; /** This makes it so there can only be one instance of Library */ private Library(){} /** * This is where the driver will pull from and act as a "new instance" * @return library */ public static Library getInstance(){ if(library == null){ System.out.println("Creating our library. Time to begin reading."); library = new Library(); } return library; } /** * Searches the database to see if a book is ins tock and if so checks the book out * @param bookName * @return true/false depending on if the book is in the library */ public boolean checkoutBook(String bookName){ if(books.containsKey(bookName) && books.get(bookName) >= 1 ){ books.replace(bookName, books.get(bookName) -1); System.out.println(bookName + " was succesfully check out"); return true; } else{ System.out.println("Sorry " + bookName + " is not in stock"); return false; } } /** * Checks in a book then adds one to the total amount of that book in stock * @param bookName The book in question * @param numToAdd The number of each book */ public void checkInBook(String bookName, int numToAdd){ if(books.containsKey(bookName)){ books.replace(bookName, books.get(bookName) + numToAdd); System.out.println("A new copy of " + bookName + " was added to the library"); } else{ books.put(bookName, numToAdd); System.out.println(bookName + " was added to the library"); } } /** * Displays the books in the library and the amount of each book */ public void displayBooks(){ System.out.println("\nInventory:"); for(String value : books.keySet()){ System.out.println("\t " + value + ", copies " + books.get(value)); } } }
8d53b075788a28358cd40dc75353bb2b865c54de
[ "Java" ]
1
Java
MichaelSana/SingletonDesignPattern
ea5912a080e4e18504d5c41990f657f375683b41
c8c84f150e855745d4b16c0363acd3c91595fb35
refs/heads/master
<file_sep>package store.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import store.dao.Action; import store.dao.BookDAO; import store.model.Book; public class RemoveBookAction implements Action { public String execute(HttpServletRequest request, HttpServletResponse response) { BookDAO bookDAO = new Book(); String msg = "Book removed."; try { int id = Integer.parseInt(request.getParameter("book_id")); bookDAO.removeBook(id); } catch (Exception e) { msg = e.getMessage(); return "/WEB-INF/error.jsp"; } request.setAttribute("message", msg); return "/WEB-INF/success.jsp"; } } <file_sep>package store.action; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import store.dao.Action; import store.dao.BookDAO; import store.model.Book; public class FindByCategoryAction implements Action { public String execute(HttpServletRequest request, HttpServletResponse response) { BookDAO book = new Book(); String category = request.getParameter("cat"); List<Book> list = book.findByCategory(category); request.setAttribute("booklist", list); return "/WEB-INF/showcategory.jsp"; } } <file_sep>package store.dao; import java.util.List; import store.model.ListItem; public interface ListItemDAO { List<ListItem> findAll(); void addListItem(int id); void addListItem(int id, int quantity); void removeListItem(int id); void updateListItem(int id, int quantity); } <file_sep>package store.impl; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import store.dao.ListItemDAO; import store.factory.Factory; import store.model.Book; import store.model.ListItem; public class ListItemImpl implements ListItemDAO { @Override public List<ListItem> findAll() { EntityManager em = Factory.emf.createEntityManager(); List<ListItem> list = em.createQuery("from ListItem").getResultList(); em.close(); return list; } @Override public void addListItem(int id) { EntityManager em = Factory.emf.createEntityManager(); EntityTransaction tr = em.getTransaction(); tr.begin(); try { Book book = em.find(Book.class, id); ListItem item = new ListItem(book); item.setQuantity(1); em.persist(item); } catch (Exception e) { tr.rollback(); } tr.commit(); em.close(); } @Override public void addListItem(int id, int quantity) { EntityManager em = Factory.emf.createEntityManager(); EntityTransaction tr = em.getTransaction(); tr.begin(); try { Book book = em.find(Book.class, id); ListItem item = new ListItem(book); item.setQuantity(quantity); em.persist(item); } catch (Exception e) { tr.rollback(); } tr.commit(); em.close(); } @Override public void removeListItem(int id) { EntityManager em = Factory.emf.createEntityManager(); EntityTransaction tr = em.getTransaction(); tr.begin(); ListItem item = em.find(ListItem.class, id); em.remove(item); tr.commit(); em.close(); } @Override public void updateListItem(int id, int quantity) { EntityManager em = Factory.emf.createEntityManager(); EntityTransaction tr = em.getTransaction(); tr.begin(); ListItem item = em.find(ListItem.class, id); item.setQuantity(quantity); em.persist(item); tr.commit(); em.close(); } } <file_sep>package store.model; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.PrimaryKeyJoinColumn; import store.impl.ListItemImpl; @Entity public class ListItem extends ListItemImpl { @Id private int id; @OneToOne @PrimaryKeyJoinColumn private Book item; private int quantity; public ListItem() {} public ListItem(Book item) { super(); this.item = item; this.id = item.getId(); } public Book getItem() { return item; } public void setItem(Book item) { this.item = item; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public String toString() { return "ListItem [id=" + id + ", item=" + item + ", quantity=" + quantity + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ListItem other = (ListItem) obj; if (id != other.id) return false; return true; } } <file_sep>package store.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import store.dao.Action; public class ErrorAction implements Action { public String execute(HttpServletRequest request, HttpServletResponse response) { return "/WEB-INF/error.html"; } } <file_sep>package store.model; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQuery; import javax.persistence.OneToOne; import javax.persistence.PrimaryKeyJoinColumn; import store.impl.BookImpl; @Entity @NamedQuery(name="findByTitle", query = "select b from Book b where b.title like :desc") public class Book extends BookImpl { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; private String title; private String author; private int pageNumber; private String isbn; private String category; private String imageUrl; private String publishingHouse; private int issueYear; private float price; private boolean bestseller; private String language; private int copyNumber; public Book() {} public Book(String title) { this.title = title; } public Book(String title, String author, int pageNumber, String isbn, String category, String imageUrl, String publishingHouse, int issueYear, float price, boolean bestseller, String language, int copyNumber) { super(); this.title = title; this.author = author; this.pageNumber = pageNumber; this.isbn = isbn; this.category = category; this.imageUrl = imageUrl; this.publishingHouse = publishingHouse; this.issueYear = issueYear; this.price = price; this.bestseller = bestseller; this.language = language; this.copyNumber = copyNumber; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getPageNumber() { return pageNumber; } public void setPageNumber(int pageNumber) { this.pageNumber = pageNumber; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getPublishingHouse() { return publishingHouse; } public void setPublishingHouse(String publishingHouse) { this.publishingHouse = publishingHouse; } public int getIssueYear() { return issueYear; } public void setIssueYear(int issueYear) { this.issueYear = issueYear; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public boolean isBestseller() { return bestseller; } public void setBestseller(boolean bestseller) { this.bestseller = bestseller; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public int getCopyNumber() { return copyNumber; } public void setCopyNumber(int copyNumber) { this.copyNumber = copyNumber; } @Override public String toString() { return "Book [id=" + id + ", title=" + title + ", author=" + author + ", pageNumber=" + pageNumber + ", isbn=" + isbn + ", category=" + category + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Book other = (Book) obj; if (id != other.id) return false; return true; } } <file_sep>package store.factory; import javax.servlet.http.HttpServletRequest; import store.action.*; import store.dao.Action; public class ActionFactory { public static Action getAction(HttpServletRequest request) { String uri = request.getRequestURI(); int lastIndex = uri.lastIndexOf("/"); String address = uri.substring(lastIndex + 1); Action action = null; if (address.equalsIgnoreCase("showbooks")) { action = new FindAllAction(); return action; } if (address.equalsIgnoreCase("search")) { action = new FindByTitleAction(); return action; } if (address.equalsIgnoreCase("showbook")) { action = new ShowBookAction(); return action; } if (address.equalsIgnoreCase("addbook")) { action = new AddBookAction(); return action; } if (address.equalsIgnoreCase("remove")) { action = new RemoveBookAction(); return action; } if (address.equalsIgnoreCase("editlist")) { action = new EditListAction(); return action; } if (address.equalsIgnoreCase("showcategory")) { action = new FindByCategoryAction(); return action; } if (address.equalsIgnoreCase("showsorted")) { action = new ShowSortedAction(); return action; } if (address.equalsIgnoreCase("addtocart")) { action = new AddToCartAction(); //add UpdateCartAction() if id already exists in the scope; make it via request.getSession().getAttribute("cart"); } if (address.equalsIgnoreCase("updatecart")) { action = new UpdateCartAction(); } if (address.equalsIgnoreCase("removefromcart")) { action = new RemoveFromCartAction(); } if (action == null) action = new ErrorAction(); return action; } }
9726cab01e2ff99c9bf5d9164f123c54f0a11456
[ "Java" ]
8
Java
Eugnat/bookstore-webproject
15781e8d9f904467369b82787a1235ce49113a3b
1ef8366bc2c31c9699a8efb757bca27c18939559
refs/heads/master
<repo_name>nidzelskyy/coursera_python_course<file_sep>/README.md **Coursera** MFTU Programming in python Course 1 - Diving in Python Московский физико-технический институт & Mail.Ru Group Программирование на Python Курс №1 Погружение в Python<file_sep>/week1/solution3.py import sys a = int(sys.argv[1]) b = int(sys.argv[2]) c = int(sys.argv[3]) d = b ** 2 - 4 * a * c if d > 0: x1 = (-b + d ** 0.5) / (2 * a) x2 = (-b - d ** 0.5) / (2 * a) elif d == 0: x1 = x2 = -b / (2 * a) else: x1 = x2 = None if not x1 is None: print(int(x1)) print(int(x2)) else: print("Корней уравнения нет")<file_sep>/week2/9_functions.py from datetime import datetime def get_seconds(): """Return current seconds""" return datetime.now().second def split_tags(tag_string): tag_list = [] for tag in tag_string.split(','): tag_list.append(tag.strip()) return tag_list def add(x: int, y: int) -> int: return x + y def extender(source_list, extend_list): source_list.extend(extend_list) def replacer(source_tuple, replace_with): source_tuple = replace_with def say(greeting, name): print("{} {}!".format(greeting, name)) result = 0 def increment(): result += 1 return result def greeting(name="tt's me..."): print("Hello, {}".format(name)) def printer(*args): print(type(args)) for argument in args: print(argument) def printer2(**kwargs): print(type(kwargs)) for key, value in kwargs.items(): print('{}: {}'.format(key, value)) print(get_seconds()) print(get_seconds.__doc__) print(get_seconds.__name__) tags = split_tags("python, courcera, mooc") print(tags) print(add(1, 3)) print(add("still ", "works")) values = [1, 2, 3] extender(values, [4, 5, 6]) print(values) user_info = ("Guido", '31/01') replacer(user_info, ('Larry', '27/09')) print(user_info) say("hello", 'Kitty') say(name='Kitty', greeting="hello") #print(increment()) #UnboundLocalError greeting('IGORek') greeting() printer(1, 2, 3, 4, 5) names = ['John', 'Bill', 'Amy'] printer(*names) printer2(a=10, b=11) payload = { 'user_id': 117, 'feedback': { 'subject': "Registration fields", 'message': 'There is no country for old men' } } printer2(**payload)<file_sep>/week2/15_generators.py def even_range(start, end): current = start while current < end: yield current current += 2 print(list(even_range(0,10))) def fibonacci(number): a = b = 1 for _ in range(number): yield a a, b = b, a + b print(list(fibonacci(20))) def accumulator(): total = 0 while True: value = yield total print("Got: {}".format(value)) if not value: break total += value generator = accumulator() next(generator) print("Accumulated:{}".format(generator.send(1))) print("Accumulated:{}".format(generator.send(1))) print("Accumulated:{}".format(generator.send(2))) next(generator)<file_sep>/week2/14_decorators.py import functools def decorator(func): return func @decorator def decorated(): print("Hello!") #decorated = decorator(decorated) def decorator2(func): def new_func(): pass return new_func @decorator2 def decorated2(): print("Hello!") decorated2() print(decorated2.__name__) def stringify(func): return str(func) @stringify def multiply(a, b): return a * b print(multiply) def logger(func): @functools.wraps(func) def wrapped(*argsm, **kwargs): result = func(*argsm, **kwargs) with open('log.txt', 'w') as f: f.write(str(result)) return result return wrapped @logger def summator(num_list): return sum(num_list) r1 = summator([1,2,3,4,5]) print(summator.__name__) print(r1) with open('log.txt', 'r') as f: print('log.txt: {}'.format(f.read())) def logger(filename): def decorator(func): def wrapper(*args, **kwargs): result = func(*args, **kwargs) with open(filename, 'w') as f: f.write(str(result)) return result return wrapper return decorator @logger('new_log.txt') def summator(num_list): return sum(num_list) r2 = summator([1,2,3,4,5,6]) print(r2) print(summator.__name__) with open('new_log.txt', 'r') as f: print('new_log.txt: {}'.format(f.read())) def first_decorator(func): def wrapped(): print("Inside first_decorator product") return func() return wrapped def seccond_decorator(func): def wrapped(): print("Inside second_decorator product") return func() return wrapped @first_decorator @seccond_decorator def decorated(): print('Finally called...') # decorated = first_decorator(seccond_decorator(decorated)) decorated() def bold(func): def wrapped(): return "<b>" + func() + "</b>" return wrapped def italic(func): def wrapped(): return "<i>" + func() + "</i>" return wrapped @bold @italic def hello(): return "Hello world" #hello = bold(italic(hello)) print(hello())<file_sep>/week1/4_none_object.py answer = None print(answer) print(type(answer)) print(bool(None)) if not answer: print("Ответ не получен") income = None if income is None: print("Еще не начинали продавать") elif not income: print("Ничего не заработали") <file_sep>/week3/solution2.py import csv import os class BaseCar: def __init__(self, brand, photo_file_name, carrying): self.car_type = None self.photo_file_name = photo_file_name self.brand = brand self.carrying = float(carrying) def get_photo_file_ext(self): path_parts = os.path.splitext(self.photo_file_name) return path_parts[-1] class Car(BaseCar): def __init__(self, brand, photo_file_name, carrying, passenger_seats_count): super().__init__(brand, photo_file_name, carrying) self.car_type = 'car' self.passenger_seats_count = int(passenger_seats_count) class Truck(BaseCar): def __init__(self, brand, photo_file_name, carrying, body_whl): super().__init__(brand, photo_file_name, carrying) self.car_type = 'truck' if len(body_whl) > 0: self.body_width, self.body_height, self.body_length = list(map(lambda x: float(x), body_whl.split('x'))) else: self.body_length = self.body_width = self.body_height = 0.0 def get_body_volume(self): return self.body_width * self.body_height * self.body_length class SpecMachine(BaseCar): def __init__(self, brand, photo_file_name, carrying, extra): super().__init__(brand, photo_file_name, carrying) self.car_type = 'spec_machine' self.extra = extra def get_car_list(csv_filename): car_list = [] try: with open(csv_filename) as csv_fd: reader = csv.reader(csv_fd, delimiter=';') next(reader) # пропускаем заголовок for row in reader: try: if len(row) > 0 and row[0] in ['car', 'truck', 'spec_machine']: car_type, brand, passenger_seats_count, photo_file_name, body_whl, carrying, extra = row car = None if car_type == 'car': car = Car(brand, photo_file_name, carrying, passenger_seats_count) elif car_type == 'truck': car = Truck(brand, photo_file_name, carrying, body_whl) elif car_type == 'spec_machine': car = SpecMachine(brand, photo_file_name, carrying, extra) else: continue car_list.append(car) else: continue except BaseException as err: continue except BaseException as err: return [] return car_list<file_sep>/week2/solution1.py import os import tempfile import argparse import json def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('-k', "--key", help="The key of storage") parser.add_argument('-v', "--value", help="Inserted value") args = parser.parse_args() return [args.key, args.value] def get_from_starage(key): storage_path = os.path.join(tempfile.gettempdir(), 'storage.data') with open(storage_path, 'a') as f: pass res = [] with open(storage_path, 'r') as f: rows = f.readlines() for row in rows: r = json.loads(row) if key in r: res.append(r[key]) return res def write_to_starage(key, value): storage_path = os.path.join(tempfile.gettempdir(), 'storage.data') with open(storage_path, 'a') as f: obj = {key: value} f.write(json.dumps(obj) + '\n') if __name__ == '__main__': key, value = parse_args() if key and value: write_to_starage(key, value) elif key: res = get_from_starage(key) if res: print(', '.join(res)) else: print(None) else: pass<file_sep>/week4/02_getattr.py class Researcher: def __getattr__(self, name): return 'Nothing found :(' def __getattribute__(self, name): return 'nope' class Researcher2: def __getattr__(self, name): return 'Nothing found :(' def __getattribute__(self, name): print('Looking for {}'.format(name)) return object.__getattribute__(self, name) class Ignorant: def __setattr__(self, key, value): print('Not gonna set {}!'.format(key)) class Polite: def __delattr__(self, item): value = getattr(self, item) print(f"Goodbye {item}, you were {value}!") object.__delattr__(self, item) class Logger: def __init__(self, filename): self.filename = filename # def __call__(self, func): # with open(self.filename, 'w') as f: # f.write('Oh Danny boy...') # return func def __call__(self, func): def wrapped(*args, **kwargs): with open(self.filename, 'a') as f: f.write('Oh Danny boy...') return func(*args, *kwargs) return wrapped obj = Researcher() print(obj.attr) print(obj.method) print(obj.DFG2H3J00KLL) obj2 = Researcher2() print(obj2.attr) print(obj2.method) print(obj2.DFG2H3J00KLL) obj3 = Ignorant() obj3.math = True #print(obj3.math) #AttributeError obj4 = Polite() obj4.attr = 10 del obj4.attr logger = Logger('log.txt') @logger def completely_useless_function(): pass completely_useless_function() with open('log.txt', 'r') as f: print(f.read())<file_sep>/week2/2_tuple.py empty_tuple = () empty_typle = tuple() immutables = (int, str, tuple) #immutables[0] = float #TypeError blink = ([], []) blink[0].append(0) print(blink) print(hash(tuple())) one_element_typle = (1,) guess_what = (1) print(type(one_element_typle)) print(type(guess_what))<file_sep>/week1/3_string.py example_string = "Курс про Python на Coursera" print(example_string) print(type(example_string)) example_string = 'Курс про "Python" на "Coursera"' print(example_string) example_string = "Курс про \"Python\" на \"Coursera\"" print(example_string) #сырые строки r-string example_string = "Файл на диске c:\\\\" print(example_string) example_string = r"Файл на диске c:\\" print(example_string) #long string example_string = "Python cource " \ "on Coursera " \ "Hello world" print(example_string)\ example_string = """ Есть всего два типа языков программирования: те, на которые люди всё время ругаются, и те, которые никто не использует. <NAME> """ print(example_string) first_string = "First " second_string = "string" concat_string = first_string + second_string print(first_string) print(second_string) print(concat_string) print(first_string * 3) #immutable string example_string = "Hello" print(id(example_string), example_string) example_string += " world!" print(id(example_string), example_string) #string slice [start:stop:step] example_string = "Курс про Python на Coursera" print(example_string[:9]) print(example_string[9:]) print(example_string[2:9]) print(example_string[2:9:2]) print(example_string[2::2]) print(example_string[-8:]) example_string = "0123456789" print(example_string[::2]) example_string = "Kyiv" print(example_string[::-1]) example_string = """ Болтовня ничего не стоит. Покажи мне код. <NAME> """ print(example_string.count("о")) print("kyiv".capitalize()) print("2018".isdigit()) #operator in print("3.14" in "Number Pi = 3.1415926") print("Алексей" in "Александр Пушкин") #operator for .. in example_string = "Hello" for letter in example_string: print("Letter", letter) num_string = str(901.25) print(num_string, type(num_string)) print(bool("not empty string")) print(bool("")) #String formating #first exapmle template = "%s - главное достоинство программиста. (%s)" print(template % ("Лень", "Larry Wall")) #second example print("{} не лгут, но {} пользуются формулами. ({})".format("Цифры", "лжецы", "<NAME>")) #third example print("{num} Кб должно хватить для любых задач. ({author})".format(num = 640, author = "<NAME>")) #f-string subject = "оптимизация" author = "<NAME>" print(f"Преждевременная {subject} - корень всех зол. ({author})") num = 8 print(f"{num} in binary: {num:#b}") num = 2 / 3 print(num) print(f"{num:.3f}") #name = input("Enter your name: ") #print(f"Hello, {name}") #bytes string (b-string) example_string = b"hello" print(example_string, type(example_string)) for element in example_string: print(element) #error using unicode #example_bytes = b"привет" example_string = "привет" print(example_string) print(type(example_string)) encoded_string = example_string.encode(encoding='utf-8') print(encoded_string) print(type(encoded_string)) decoded_string = encoded_string.decode(encoding='utf-8') print(decoded_string) print(type(decoded_string)) <file_sep>/week4/04_getitem.py class PascalList: def __init__(self, original_list=None): self.container = original_list or [] def __getitem__(self, index): return self.container[index - 1] def __setitem__(self, key, value): self.container[key - 1] = value def __str__(self): return self.container.__str__() numbers = PascalList([1, 2, 3, 4, 5]) print(numbers[1]) numbers[5] = 25 print(numbers) <file_sep>/week2/solution2.py import json import functools def to_json(func): @functools.wraps(func) def wrapped(*argsm, **kwargs): res = func(*argsm, **kwargs) return json.dumps(res) return wrapped<file_sep>/week4/01_singelton.py class Singelton: instance = None def __new__(cls, *args, **kwargs): if cls.instance is None: cls.instance = super().__new__(cls, *args, **kwargs) return cls.instance class User: def __init__(self, name, email): self.name = name self.email = email def __str__(self): return '{} <{}>'.format(self.name, self.email) def __hash__(self): return hash(self.email) def __eq__(self, other): return self.email == other.email a = Singelton() b = Singelton() print(a is b) jane = User('<NAME>', '<EMAIL>') joe = User('<NAME>', '<EMAIL>') print(jane) print(jane == joe) print(hash(jane)) print(hash(joe)) user_email_map = {user: user.name for user in [jane, joe]} print(user_email_map) <file_sep>/week2/1_list.py empty_list = [] empty_list = list() none_list = [None] * 10 collections = ['list', 'tuple', 'dict', 'set'] user_data = [ ['Elena', 4.4], ['Andrey', 4.2] ] list_len = len(collections) print(list_len) print(collections) print(collections[0]) print(collections[-1]) collections[3] = 'frozenset' print(collections) #collections[10] #IndexError print('tuple' in collections) range_list = list(range(10)) print(range_list) print(range_list[1:3]) print(range_list[3:]) print(range_list[:5]) print(range_list) print(range_list[::2]) print(range_list[::-1]) print(range_list[5:1:-1]) print(range_list[:] is range_list) for collection in collections: print("Learning {}...".format(collection)) for idx, collection in enumerate(collections): print('#{} {}'.format(idx, collection)) collections.append('OrderedDict') print(collections) collections.extend(['ponyset', 'unicorndict']) print(collections) collections += [None] print(collections) del collections[7] print(collections) numbers = [4, 17, 19, 9, 2, 6, 10, 13] print(min(numbers)) print(max(numbers)) print(sum(numbers)) tag_list = ['python', 'cource', 'courcera'] print(', '.join(tag_list)) import random numbers = [] for _ in range(10): numbers.append(random.randint(1, 20)) print(numbers) print(sorted(numbers)) print(numbers) numbers.sort() print(numbers) print(sorted(numbers, reverse=True)) print(numbers) numbers.sort(reverse=True) print(numbers) print(reversed(numbers)) print(list(reversed(numbers)))<file_sep>/week1/1_base_type.py num = 1 print(num, type(num)) big_num = 1_000_000 print(big_num, type(big_num)) num_float = 3.1415 print(num_float, type(num_float)) big_num_float = 1_000_000.000_001 print(big_num_float, type(big_num_float)) exp_float_num = 1.5e2 print(exp_float_num, type(exp_float_num)) float_to_int = int(num_float) print(float_to_int, type(float_to_int)) int_to_float = float(num) print(int_to_float, type(int_to_float)) complex_num = 14 + 1j print(complex_num, type(complex_num), complex_num.real, complex_num.imag) str = "Some string" print(str, type(str)) sum1 = 1 + 2 print(sum1, type(sum1)) sum2 = 1 + 2.0 print(sum2, type(sum2)) sub1 = 10 - 1 print(sub1, type(sub1)) sub2 = 10 - 1.0 print(sub2, type(sub2)) div1 = 10 / 2 print(div1, type(div1)) #div2 = 10 / 0 #ZeroDivisionError mul1 = 4 * 5.25 print(mul1, type(mul1)) mul2 = 4 * 5 print(mul2, type(mul2)) num_sqrt = 4 ** 2 print(num_sqrt, type(num_sqrt)) num_sqrt2 = 4 ** (1 / 2) print(num_sqrt2, type(num_sqrt2)) num_sqrt3 = 4 ** -2 print(num_sqrt3, type(num_sqrt3)) div_ceil = 10 // 3 print(div_ceil, type(div_ceil)) div_rem = 10 % 3 print(div_rem, type(div_rem)) print(10 * 3 + 3) print(10 * (3 + 3)) x = 4 y = 3 print("Побитовое или:", x | y) print("Побитовое исключающее или:", x ^ y) print("Побитовое и:", x & y) print("Побитовый сдвиг влево:", x << 3) print("Побитовое сдвиг вправо:", x >> 1) print("Инверсия битов:", ~x) #нахождение гипотенузы #распаковка значений x1, y1 = 0, 0 x2 = 3 y2 = 4 distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5 print("Решение:", distance, type(distance)) #меняем местами 2 значения a = 100 b = 200 print("Before", a, b) a, b = b, a print("After", a, b) #immutable example x = y = 0 x += 1 print(x, y) #mutable example x = y = [] x.append(1) x.append(2) print(x, y)<file_sep>/week2/13_list_comprehensions.py square_list = [] for number in range(10): square_list.append(number ** 2) print(square_list) square_list2 = [number ** 2 for number in range(10)] print(square_list2) even_list = [] for number in range(10): if number % 2 == 0: even_list.append(number) print(even_list) even_list2 = [num for num in range(10) if num % 2 == 0] print(even_list2) square_map = {number: number **2 for number in range(5)} print(square_map) reminders_set = {num %10 for num in range(100)} print(reminders_set) print(type(num ** 2 for num in range(5))) num_list = range(7) squared_list = [x ** 2 for x in num_list] r1 = list(zip(num_list, squared_list)) print(r1) r2 = list(zip( filter(bool, range(3)), [x for x in range(3) if x] )) print(r2)<file_sep>/week1/8_object_struct.py num = 13 num = num.__add__(2) print(num)<file_sep>/week1/2_base_logical_type.py #bool print(True, type(True)) print(False, type(False)) res = True print(type(res)) print("Equals",13 == 13, type(13 == 13)) print("Not equals", 13 != 14, type(13 != 14)) print("More", 3 > 4, type(3 > 4)) print("Less or equals", 3 <= 4, type(3 <= 4)) print("More or equals", 3 >= 4, type(3 >= 4)) print("Less", 3 < 4, type(3 < 4)) #mass equals x = 2 print("Mass equals", 1 < x < 3, type(1 < x < 3)) print(bool(12), type(bool(12))) print(bool(0), type(bool(0))) x, y = True, False print("Logical and", x and y) print("Logical or", x or y) print("Logical not", not y) #lazy loads x = 12 y = False print(x or y, type(x or y)) x = 12 z = "boom" print(x and z, type(x and z)) #It is a leap year? year = 2017 is_leap = year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) print(is_leap, type(is_leap)) import calendar print(calendar.isleap(year))<file_sep>/week1/5_if_operator.py company = "my.com" if "my" in company: print("Условие выполнено!") company = "example.net" if "my" in company or company.endswith(".net"): print("Условие выполнено!") company = "google.com" if "my" in company: print("Условие выполнено!") else: print("Условие не выполнено!") company = "google.com" if "my" in company: print("Подстрока my найдена") elif "google" in company: print("Подстрока google найдена") else: print("Подстрока не найдена") #ternary operator score_1 = 5 score_2 = 0 winner = "Argentina" if score_1 > score_2 else "Jamaica" print(winner) #while loop i = 0 while i < 100: i += 1 print("while loop") print(i) #for loop, range object name = "Igor" print("String for iteration") for letter in name: print(letter) print("range for iteraion") for i in range(3): print(i) result = 0 for i in range(101): result += i print("Summ of range numbers") print(result) print("Range diapason") for i in range(5, 8): print(i) print("Range diapason with step") for i in range(1, 10, 2): print(i) print("Revert range") for i in range(10, 1, -1): print(i) #pass operator print("pass opertor") for i in range(100): pass #break operator print("break operator") result = 0 while True: result += 1 if result >= 100: break print(result) print("break in for") for i in range(10): if i == 5: break print(i) #continue operator result = 0 print("sum even numbers") for i in range(10): if i % 2 != 0: continue result += i print(result) <file_sep>/week2/11_functional_programming.py def caller(func, params): return func(*params) def printer(name, origin): print("I'm {} of {}!".format(name, origin)) caller(printer, ['Moana', 'Motunui']) def get_multiplier(): def inner(a, b): return a * b return inner multiplier = get_multiplier() print(multiplier(10, 11)) print(multiplier.__name__) def get_multiplier2(number): def inner(a): return a * number return inner multiplier_by_2 = get_multiplier2(2) print(multiplier_by_2(10)) def squarify(a): return a ** 2 r1 = list(map(squarify, range(5))) print(r1) squarify_list = [] for number in range(5): squarify_list.append(squarify(number)) print(squarify_list) def is_positive(a): return a > 0 r2 = list(filter(is_positive, range(-2, 3))) print(r2) positive_list = [] for number in range(-2, 3): if is_positive(number): positive_list.append(number) print(positive_list)<file_sep>/week2/12_lambda_functions.py r1 = list(map(lambda x: x ** 2, range(5))) print(r1) print(type(lambda x: x ** 2)) r2 = list(filter(lambda x: x > 0, range(-2, 3))) print(r2) def stringify_list(num_list): return list(map(str, num_list)) r3 = list(map(lambda x: str(x), range(10))) r4 = list(map(str, range(10))) r5 = stringify_list(range(10)) print(r3) print(r4) print(r5) from functools import reduce def multiply(a, b): return a * b r6 = reduce(multiply, range(1, 6)) print(r6) r7 = reduce(lambda a, b: a * b, range(1, 6)) print(r7) from functools import partial def greeter(person, greeting): return '{}, {}!'.format(greeting, person) hier = partial(greeter, greeting="Hi") helloer = partial(greeter, greeting="Hello") print(hier('brother')) print(helloer('sir'))<file_sep>/week1/7_modules_packages.py from mypackage.utils import * import inspect import os if __name__ == "__main__": print(multiply(2, 3)) #inspect.getfile(this) #os.listdir(inspect.getfile(this)) <file_sep>/week1/9_bytecode.py from mypackage.utils import multiply import dis import opcode print(dir(multiply)) print(multiply.__code__) print(multiply.__code__.co_code) print(dis.dis(multiply)) print(opcode.opmap)<file_sep>/week2/10_files.py f = open('test.txt', 'w') text_modes = ['r', 'w', 'a', 'r+'] binary_modes = ['br', 'bw', 'ba', 'br+'] f.write("The world is changed. \nI taste it in the watter.\n") f.close() f = open('test.txt', 'r+') f.read() f.tell() f.read() f.seek() f.read() f.close() f = open('test.txt', 'r+') f.readline() f.close() f = open('test.txt', 'r+') f.readlines() f.close() with open('test.txt') as f: print(f.read())
1cd123c7f356f47762cb2bd1f839ee1d9b98bc48
[ "Markdown", "Python" ]
25
Markdown
nidzelskyy/coursera_python_course
4232e13bb4ca5c1e63d8b88af311a9e58a37d740
35cd4f546340c461150516d0c9a2211903478222
refs/heads/master
<file_sep>#include <stdio.h> int main(void) { char buffer[] = "1234\n"; printf("sizeof '1234\\n\\0' = %d\n", (int)sizeof(buffer)); return 0; } <file_sep>#include <pcre.h> #include <stdio.h> #include <string.h> int main(void) { pcre *re; const char *sampleData = "\rNet: dm9000\n\rHit any key to stop autoboot: disabled\n\r2 seconds remain until autoboot, $bootdelaykey{,2} to cancel\n\rDefault values: spac, ctrl-c"; const char *regex = "(Hit any key to stop autoboot)|([\\n\\r]+\\$ $)"; const char *errorMsg; int errorOffset; int rc; re = pcre_compile( regex, PCRE_DOLLAR_ENDONLY | PCRE_DOTALL | PCRE_UTF8 | PCRE_NEWLINE_LF, &errorMsg, &errorOffset, 0); if (re == 0) { printf("Regex failed @ %d offset: %s\n", errorOffset, errorMsg); return 1; } rc = pcre_exec( re, NULL, sampleData, strlen(sampleData), 0, PCRE_NEWLINE_LF, NULL, 0); if (rc == 0) { printf("Matched\n"); } else { printf("No matched\n"); } return 0; } <file_sep>CC := gcc EXT ?= PROGS := $(addsuffix $(EXT),$(basename $(wildcard *.c))) PCRE_PROGS := $(addsuffix $(EXT),$(basename $(wildcard pcre_*.c))) PCRE_LIBS := -L../pcre -lpcre pcre_test1.c_LIBS := $(PCRE_LIBS) all: $(PROGS) clean: rm -f $(PROGS) .PHONY: all clean .SECONDEXPANSION: $(PROGS): %$(EXT): %.c $(CC) -Wall -O2 $< $($<_CFLAGS) -o $@ $($<_LIBS)
752d21144b84dda6344d71c6a41ae6ac2d96b80a
[ "C", "Makefile" ]
3
C
aeruder/testcprogs
edfb3476437f6aa479fa8b16d25e669175286106
ad61260a9288e332f855a0e768932b0daa7df3f0
refs/heads/master
<file_sep>package mediabrowser.model.livetv; public class ListingsProviderInfo { private String Id; public final String getId() { return Id; } public final void setId(String value) { Id = value; } private String Type; public final String getType() { return Type; } public final void setType(String value) { Type = value; } private String Username; public final String getUsername() { return Username; } public final void setUsername(String value) { Username = value; } private String Password; public final String getPassword() { return Password; } public final void setPassword(String value) { Password = value; } private String ListingsId; public final String getListingsId() { return ListingsId; } public final void setListingsId(String value) { ListingsId = value; } private String ZipCode; public final String getZipCode() { return ZipCode; } public final void setZipCode(String value) { ZipCode = value; } private String Country; public final String getCountry() { return Country; } public final void setCountry(String value) { Country = value; } private String Path; public final String getPath() { return Path; } public final void setPath(String value) { Path = value; } private String[] EnabledTuners; public final String[] getEnabledTuners() { return EnabledTuners; } public final void setEnabledTuners(String[] value) { EnabledTuners = value; } private boolean EnableAllTuners; public final boolean getEnableAllTuners() { return EnableAllTuners; } public final void setEnableAllTuners(boolean value) { EnableAllTuners = value; } public ListingsProviderInfo() { setEnabledTuners(new String[] { }); setEnableAllTuners(true); } }<file_sep>package mediabrowser.apiinteraction.android.sync.data; import android.content.Context; import mediabrowser.apiinteraction.sync.data.FileRepository; import mediabrowser.model.logging.ILogger; import java.io.File; /** * Created by Luke on 3/25/2015. */ public class AndroidFileRepository extends FileRepository { protected Context context; public AndroidFileRepository(Context context, ILogger logger) { super(logger); this.context = context; } @Override protected String getBasePath() { File directory = context.getExternalFilesDir(null); if (directory == null){ directory = context.getFilesDir(); } File file = new File(directory, "sync"); return file.getPath(); } }
c0d54edd4c86fe8b8d65088c92c2d21cbb30484d
[ "Java" ]
2
Java
MithrilTuxedo/Emby.ApiClient.Java
8813d4ec87984f354ef731cde4ba559e57239a8e
5ab517e2d078c55a1871f7893249e246646121db
refs/heads/master
<file_sep># Goldmaster testing Inspired by [RailsConf 2017: A Gold Master Test in Practice by <NAME>](https://www.youtube.com/watch?v=D9awDBUQvr4)<file_sep>class Foo def initialize(v, w, x, y, z) @v = v @w = w @x = x @y = y @z = z end def bar ((@z && (@x || @y)) && ((@x && @y) || (@x && @z))) || (((@w || @v) || !@x) && (@x && (@y && @z))) end end <file_sep>RSpec.describe Foo do describe '#bar' do let(:csv_goldmaster) { CSV.read('spec/fixtures/goldmaster.csv') } it 'produce a consistent result' do out_path = 'spec/fixtures/goldmaster.out' bar_values = csv_goldmaster.map do |row| Foo.new(row[0], row[1], row[2], row[3], row[4]).bar end if !File.exist?(out_path) write_goldmaster(csv_goldmaster, out_path) else goldmaster_to_ary = CSV.foreach(out_path).map(&:first) expect(bar_values).to eql(goldmaster_to_ary) end end end def write_goldmaster(csv, path) csv.each do |row| open(path, 'a') do |f| f.puts Foo.new(row[0], row[1], row[2], row[3], row[4]).bar end end end end
264fe8f7d1cac17a69b53f6776bd7491e1729e2d
[ "Markdown", "Ruby" ]
3
Markdown
nicolaslechenic/goldmaster
bad58be5c0319ad2cdaf65c225306d9f28aa15ac
2506989173f63da4260953e362073d8d5c421006
refs/heads/master
<repo_name>Yicong-Huang/TwiSpider<file_sep>/src/job.py from datetime import datetime from twitter import Status class Job: def __init__(self, tweet: Status, original_tweet_retweet_count=0): self.tweet_id = tweet.id self.tweet_created_at = datetime.strptime(tweet.created_at, '%a %b %d %H:%M:%S %z %Y').timestamp() self.retweet_count = tweet.retweet_count - original_tweet_retweet_count self.last_check_time = self.tweet_created_at def retweet_rate(self): return self.retweet_count / (datetime.now().timestamp() - self.tweet_created_at) def __lt__(self, other): return self.possible_retweets() < other.possible_retweets() def __hash__(self): return self.tweet_id def __str__(self): return f'Job[id={self.tweet_id}, created_at={self.tweet_created_at}, retweet_count={self.retweet_count},' \ f' last_check_time={self.last_check_time}, retweet_rate={self.retweet_rate()}, ' \ f'possible_retweets={self.possible_retweets()}]' def __eq__(self, other): return hash(self) == hash(other) def set_check_time(self): self.last_check_time = datetime.now().timestamp() def should_check(self): return self.possible_retweets() > 1 or \ (self.retweet_rate() == 0 and (datetime.now().timestamp() - self.last_check_time) > 30 * 60 and ( datetime.now().timestamp() - self.tweet_created_at) < 60 * 60 * 3) def possible_retweets(self): delta_time = datetime.now().timestamp() - self.last_check_time return delta_time * self.retweet_rate() __repr__ = __str__ <file_sep>/src/dumpers/twitter_retweet_of_dumper.py import logging from dumpers.dumperbase import DumperBase from utilities.connection import Connection logger = logging.getLogger(__name__) class TweetRetweetOfDumper(DumperBase): def __init__(self): super().__init__() def insert(self, original_tweet_id, retweet_id) -> None: Connection.sql_execute_commit( f"INSERT INTO retweet_of values ({original_tweet_id}, {retweet_id}) ON CONFLICT DO NOTHING") if __name__ == '__main__': logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler()) tweet_dumper = TweetRetweetOfDumper() # id mode tests: tweet_dumper.insert(1, 2) <file_sep>/README.md # TwiSpider Crawling Tweets as a Network. Given a list of keywords, TwiSpider will crawl for real time tweets with this keyword(s). It saves the original tweet of it if that's a retweet. It then monitors the original tweets in a regualar basis. # Setup ## Environment postgresql@11 postgis@3.0 python@3.6+ ## Dependency `pip install -r requirements.txt` # Quick Start 1. Fill in configs. Make a copy from `.template` files. For example, copy a file from `twitter.ini.template` and name it as `twitter.ini`, fill your api information inside. 2. Edit `src/keywords.txt` for monitored keywords, one at a line. Space means boolean AND. `hpv vaccine` will monitor tweets that both contain `hpv` and `vaccine` 3. Create tables with `src/sqls/create_tables.sql` 4. Run with `python3 src/main.py` <file_sep>/src/api/twitter_api_load_balancer.py import twitter from paths import TWITTER_API_CONFIG_PATH from utilities.ini_parser import parse class TwitterAPILoadBalancer: def __init__(self): self.apis = [twitter.Api(**config, sleep_on_rate_limit=True) for config in parse(TWITTER_API_CONFIG_PATH).values()] self.iter_index = -1 def get(self): self.iter_index += 1 if self.iter_index == len(self): self.iter_index = 0 return self.apis[self.iter_index] def __len__(self): return self.apis.__len__() if __name__ == '__main__': twitter_api_load_balancer = TwitterAPILoadBalancer() for i in range(19): print(twitter_api_load_balancer.get()) <file_sep>/src/crawlers/twitter_retweet_crawler.py import logging import time import traceback from typing import List import twitter from twitter import TwitterError from api.twitter_api_load_balancer import TwitterAPILoadBalancer from crawlers.crawlerbase import CrawlerBase logger = logging.getLogger(__name__) class TweetRetweetCrawler(CrawlerBase): MAX_WAIT_TIME = 256 def __init__(self): super().__init__() self.wait_time = 1 self.api_load_balancer = TwitterAPILoadBalancer() self.data: List[twitter.Status] = [] self.total_crawled_count = 0 def crawl(self, tweet_id) -> List[twitter.Status]: """ Crawling twitter.Status with the given Tweet Id. Args: tweet_id (int): the tweet id to be crawled Returns: twitter.Status """ logger.info(f'Crawler Started') while True: try: logger.info(f'Sending a Request to Twitter Get Retweets API') tweets = self.api_load_balancer.get().GetRetweets(tweet_id, count=100) self.reset_wait_time() return tweets except TwitterError as err: # if err.args[0][0]['code'] == 34: # logger.info("Skipping since the tweet has been deleted") # return [] # elif err.args[0][0]['code'] == 200 and err.args[0][0]['message'] == "Forbidden.": # logger.info("Skipping since the tweet is from a private account") # return [] # else: logger.error('error: ' + traceback.format_exc()) # in this case the collected twitter id will be recorded and tried again next time try: self.wait() except TimeoutError: return [] except: logger.error('error: ' + traceback.format_exc()) # in this case the collected twitter id will be recorded and tried again next time logger.error(f'skipped: {tweet_id}') return [] def reset_wait_time(self): """resets the wait time""" self.wait_time = 1 def wait(self) -> None: """Incrementally waits when the request rate hits limitation.""" time.sleep(self.wait_time) if self.wait_time < self.MAX_WAIT_TIME: # set a wait time limit no longer than 64s self.wait_time *= 2 # an exponential back-off pattern in subsequent reconnection attempts else: raise TimeoutError if __name__ == '__main__': logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler()) tweet_retweet_crawler = TweetRetweetCrawler() status = tweet_retweet_crawler.crawl(1198263248036007936) print(status) <file_sep>/src/crawlers/twitter_filter_api_crawler.py import logging import pickle import time import traceback from typing import List from api.twitter_api_load_balancer import TwitterAPILoadBalancer from crawlers.crawlerbase import CrawlerBase from paths import ID_CACHE_PATH from utilities.cacheset import CacheSet logger = logging.getLogger(__name__) class TweetFilterAPICrawler(CrawlerBase): MAX_WAIT_TIME = 64 def __init__(self): super().__init__() self.wait_time = 1 self.api_load_balancer = TwitterAPILoadBalancer() self.data: List = [] self.keywords = [] self.total_crawled_count = 0 try: with open(ID_CACHE_PATH, 'rb') as cache_file: self.cache = pickle.load(cache_file) except: self.cache: CacheSet[int] = CacheSet() def crawl(self, keywords: List, batch_number: int = 100) -> List[int]: """ Crawling Tweet ID with the given keyword lists, using Twitter Filter API Twitter Filter API only provides compatibility mode, thus no `full_text` is returned by the API. Have to crawl for IDs and then fetch full_text with GetStatus, which will be in other thread. Args: keywords (List[str]): keywords that to be used for filtering tweet text, hash-tag, etc. Exact behavior is defined by python-twitter. batch_number (int): a number that limits the returned list length. using 100 as default since Twitter API limitation is set to 100 IDs per request. Returns: (List[int]): a list of Tweet IDs """ self.keywords = list(map(str.lower, keywords + ["#" + keyword for keyword in keywords])) logger.info(f'Crawler Started') self.data = [] count = 0 while len(self.data) < batch_number: logger.info(f'Sending a Request to Twitter Filter API') try: for tweet in self.api_load_balancer.get().GetStreamFilter(track=self.keywords, languages=['en']): self.reset_wait_time() if tweet.get('retweeted_status'): self._add_to_batch(tweet['retweeted_status']['id']) else: self._add_to_batch(tweet['id']) # print Crawling info if len(self.data) > count: count = len(self.data) if count % (batch_number // 10) == 0: logger.info(f"Crawled ID count in this batch: {count}") if count >= batch_number: break except: # in this case the collected twitter id will be recorded and tried again next time logger.error(f'Error: {traceback.format_exc()}') self.wait() count = len(self.data) with open(ID_CACHE_PATH, 'wb+') as cache_file: pickle.dump(self.cache, cache_file) logger.info(f'Outputting {count} Tweet IDs') self.total_crawled_count += count logger.info(f'Total crawled count {self.total_crawled_count}') return self.data def _add_to_batch(self, tweet_id: int) -> None: if tweet_id not in self.cache: self.data.append(tweet_id) self.cache.add(tweet_id) def reset_wait_time(self) -> None: """resets the wait time""" self.wait_time = 1 def wait(self) -> None: """Incrementally waits when the request rate hits limitation.""" time.sleep(self.wait_time) if self.wait_time < self.MAX_WAIT_TIME: # set a wait time limit no longer than 64s self.wait_time *= 2 # an exponential back-off pattern in subsequent reconnection attempts if __name__ == '__main__': logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler()) tweet_filter_api_crawler = TweetFilterAPICrawler() for _ in range(3): raw_tweets = tweet_filter_api_crawler.crawl(['hpv vaccine', 'hpvvaccine'], batch_number=1) print(raw_tweets) <file_sep>/src/sqls/create_tables.sql create table if not exists tweets ( id bigint not null constraint tweets_pk primary key, create_at timestamp, text text, original_tweet_retweet_count integer, location text, hash_tags text, profile_pic text, screen_name text, user_name text, created_date_time timestamp, followers_count integer, favourites_count integer, friends_count integer, user_id bigint, user_location text, statuses_count integer ); create table if not exists retweet_of ( original_tweet_id bigint not null constraint retweet_of_tweets_id_fk references tweets, retweet_tweet_id bigint not null constraint retweet_of_tweets_id_fk_2 references tweets, constraint retweet_of_pk primary key (original_tweet_id, retweet_tweet_id) ); <file_sep>/src/server.py import logging import time import sh from flask import Flask, render_template from flask_socketio import SocketIO, emit logging.basicConfig(level=logging.DEBUG) app = Flask(__name__) app.config.from_mapping( SECRET_KEY='dev', ) socketio = SocketIO(app) tail = None frontier_size = None top_10 = None current_job = None previous_job = None current_iteration_count = None @app.route('/') def status(): return render_template('index.html') @app.route('/') def index(): """Serve the index HTML""" return render_template('index.html') def status_update(line): global frontier_size, current_job, previous_job, current_iteration_count if 'monitoring' in line: frontier_size = line if 'done with Job' in line: previous_job = line if '----> Checking' in line: current_iteration_count = line if 'running for Job' in line: current_job = line @socketio.on('status') def status(): while True: emit('status', [frontier_size, current_iteration_count, previous_job, current_job]) time.sleep(1) @socketio.on('log') def log(): global tail tail = sh.tail("-f", "-n", "2000", "/Users/yicong/Library/Mobile Documents/com~apple~CloudDocs/Research/TwiSpider/nohup.out", _iter=True) while True: log = tail.next() if log: status_update(log) emit('log', log) if __name__ == '__main__': from argparse import ArgumentParser from waitress import serve parser = ArgumentParser() parser.add_argument("--deploy", help="deploy server in production mode", action="store_true") args = parser.parse_args() if args.deploy: serve(app, host='0.0.0.0', port=2333) else: socketio.run(app, port=5000, debug=True) <file_sep>/src/extractor/twitter_extractor.py import datetime import json import logging from datetime import datetime from typing import List, Iterable from twitter import Status from crawlers.twitter_id_mode_crawler import TweetIDModeCrawler from extractor.extractorbase import ExtractorBase logger = logging.getLogger(__name__) class TweetExtractor(ExtractorBase): def __init__(self): super().__init__() self.data: list = [] def extract(self, tweets: Iterable[Status]) -> List: """extracts useful information after being provided with original tweet data (similar to a filter)""" collected_ids = set() self.data.clear() for tweet in tweets: id = tweet.id if id not in collected_ids: collected_ids.add(id) # extracts (filters) the useful information user = tweet.user [[top_left, _, bottom_right, _]] = tweet.place['bounding_box']['coordinates'] if tweet.place else [ [None] * 4] self.data.append( {'id': id, 'date_time': datetime.strptime(tweet.created_at, '%a %b %d %H:%M:%S %z %Y'), 'full_text': tweet.full_text, 'hash_tags': [tag.text for tag in tweet.hashtags], 'top_left': top_left, 'bottom_right': bottom_right, 'original_tweet_retweet_count': tweet.retweet_count, 'profile_pic': user.profile_image_url, 'screen_name': user.screen_name, 'user_name': user.name, 'created_date_time': datetime.strptime(tweet.user.created_at, '%a %b %d %H:%M:%S %z %Y'), 'followers_count': user.followers_count, 'favourites_count': user.favourites_count, 'friends_count': user.friends_count, 'user_id': user.id, 'user_location': user.location if user.geo_enabled else 'None', 'statuses_count': user.statuses_count}) return self.data # stores self.data and returns a reference of it def export(self, file_type: str, file_name: str) -> None: """exports data with specified file type""" # for example, json replace_list = list(self.data) # make replace_list equal to self.data and change it if file_type == 'json': for each_extractor_line in replace_list: each_extractor_line['date_time'] = str(each_extractor_line['date_time']) # json does not accept datetime values, does change it into string json.dump(replace_list, open(file_name, 'w')) if __name__ == '__main__': logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler()) tweet_id_mode_crawler = TweetIDModeCrawler() tweet_extractor = TweetExtractor() raw_ids = [1198260660263624704, 1198260018602237952, 1198249993070624770, 1198238472206729216, 1198238463063187456, 1198254653827366917, 1198257144744890374, 1198236032803758080, 1198227110843863043, 1198218486511808513, 1198215395024527360, 1198144558049189889, 1198094686507982849, 1198089147803557890, 1198081137106657282, 1198059467323121666, 1198173800434749440, 1198195017795407872, 1198115743180689408, 1198073343729111040, 1198047793845280768, 1198144719030759424, 1198157405705650176, 1198039714529447937, 1198152680960675840] status = tweet_id_mode_crawler.crawl(raw_ids) print(tweet_extractor.extract(status)) <file_sep>/requirements.txt sh waitress flask beautifulsoup4==4.8.1 certifi==2019.9.11 chardet==3.0.4 future==0.18.2 idna==2.8 oauthlib==3.1.0 psycopg2==2.8.4 python-twitter==3.5 requests==2.22.0 requests-oauthlib==1.3.0 selenium==3.141.0 setuptools==40.8.0 soupsieve==1.9.5 urllib3==1.25.7<file_sep>/src/twi_spider.py import logging import pickle import threading import time from crawlers.twitter_filter_api_crawler import TweetFilterAPICrawler from crawlers.twitter_id_mode_crawler import TweetIDModeCrawler from crawlers.twitter_retweet_crawler import TweetRetweetCrawler from crawlers.twitter_search_api_crawler import TweetSearchAPICrawler from dumpers.twitter_dumper import TweetDumper from dumpers.twitter_retweet_of_dumper import TweetRetweetOfDumper from extractor.twitter_extractor import TweetExtractor from job import Job from paths import FRONTIER_CACHE_PATH from utilities.connection import Connection logger = logging.getLogger(__name__) class TwiSpider: def __init__(self, keywords=None): self.keywords = ['hpv vaccine', 'hpvvaccine'] if keywords is None else keywords try: print(FRONTIER_CACHE_PATH) with open(FRONTIER_CACHE_PATH, 'rb') as cache_file: self.frontier = pickle.load(cache_file) except: self.frontier = set() self.twitter_filter_api_crawler = TweetFilterAPICrawler() self.twitter_search_api_crawler = TweetSearchAPICrawler() self.twitter_id_mode_crawler = TweetIDModeCrawler() self.twitter_retweet_crawler = TweetRetweetCrawler() self.twitter_dumper = TweetDumper() self.twitter_retweet_of_dumper = TweetRetweetOfDumper() self.twitter_extractor = TweetExtractor() def run_crawler_for_root_tweets(self, crawler, batch_number, sleep_time): while True: root_tweet_ids = crawler.crawl(self.keywords, batch_number) self.crawl_for_root_tweets(root_tweet_ids) time.sleep(sleep_time) def run(self): self.load_root_tweets() threading.Thread(target=self.run_crawler_for_root_tweets, args=(self.twitter_search_api_crawler, 1, 1)).start() threading.Thread(target=self.run_crawler_for_root_tweets, args=(self.twitter_filter_api_crawler, 100, 10)).start() threading.Thread(target=self.run_monitor).start() def run_monitor(self): logger.info(f'monitoring {len(self.frontier)}') logger.info(self.frontier) while True: if self.frontier: check_list = sorted(filter(lambda job: job.should_check(), list(self.frontier)), reverse=True) if check_list: logger.info(f"----> Checking {len(check_list)} in this iteration") ids = [job.tweet_id for job in check_list] self.crawl_for_root_tweets(ids) for job in check_list: logger.info(f"running for {job}") new_tweets = self.twitter_retweet_crawler.crawl(job.tweet_id) self.twitter_dumper.insert(self.twitter_extractor.extract(new_tweets)) for new_retweeted_tweet in new_tweets: self.twitter_retweet_of_dumper.insert(job.tweet_id, new_retweeted_tweet.id) job.retweet_count = max(job.retweet_count, new_retweeted_tweet.retweet_count) job.set_check_time() time.sleep(7) with open(FRONTIER_CACHE_PATH, 'wb+') as cache_file: pickle.dump(self.frontier, cache_file) logger.info(f"done with {job}") else: logger.info("waiting for 5 seconds") rank_panel = "#### Possible Rank\n" for job in sorted(list(self.frontier), reverse=True)[:10]: rank_panel += f"## {job}\n" rank_panel += "\n" logger.info(rank_panel) time.sleep(5) logger.info(f'monitoring {len(self.frontier)}') def load_root_tweets(self): root_tweet_ids = {id_ for (id_,) in Connection.sql_execute("select id from tweets where text not like 'RT %'")} self.crawl_for_root_tweets(root_tweet_ids) def crawl_for_root_tweets(self, root_tweet_ids): logger.info("Start crawling for root tweets") tweets = self.twitter_id_mode_crawler.crawl(root_tweet_ids) root_tweets = {tweet.retweeted_status if tweet.retweeted_status else tweet for tweet in tweets} self.twitter_dumper.insert(self.twitter_extractor.extract(root_tweets)) self.frontier.update({Job(tweet) for tweet in root_tweets}) <file_sep>/src/main.py import logging import os from paths import KEYWORDS_PATH, CACHE_DIR logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(threadName)s:(%(name)s) [%(funcName)s()] %(message)s') logger = logging.getLogger(__name__) from twi_spider import TwiSpider if __name__ == '__main__': logger.setLevel(logging.DEBUG) if not os.path.exists(CACHE_DIR): os.makedirs(CACHE_DIR) with open(KEYWORDS_PATH) as file: keywords = [line.rstrip() for line in file] TwiSpider(keywords).run() <file_sep>/src/paths.py import os # root path of the project ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) # directory for logs LOG_DIR = os.path.join(ROOT_DIR, 'backend', 'logs') # dir for all configs CONFIGS_DIR = os.path.join(ROOT_DIR, 'configs') # path of the config file for connection to postgresql DATABASE_CONFIG_PATH = os.path.join(CONFIGS_DIR, 'database.ini') # path of the config file for twitter api TWITTER_API_CONFIG_PATH = os.path.join(CONFIGS_DIR, 'twitter.ini') # dir for all cache CACHE_DIR = os.path.join(ROOT_DIR, 'cache') # path of the job frontier set FRONTIER_CACHE_PATH = os.path.join(CACHE_DIR, 'twitter.frontier.pickle') # path of the id CacheSet ID_CACHE_PATH = os.path.join(CACHE_DIR, 'ids.pickle') # path for keywords.txt KEYWORDS_PATH = os.path.join(ROOT_DIR, 'keywords.txt')
d4337721ac13af1860bed329219133a5e5f0b5f9
[ "Markdown", "SQL", "Python", "Text" ]
13
Python
Yicong-Huang/TwiSpider
564e55a58024d2035611500a3b5f3f041e65335d
14e33e796405dbc1794b4364af30fc83f58521b2
refs/heads/master
<repo_name>haoayou4211/baojia01<file_sep>/js/page_api_common.js //日期格式化 Date.prototype.Format = function (fmt) { //author: meizz var o = { "M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "h+": this.getHours(), //小时 "m+": this.getMinutes(), //分 "s+": this.getSeconds(), //秒 "q+": Math.floor((this.getMonth() + 3) / 3), //季度 "S": this.getMilliseconds() //毫秒 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; } //公用方法 var c = {}; c.debug = true,//是否开启调试打印 c.api = { /*获取用户openid*/ getUserOpenID : "/manage/getopenid", /**/ getIndex:"/manage/getindex", }, c.BaseUrl="http://wx.baojiatech.com/weixin/", //服务器端口 // c.BaseUrl="http://1172.16.31.10:8080/weixin/", //测试端口 /** * @param url 请求的地址,域名已经设置 * @param send 发送的数据,json对象 * @param onSuccess 成功回调 * @param onError 失败回调 * @param _this 回调函数的执行域 */ c.get = function(url, send, onSuccess, onError, _this) { if (c.debug) { console.log("====================start request==========================\r\n"); console.log(c.BaseUrl + url); console.log(JSON.stringify(send)); console.log("====================end request==========================\r\n"); } $.ajax({ type:"get", url: c.BaseUrl + url , async:true, data:send, dataType: "json", xhrFields:{ withCredentials:true }, success: function(ret){ if (!ret.success) { if (onError) { if (_this) { onError.call(_this, ret); } else onError(ret); } else { $appFun.errorHandling(ret); } } else { if (_this) { onSuccess.call(_this, ret); } else { onSuccess(ret); } } }, error: function(err){ if (c.debug) { console.log("====================start request==========================\r\n"); console.log(c.BaseUrl + url); console.log(JSON.stringify(send)); console.log(err); console.log("====================end request==========================\r\n"); } } }); }, //post请求 c.post = function(url, send, onSuccess, onError, _this) { if (c.debug) { console.log("====================start request==========================\r\n"); console.log(c.BaseUrl + url); console.log(JSON.stringify(send)); console.log("====================end request==========================\r\n"); } $.ajax({ type:"post", url:c.BaseUrl + url, async:true, data: send, dataType: "json", xhrFields:{ withCredentials:true }, success: function(ret){ if (!ret.success) { if (onError) { if (_this) { onError.call(_this, ret); } else onError(ret); } else { $appFun.errorHandling(ret); } } else { if (_this) { onSuccess.call(_this, ret); } else { onSuccess(ret); } } }, error: function(err){ if (c.debug) { console.log("====================start request==========================\r\n"); console.log(c.BaseUrl + url); console.log(JSON.stringify(send)); console.log(err); console.log("====================end request==========================\r\n"); } } }); }, //jsonP get请求 c.jsonPGet = function (url , send, onSuccess, onError, _this){ if (c.debug) { console.log("====================start request==========================\r\n"); console.log(c.BaseUrl + url); console.log(JSON.stringify(send)); console.log("====================end request==========================\r\n"); } $.ajax({ type:"get", url:url, async:true, dataType: 'jsonp', data: send, jsonp: 'jsonpCallback', jsonpCallback: 'success_jsonpCallback', success: function(ret){ if (ret.code !== 200) { if (onError) { if (_this) { onError.call(_this, ret); } else onError(ret); } else { $appFun.errorHandling(ret); } } else { if (_this) { onSuccess.call(_this, ret); } else { onSuccess(ret); } } }, error:function(err){ if (c.debug) { console.log("====================start request==========================\r\n"); console.log(c.BaseUrl + url); console.log(JSON.stringify(send)); console.log(err); console.log("====================end request==========================\r\n"); } } }); } window.$comm = c; //统一方法 window.$appFun = { //错误处理 errorHandling : function(data) { // alert(JSON.stringify(data)) console.log(data); if (!data) { console.log("data参数不能为空"); return; } if(!data.success){ console.log("错误"); //可能由于用户没有登录导致,此处跳转到选择门店 // $Widget.error_toast("温馨提示","您还未登录哦!",function(){ // location.href="./storeSelection.html"; // }) return; } } } /** * 页面公共数据 * */ window.$Widget = { /** * 弹出提示信息 * @param { string } title 弹出消息标题 * @param { string } msg 弹出消息体 * @param { string } callback 回调函数 */ toast: function (msg,callback) { //普通提示 $("body").append('<div class="toast_tips" style="position: absolute;top: 0;left: 0;width: 100%;height: 100%;overflow: hidden;background: rgba(0,0,0,0.64);z-index: 99;display:none">'+ '<p style="background: #fff;width: 11.2rem;height: 4rem;text-align: center;line-height: 4rem;margin: 8.56rem auto 0;color: rgba(51,51,51,0.7);font-size: 0.72rem;border-radius: 0.32rem;">'+msg+'</p>'+ '</div>'); $("body").find(".toast_tips").fadeIn(); this.remove_toast(".toast_tips",1500,callback); }, error_toast :function(title,msg,callback){ //错误提示 感叹号 var html = '<section class="Popup_wrap">'+ '<div class="Popup" >'+ '<img src="img/error/error2.svg">'+ '<h3>'+title+'</h3>'; if(msg){ html += '<p>'+msg+'</p>'; } html+= '</div>'+ '</section>' $("body").append(html); $("body").find(".Popup_wrap").fadeIn(1500); this.remove_toast(".Popup_wrap",1500,callback); }, success_toast :function(msg,callback){ //正确提示 感叹号 $("body").append('<section class="Popup_wrap" ">'+ '<div class="Popup">'+ '<img src="img/selfhelp/checkoutsuccess.svg">'+ '<h3 >'+msg+'</h3>'+ '</div>'+ '</section>'); $("body").find(".Popup_wrap").fadeIn(1500); this.remove_toast(".Popup_wrap",1500,callback); }, confirm_toast:function(title,msg,callback){ title = title || "温馨提醒"; $("body").append('<section class="Popup_wrap"> '+ '<div class="Popup" >'+ '<h3>'+title+'</h3>'+ '<p >'+msg+'</p>'+ '<div class="confirmChoose" >'+ '<span class="no">否</span>'+ '<span class="yes">是</span>'+ '</div>'+ '</div>'+ '</section>'); $("body").find(".Popup_wrap").show(); }, /** * @param className 需要关闭的类名称 * @param time 间隔多少时间关闭 * @param callback 回调方法 */ remove_toast:function(className,time,callback){ setTimeout(function(){ $("body").find(className).fadeOut(1000,function(){ $(this).remove(); if(callback){ callback(); } }); }, time); }, //等待框 showLoading: function () { $("body").append('<div class="loading" id="loading" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: transparent; z-index: 9999;">\ <div class="loading-cont" style="-webkit-box-sizing: border-box;box-sizing: border-box;position: absolute;top: 50%;left: 50%; width: 4.5rem; height: 4.5rem;margin-left:-2.25rem;margin-top:-2.25rem;padding: .5rem;background-color: rgba(0, 0, 0, .5);text-align: center;color: #fff;border-radius: .2rem;">\ <div class="loading-img" style="width: 1rem;height: 1rem;margin: 0.5rem auto;"><img src="./img/selfhelp/loading.gif"></div>\ <p class="loading-words" style="font-size:0.56rem;color:#fff;">努力加载中...</p>\ </div>\ </div>' ) }, //关闭等待框 hideLoading: function () { $("body").find("#loading").remove(); } }; <file_sep>/js/orderView.js var BaseUrls = 'http://wx.baojiatech.com/weixin/'; var oRderItemsUl1 = null; var aH5 = null; var aH6 = null; var pages = 1; var rowSs = 10; //判断是不是取消预约跳转过来 var state = GetQueryString('state'); var cancelS = 'cancel'; if(state === cancelS){ $('#orderNavigation li').eq(4).attr('class', 'active').siblings().attr('class', ''); $('.orderItems').eq(4).show().siblings().hide(); OrderList(-1, '.orderItems_ul5', 'orderDetails.html'); }else{ OrderList(5, '.orderItems_ul1', 'orderHasBeenBooked.html'); } //导航选项卡操作 //$('#orderNavigation').find('li').click(function(){ // $(this).attr('class', 'active').siblings('li').attr('class', ''); // $('#orderItem').children('div').eq($(this).index('li')).css('display', 'block').siblings('div').css('display', 'none'); //}); //客户当前门店订单列表 function OrderList(num, obj, url){ var data = { state: num, page: pages, rows: rowSs }; $comm.post("/manage/orderlist",data,function(data){ //判断如果没有数据了 if(data.data.length === 0 && pages !== 1) { $(".loadtip").html("没有更多数据了哦..."); $(".empty").hide() return; }else if(data.data.length === 0 && pages === 1){ $(".empty").show(); $(".refreshtip").hide(); $(".loadtip").hide(); return; }else{ $(".empty").hide(); } var oRderItemsUl = $(obj); //数据创建添加 // template.helper('urlFormat', function(inp) { // return url+'?number='+inp; // }); template.helper('pronameFilter', function (inp) { var projectName = inp.split(","); var html = ""; for(var i = 0 ;i<projectName.length; i++){ html +="<p>"+projectName[i]+"</p>"; } return html; }); var html = template("groupItemTmpl", data.data); if(pages === 1){ oRderItemsUl.html(html); }else{ oRderItemsUl.append(html); } // if(oRderItemsUl.find('li').length == 0){ // $('.empty').show(); // }else{ // $('.empty').hide(); // } //上拉加载调用 mySwiper.update(); if(oRderItemsUl.find('li').length < 3){ $(".loadtip").hide(); }else{ $(".loadtip").show(); } if($('#orderNavigation').find('li').eq(0).prop('className') == 'active'){ jianSuo('orderItemsUl1'); return; } else if($('#orderNavigation').find('li').eq(4).prop('className') == 'active'){ jianSuo('orderItemsUl5'); } }) } //上拉加载插件页面加载时调用 var loadFlag = true; var mySwiper = new Swiper('.swiper-container',{ direction: 'vertical', scrollbar: '.swiper-scrollbar', slidesPerView: 'auto', mousewheelControl: true, freeMode: true, onTouchMove: function(swiper){ //手动滑动中触发 var _viewHeight = document.getElementsByClassName('swiper-wrapper')[0].offsetHeight; var _contentHeight = document.getElementsByClassName('swiper-slide')[0].offsetHeight; if(mySwiper.translate < 50 && mySwiper.translate > 0) { $(".init-loading").html('下拉刷新...').show(); }else if(mySwiper.translate > 50 ){ $(".init-loading").html('释放刷新...').show(); } }, onTouchEnd: function(swiper) { var _viewHeight = document.getElementsByClassName('swiper-wrapper')[0].offsetHeight; var _contentHeight = document.getElementsByClassName('swiper-slide')[0].offsetHeight; // 上拉加载 if(mySwiper.translate <= _viewHeight - _contentHeight - 50 && mySwiper.translate < 0) { if(loadFlag){ $(".loadtip").html('正在加载...'); }else{ $(".loadtip").html('没有更多啦!'); } pages++; var thisActive = $('#orderNavigation li.active'); OrderList(Number(thisActive.attr("data-id")), '.orderItems_ul'+thisActive.attr("data-index"),thisActive.attr("data-url")); $(".loadtip").html('上拉加载更多...'); mySwiper.update(); // 重新计算高度; } // 下拉刷新 if(mySwiper.translate >= 50) { $(".init-loading").html('正在刷新...').show(); // $(".loadtip").html('上拉加载更多'); loadFlag = true; setTimeout(function() { pages = 1; $(".refreshtip").show(0); $(".init-loading").html('刷新成功!'); setTimeout(function(){ $(".init-loading").html('').hide(); },800); var thisActive = $('#orderNavigation li.active'); OrderList(thisActive.attr("data-id"), '.orderItems_ul'+thisActive.attr("data-index"),thisActive.attr("data-url")); $(".loadtip").show(0); //刷新操作 mySwiper.update(); // 重新计算高度; }, 1000); }else if(mySwiper.translate >= 0 && mySwiper.translate < 50){ $(".init-loading").html('').hide(); } return false; } }); //var mySwiper2 = new Swiper('.swiper-container2',{ // onTransitionEnd: function(swiper){ // // $('.w').css('transform', 'translate3d(0px, 0px, 0px)'); // $('.swiper-container2 .swiper-slide-active').css('height','auto').siblings('.swiper-slide').css('height','0px'); // // mySwiper.update(); // $('.tab li').eq(mySwiper2.activeIndex).addClass('active').siblings('li').removeClass('active'); // } // //}); $('.tab li').click(function(){ $(this).addClass('active').siblings('li').removeClass('active'); //mySwiper2.slideTo($(this).index(), 500, false); //$(this).attr('class', 'active').siblings('li').attr('class', ''); $('.orderItems').eq($(this).index('li')).css('display', 'block').siblings('div').css('display', 'none'); $('.w').css('transform', 'translate3d(0px, 0px, 0px)'); $('.swiper-container2 .swiper-slide-active').css('height','auto').siblings('.swiper-slide').css('height','0px'); mySwiper.update(); }); //点击的时候切换 $("#orderNavigation li").click(function(){ pages = 1; $(".orderItems_ul").html(); OrderList(Number($(this).attr("data-id")), '.orderItems_ul'+$(this).attr("data-index"), $(this).attr("data-url")); $('#searchBox').val(''); jianSuo('orderItemsUl5'); mySwiper.update(); }) var oSearchBox = document.getElementById('searchBox'); //排序调用 function jianSuo(id){ var oRderItemsUl1 = document.getElementById(id); var aH5 = oRderItemsUl1.getElementsByTagName('h5'); var aH6 = oRderItemsUl1.getElementsByTagName('h6'); oSearchBox.onkeyup = function(){ paiXu(aH5, id); paiXu(aH6, id); } } //搜索排序 function paiXu(obj, id){ var arr1 = []; var arr2 = []; var bBtn = false; var oInputVal = oSearchBox.value; for(var i=0; i<obj.length; i++){ arr1.push(obj[i]); arr2.push(obj[i]); }; var re = new RegExp(oInputVal, 'i', 'g'); if(oInputVal != ''){ for(var i=0; i<arr2.length; i++){ var sHtml = arr2[i].innerHTML; if(re.test(sHtml)){ bBtn = true; var aSearchList = arr2.splice(i, 1); for(var j=0; j<aSearchList.length; j++){ arr2.unshift(aSearchList[j]); } } } } else{ $('#'+ id).html(''); for(var i=0; i<arr1.length; i++){ $('#'+ id).append(arr1[i].parentNode.parentNode.parentNode); } } if(bBtn){ bBtn = false; $('#'+ id).html(''); for(var i=0; i<arr2.length; i++){ $('#'+ id).append(arr2[i].parentNode.parentNode.parentNode); } } } <file_sep>/js/storeSelection.js //公众号名称存cookie if(!getCookies("account")){ setCookies('account', GetQueryString("state"), 1); } var account = getCookies("account"); var code = GetQueryString("code"); //获取openid ; 如果cookie里面有,就取cookie,如果没有,就发ajax请求获取 var Daopenids = getCookies("openId"); if(Daopenids){ setCookies("openId", Daopenids, 1); getOpenid(Daopenids, account); }else{ $comm.post("/manage/getopenid/",{code: code,account: account},function(data){ Daopenids = data.data; setCookies("openId", Daopenids, 1); getOpenid(Daopenids, account); }) } //获取选择门店数据 // getOpenid('oLmhAwcMoI_L8NPrxJ-jv1G-pTus','gh_14812e2ad3cc'); //开发环境调用 /** * @param Daopenids 获取到的code * @param account 微信返回的数据code */ var dataList = {}; function getOpenid(Daopenids, account){ var data = { openid: Daopenids, account: account }; $comm.post("/manage/getindex",data,function(data){ dataList = data.data; var html = template("chooiceTmpl", data.data); $("#choice").html(html); }) } //门店登陆 function Land(obj ,callback){ var data = { account: obj.account, address: obj.address, balance: obj.balance, cardnumber: obj.cardnumber, client: obj.client, img: obj.img, integrals: obj.integrals, member: obj.member, mobile: obj.mobile, mobilex: obj.mobilex, name: obj.name, number: obj.number, openid: obj.openid, store: obj.store, store_name: obj.store_name, timestr: obj.timestr, token: obj.token, type: obj.type, zk: obj.zk }; $comm.post("/manage/ajaxlogin",data,function(data){ if(callback){ callback(); } }) } //获取登陆信息 function LandingInformation(){ $comm.get("/manage/getsession",{},function(data){ }) } $(document).on("click",".store",function(e){ //做判断是否是新用户,是需要注册还是数据同步 var dataType = $(this).attr('data-type'); var dataStore = $(this).attr('data-store'); var index = $(this).index(); switch(dataType){ case "0": //获取用户数据 Land(dataList[index],function(){ window.location.href = 'index.html' }); break; case "1": //用户绑定手机,点击跳转手机号码绑定 window.location.href = 'bindingCellPhone.html?store='+dataStore; break; case "2": //同步用户数据 Land(dataList[index],function(){ window.location.href = 'index.html' }); break; } })<file_sep>/js/vehiceModification.js let BaseUrl = 'http://wx.baojiatech.com/weixin/'; var oSelect1 = document.getElementById('select1'); var oSelect2 = document.getElementById('select2'); var oSelect3 = document.getElementById('select3'); var chePai = /(^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z0-9]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳使领]{1}$)|(^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z0-9]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳使领]{1}[A-Z0-9]{1}$)/; var chePai2 = GetQueryString('chePai2'); var cheId = GetQueryString('id'); $('#plate').val(chePai2); //获取车型类表 models(); function models(){ $comm.jsonPGet("http://wx.baojiatech.com/baojia-web/web/address/rest/getmodels","",function(data){ var html = template("oSelectTmpl", data.object); $("#select1").append(html); var cheName1 = oSelect1.value; cheName(cheName1); }); } //当车型选择的值发生改变时 jq事件 (.change()) $('#select1').change(function(){ var cheName2 = oSelect1.value; cheName(cheName2) }); //根据name添加车辆 function cheName(name){ var data = { name: name }; $comm.jsonPGet("http://wx.baojiatech.com/baojia-web/web/address/rest/getmodels",data,function(data){ oSelect2.innerHTML = ''; oSelect3.innerHTML = ''; for(var i=0; i<data.object.length; i++){ oOption2 = document.createElement('option'); oOption2.innerHTML = data.object[i].models; oOption2.setAttribute('data-id', data.object[i].id); oSelect2.appendChild(oOption2); $('#select3').html(data.object[0].prices) } CarSelection(data.object) }); } //点击匹配选择型号匹配价格 function CarSelection(data){ $('#select2').change(function(){ for(var i=0; i<data.length; i++){ if(oSelect2.value == data[i].models){ var prices = data[i].prices $('#select3').html(prices); } } }); } //点击确认修改 $('.Confirmation_of_modification').click(function(){ var ValueS = $('#plate').val(); var MileageShu = $('#MileageShu').val(); var select2Val = oSelect2.value; var oPtion2 = oSelect2.getElementsByTagName('option'); for(var i=0; i<oPtion2.length; i++){ if(select2Val == oPtion2[i].value){ var Select2 = oPtion2[i].getAttribute('data-id') } } console.log(Select2) if(ValueS == ''){ $Widget.toast("请输入您的车牌"); return; } else if(ValueS){ if(!chePai.test(ValueS)){ $Widget.toast("请输入您的车牌"); return; } } //如果车牌没有改变,就不处理 if(ValueS == chePai2){ return; }else{ var data = { carnumber: ValueS, id: cheId, models: Select2, kilometers: MileageShu }; $comm.post("/manage/editcar",data,function(data){ var timer = null; $Widget.success_toast("修改成功",function(){ window.location.href=document.referrer; }); }) }; }); //点击确认删除 $('.delete').click(function(){ $('#plate').val(GetQueryString('chePai2')); $Widget.confirm_toast("删除提示","确定删除此车记录吗"); }); $(document).on("click",".no",function(){ $Widget.remove_toast(".Popup_wrap",0); return; }) $(document).on("click",".yes",function(){ var data ={ id: cheId }; $comm.post("/manage/delcar",data,function(data){ $Widget.success_toast("删除成功",function(){ window.location.href="./myFavoriteCar.html"; }) }) }); $("#plate").click(function(ev){ var event = ev || event; oPlate.focus(); getTxt1CursorPosition(); clickShowKeybord(); event.stopPropagation(); })<file_sep>/js/wxIPA.js //获取微信cookie var accounts = getCookies('account'); var baidu_token = ""; //调取百度获取 access_token 参数 // $comm.get("/manage/getbaidutoken","",function(data){ // baidu_token = data.data; // }) //点击事件 $('.Camera_img').click(function(){ $comm.post("manage/getwxsign?data="+new Date().getTime(),{account: accounts,url: location.href.split("#")[0]},function(data){ wx.config({ debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: data.data.appId, // 必填,公众号的唯一标识 timestamp: data.data.timestamp, // 必填,生成签名的时间戳 nonceStr: data.data.nonceStr, // 必填,生成签名的随机串 signature: data.data.signature,// 必填,签名 jsApiList: ['chooseImage','getLocalImgData'] }) wx.ready(function(){ // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。 wx.chooseImage({ count: 1, // 默认9 sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function (res) { $Widget.showLoading(); var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片 // getBase64Image(localIds[0]);//车牌识别 wx.getLocalImgData({ localId:localIds[0], // 图片的localID success: function (res) { var localData = res.localData; // localData是图片的base64数据,可以用img标签显示 var dataURL = localData.split(","); if(dataURL.length > 1){ localData = dataURL.splice(1, 1); } removeBase64(localData);//车牌识别 } }); }, fail: function (err) { console.log(err) } }); wx.error(function(res){ // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。 console.log(res); }); }); }) }); //图片利用canvas转base64 // function getBase64Image(img) { // var canvas = document.createElement("canvas"); // var image = new Image(); // image.src = img; // image.onload = function(){ // canvas.width = image.width; // canvas.height = image.height; // var ctx = canvas.getContext("2d"); // ctx.drawImage(image, 0, 0, image.width, image.height); // var ext = image.src.substring(image.src.lastIndexOf(".")+1).toLowerCase(); // var dataURL = canvas.toDataURL("image/"+ext,0.7); // //去除base64前缀 // var arr = dataURL.split(",").splice(0, 1) //去除前缀 // var str2 = arr.join(''); // removeBase64(str2); // } // } //调用百度识别车牌接口 function removeBase64(dataURL){ $comm.post("/manage/getcarnumber",{img:dataURL},function(data){ $('#plate').val(JSON.parse(data.data).words_result.number); $Widget.hideLoading(); }) } <file_sep>/js/index.js $(function(){ $comm.get("/manage/getsession","",function(data){ var oDiv = document.createElement('div'); oDiv.innerHTML = '<div class="User_name"><img src=" '+ data.data.img +' "/><p>'+ data.data.cardnumber +'</p></div><div class="balance"><ul><li class="yuE"><p><span>¥</span><span>'+ data.data.balance +'</span></p><p>账户余额</p></li><li class="integral"><p>'+ data.data.integrals +'</p><p>积分</p></li></ul></div>' $('.header').append(oDiv); }) })<file_sep>/js/shiJian.js //时间插件调用 $(function() { var currYear = (new Date()).getFullYear(); var opt = {}; opt.date = { preset: 'date' }; //opt.datetime = { preset : 'datetime', minDate: new Date(2012,3,10,9,22), maxDate: new Date(2014,7,30,15,44), stepMinute: 5 }; opt.datetime = { preset: 'datetime' }; opt.time = { preset: 'time' }; opt.default = { theme: 'android-ics light', //皮肤样式 display: 'modal', //显示方式 mode: 'scroller', //日期选择模式 lang: 'zh', startYear: currYear - 10, //开始年份 endYear: currYear + 10 //结束年份 }; var optDateTime = $.extend(opt['datetime'], opt['default']); var optTime = $.extend(opt['time'], opt['default']); $("#mailbox").mobiscroll(optTime).time(optTime); });
8610e363a31cdb6970f494c18f7be35d1d1d7ddc
[ "JavaScript" ]
7
JavaScript
haoayou4211/baojia01
7a27d8ba5b7f0cf8aab9f8219b8bae46552d6503
a7de279b27e1fb1a25a5551ee1e30c57c30e3868
refs/heads/master
<file_sep><?php if (!defined('THINK_PATH')) exit(); /*a:1:{s:53:"D:\lp\WWW\jiu/application/index\view\login\index.html";i:1548240536;}*/ ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>红酒登录页面</title> <link href="__STATIC__/css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="__STATIC__/css/style.css" /> <link rel="stylesheet" href="__STATIC__/fonts/css/font-awesome.min.css"> <script src="__STATIC__/js/jquery-2.1.0.js"></script> </head> <body> <div class="container"> <!--视频开始--> <div class="area1"> <h3>布鲁塞尔国际酒类大奖赛博览中心</h3> <h2>打造原产地直供平台</h2> <img src="__STATIC__/images/pro.png"/> </div> <!--视频结束--> <!--登录表单开始--> <div class="area7"> <h1>打造原产地一站式的平台</h1> <p>欢迎到布鲁塞尔国际酒类大奖赛博览中心考察</p> <form action="" method="post"> <div class="phone clearfix"> <label> <i class="fa fa-mobile"></i> <span>手机号</span> </label> <input type="text" name="phone" id="phone" placeholder="请输入您的手机号"/> </div> <div class="code clearfix"> <label> <i class="fa fa-mobile"></i> <span>验证码</span> </label> <input type="text" name="vcode" id="vcode" placeholder="请输入验证码"/> <span class="yanzheng" > <a id="sendmsg">获取验证码</a> </span> </div> <button class="login btn" id="login">登录</button> </form> </div> <!--登录表单结束--> </div> </body> <script> var InterValObj; //timer变量,控制时间 var count = 60; //间隔函数,1秒执行 var curCount;//当前剩余秒数 var code = ""; //验证码 var codeLength = 6;//验证码长度 //发送验证码 $('#sendmsg').click(function(){ var phone=$("#phone").val(); $.ajax({ type:"POST", url:"<?php echo url('index/login/sendSms'); ?>", data:{"phone":phone}, success:function (res){ console.log(res); if(res.code=="1"){ curCount = count; //设置button效果,开始计时 // $("#sendmsg").css("background-color", "LightSkyBlue"); $('#sendmsg').attr("disabled", "true"); $('#sendmsg').val("还剩" + curCount + "秒"); InterValObj = window.setInterval(SetRemainTime, 1000); //启动计时器,1秒执行一次 }else if(res.code=="-1"){ alert(res.message); }else{ alert(res.message); } }, dataType: 'json' }); return false; }); function SetRemainTime() { if (curCount == 0) { window.clearInterval(InterValObj);//停止计时器 $("#sendmsg").removeAttr("disabled");//启用按钮 // $("#sendmsg").css("background-color", ""); $("#sendmsg").val("重发验证码"); code = ""; //清除验证码。如果不清除,过时间后,输入收到的验证码依然有效 }else { curCount--; $("#sendmsg").val("获取" + curCount + "秒"); } } //登录模块 $('#login').click(function () { var phone=$("#phone").val(); var vcode=$("#vcode").val(); $.ajax({ type:"POST", url:"<?php echo url('index/login/login'); ?>", data:{"phone":phone,"vCode":vcode}, success:function (res) { if (res.code==1) { alert(res.message); window.location.href = "<?php echo url('index/index/index'); ?>" }else{ alert(res.message); window.location.href = "<?php echo url('index/login/index'); ?>" } }, dataType: 'json' }); return false; }); </script> </html> <file_sep><?php namespace app\common\validate; use think\Validate; class Activity extends Validate { } <file_sep><?php if (!defined('THINK_PATH')) exit(); /*a:1:{s:51:"D:\lp\WWW\jiu/application/index\view\join\join.html";i:1548063410;}*/ ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>红酒加盟页面</title> <link href="__STATIC__/css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="__STATIC__/css/style.css" /> <link rel="stylesheet" href="__STATIC__/fonts/css/font-awesome.min.css"> </head> <body style="background: #fff;"> <div class="container"> <div class="area9"> <h1>加盟中心</h1> <form action=""> <input type="text" placeholder="请输入公司名称"/> <input type="text" placeholder="请输入您的姓名"/> <input type="tel" placeholder="请输入您的电话"/> <button class="btn">立即加盟</button> </form> </div> </div> </body> </html> <file_sep><?php namespace app\common\model; use think\Model; class Wallet extends Model { // 指定表名,不含前缀 protected $name = 'wallet'; // 开启自动写入时间戳字段 protected $autoWriteTimestamp = 'int'; //获取提现类型 public function getStatusType(){ return $statusType = [ [ 'id' => 0 , 'name' => '未提现' ] , [ 'id' => 1 , 'name' => '部分提现' ] , [ 'id' => 2 , 'name' => '全部提现' ] ]; } /* public function getStatusType($value, $data){ $get_data = [ '0'=>'未付款', '1'=>'已付款' ]; return $get_data[$data['is_pay']]; }*/ } <file_sep><?php namespace app\admin\controller; \think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT); use app\admin\Controller; use think\exception\HttpException; use think\Exception; use think\Db; class JoinUs extends Controller { use \app\admin\traits\controller\Controller; public function edit(){ if($this->request->isPost()){ $id=$this->request->param('id'); $checkStatus=$this->request->param('check_status'); $res=Db::name('join_us')->where('id', $id)->setField('check_status', $checkStatus); if($res){ return ajax_return_adv('修改成功'); }else{ return ajax_return_adv('修改失败'); } }else{ //获取到该数据的值 $id = $this->request->param('id'); if (!$id) { throw new Exception("缺少参数ID"); } $vo = Db::name('join_us')->where('id', $id)->find(); // print_r($vo);die; if (!$vo) { throw new HttpException(404, '该记录不存在'); } $this->view->assign('list', $vo); return $this->view->fetch(); } } } <file_sep><?php namespace app\common\validate; use think\Validate; class Wallet extends Validate { } <file_sep><?php namespace app\common\validate; use think\Validate; class User extends Validate { protected $rule = [ "mobile|手机号码" => "require", "password|密码" => "<PASSWORD>", "username|姓名" => "require", "nickname|昵称" => "require", ]; } <file_sep><?php namespace app\index\controller; use think\Db; use think\Exception; use think\Request; use think\Response; use think\Controller; /** * 前端首页控制器 * Class Index * @package app\index\controller */ class Base extends Controller { public function no($code, $message, $data = '') { if ($data == '') { $result = array( "code" => $code, "message" => $message, "data" => $data ); } else { $result = array( "code" => $code, "message" => $message, "data" => $data ); } return json($result); } public function ok($code, $message, $data = '') { if ($data == '') { $result = array( "code" => $code, "message" => $message, ); } else { $result = array( "code" => $code, "message" => $message, "data" => $data ); } return json($result); } /** * 返回标准错误json信息 */ function ajax_return_error($msg = "出现错误", $code = 1, $data = [], $extend = []) { return ajax_return($data, $msg, $code, $extend); } }<file_sep><?php namespace app\index\controller; use think\Db; use think\Exception; use think\Request; use think\Response; use think\Controller; use think\Image; /** * 前端首页控制器 * Class Index * @package app\index\controller */ class Share extends Controller { /** * 分享功能的实现 */ public function index(){ $userId=$this->request->param('user_id'); $data=Db::name('share_num')->field('id,qrcode')->where('user_id',$userId)->find(); if($data['qrcode']){ $this->view->assign('data',$data); }else{ header('Content-Type: image/png'); vendor("phpqrcode.phpqrcode");//引入工具包 $qRcode = new \QRcode(); $path = "public/Uploads/QRcode/";//生成的二维码所在目录 $time=time().'.png'; $fileName=$path.$time; $data='http://www.loungwangtouzi.com/index/login/index?user_id='.$userId; $level='L'; $info=[]; $size=4.5; ob_end_clean();//清空缓冲区 $qRcode::png($data,$fileName,$level, $size); session('imgpath',$fileName); $file_name = iconv("utf-8","gb2312",$time); $file_path = $_SERVER['DOCUMENT_ROOT'].'/'.$fileName; //获取下载文件的大小 $file_size = filesize($file_path); // $file_temp = fopen ( $file_path, "r" ); //返回的文件 header("Content-type:application/octet-stream"); //按照字节大小返回 header("Accept-Ranges:bytes"); //返回文件大小 header("Accept-Length:".$file_size); //这里客户端的弹出对话框 header("Content-Disposition:attachment;filename=".$time); $path_1 = "http://www.loungwangtouzi.com/public/static/index/images/share.png"; $path_2 = "http://www.loungwangtouzi.com/".session('imgpath'); $image_1 = imagecreatefrompng($path_1); $image_2 = imagecreatefrompng($path_2); $image_3 = imageCreatetruecolor(imagesx($image_1),imagesy($image_1)); $color = imagecolorallocate($image_3, 255, 255, 255); imagefill($image_3, 0, 0, $color); imageColorTransparent($image_3, $color); imagecopyresampled($image_3,$image_1,0,0,0,0,imagesx($image_1),imagesy($image_1),imagesx($image_1),imagesy($image_1)); imagecopymerge($image_3,$image_2,118,382,0,0,imagesx($image_2),imagesy($image_2), 100); //将画布保存到指定的gif文件 $fn='public/Uploads/QRcode/'.time().'.jpg'; // $im= '/Uploads/QRcode/'.$time; imagejpeg($image_3, $fn); //将数据进行销毁 @unlink($path_2); $info['qrcode']=$fn; $info['user_id']=$userId; $info['create_time']=time(); Db::name('share_num')->insert($info); $this->view->assign('data',$info); } return $this->view->fetch(); } /** * 发放现金红包 * $str 支付的人的上级id */ public function payLuckyMoney($str) { //获得上级的信息 $where['open_id']=$str; $in=Db::name('bminfo')->field('pid')->where($where)->find(); $info=Db::name('bminfo')->field('client_id,open_id')->where('id',$in['pid'])->find(); $obj2 = array(); //appid $obj2['wxappid'] = 'wxafe3f25daebca711'; //商户id $obj2['mch_id'] = '1521765611'; //组合成28位,根据官方开发文档,可以自行设置 $obj2['mch_billno'] = "abc123456def789ghijklmn123456766" . date('YmdHis') . rand(1000, 9999); // 调用接口的机器IP地址 $obj2['client_ip'] = $info['client_id']; //接收红包openid $obj2['re_openid'] = $info['open_id']; /* 付款金额设置start,按照概率设置随机发放。 * 1-200元之间,单位分。这里设置95%概率为1-2元,5%的概率为2-10元 */ $n = rand(1, 100); if ($n <= 95) { $obj2['total_amount'] = rand(1, 2); } else { $obj2['total_amount'] = rand(2, 3); } /* 付款金额设置end */ // 红包个数 $obj2['total_num'] = 1; // 商户名称 $obj2['send_name'] = "大象教育"; // 红包祝福语 $obj2['wishing'] = "恭喜发财,大吉大利"; // 活动名称 $obj2['act_name'] = "布鲁塞尔国际酒类大奖分享领红包"; // 备注 $obj2['remark'] = "布鲁塞尔国际酒类大奖红包"; /* 文档中未说明以下变量,李富林博客中有。注释起来也没问题。不需要。 $obj2['min_value'] = $money; $obj2['max_value'] = $money; $obj2['nick_name'] = '小门太红包'; */ $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"; $isPay = pay_lucky_money($url, $obj2);//调用commom.php里面的方法 $res = $this->XmlToArr($isPay); // 发放成功,把红包数据插入数据库 if ($res['return_msg'] == '发放成功') { //发放成功,进行逻辑处理 //红包金额入库 $b['yongjin']=$obj2['total_amount']; Db::name('bminfo')->where('id',$info['id'])->update($b); return $res['return_msg']; //红包金额入库结束 } else { // 发放失败,返回失败原因 return $res['return_msg']; } } public function XmlToArr($xml) { if($xml == '') return ''; libxml_disable_entity_loader(true); $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); return $arr; } } <file_sep><?php namespace app\common\model; use think\Model; class Opinion extends Model { // 指定表名,不含前缀 protected $name = 'opinion'; } <file_sep><?php namespace app\common\validate; use think\Validate; class Partner extends Validate { protected $rule = [ "logo|合作伙伴LOGO" => "require", "name|合作伙伴名称" => "require", ]; } <file_sep><?php if (!defined('THINK_PATH')) exit(); /*a:2:{s:68:"D:\lp\WWW\jingguan\public/../application/index\view\index\index.html";i:1547192827;s:70:"D:\lp\WWW\jingguan\public/../application/index\view\public\footer.html";i:1547171540;}*/ ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <title>江苏警官学院首页1</title> <link rel="stylesheet" href="__STATIC__/css/bootstrap.min.css"/> <link rel="stylesheet" href="__STATIC__/css/animate.css"/><!--页面块特效css--> <link rel="stylesheet" href="__STATIC__/css/swiper.min.css" /> <link rel="stylesheet" href="__STATIC__/css/bxyindex.css"/> <link rel="stylesheet" href="__STATIC__/css/head.css"/> <script src="__STATIC__/js/jquery.min.js"></script> <script src="__STATIC__/js/bootstrap.min.js"></script> <script type="text/javascript" src="__STATIC__/js/swiper.min.js"></script> <script src="__STATIC__/js/jquery.singlePageNav.min.js"></script><!--页面上拉下拉慢镜头--> <script src="__STATIC__/js/wow.min.js"></script><!--页面块特效js--> <script type="text/javascript" src="__STATIC__/js/script.js"></script> <script> /*运用页面块特效*/ if(!(/msie [6|7|8|9]/i.test(navigator.userAgent))) { new WOW().init(); }; </script> <!--[if lt IE 9]> <script src="__STATIC__/js/html5.js" type="text/javascript"></script> <![endif]--> </head> <body> <!--header开始--> <header class="header"> <div class="topWrap"> <div class="top"> <img src="__STATIC__/images/head1.png" class="img1 img-responsive"> <img src="__STATIC__/images/jingcha.png" class="img3 img-responsive"> <img src="__STATIC__/images/head2.png" class="img2 img-responsive"> </div> </div> <div class="nav-wrapper nav-wrapper_index"> <div class="logo"><a href="<?php echo Url('index/index2'); ?>"><img src="__STATIC__/images/logo.png" alt="" style="width:100%;max-width:100%;width:auto\9;-ms-interpolation-mode: bicubic;"></a></div> <div class="nav" id="nav"> </div> </div> <span class="black_bg01"></span> <!-- 移动端主导航--> </header> <!--header结束--> <!--banner--> <!-- Swiper --> <div class="swiper-container"> <div class="swiper-wrapper"> <?php if(is_array($banner) || $banner instanceof \think\Collection || $banner instanceof \think\Paginator): $i = 0; $__LIST__ = $banner;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?> <div class="swiper-slide"><img src="<?php echo $vo['logo']; ?>"></div> <?php endforeach; endif; else: echo "" ;endif; ?> </div> <!-- Add Pagination --> <div class="swiper-pagination"></div> <!-- Add Arrows --> <div class="swiper-button-next"></div> <div class="swiper-button-prev"></div> </div> <script> var swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', paginationClickable: true, spaceBetween: 30, centeredSlides: true, autoplay: 2500, loop:true, autoplayDisableOnInteraction: false }); </script> <!--banner--> <div class="container"> <div class="row"> <div class="bxya"> <div class="col-md-12"><span>学院简介</span></div> </div> </div> </div> <section class="bxyb"> <div class="container"> <div class="row"> <div class="col-md-8 col-xs-10 col-xs-push-1 bxyb1 wow fadeInLeft " data-wow-delay="0.2s"><p><?php echo $data['editorValue']; ?></p></div> <div class="col-md-3 col-xs-8 col-sm-pull-1 bxyb2 wow fadeInRight" data-wow-delay="0.2s"><img src="<?php echo $data['logo']; ?>" class="img-responsive"></div> </div> </div> </section> <section class="bxyc"> <a href="<?php echo url('index/index2'); ?>"><img src="__STATIC__/images/bxyc.jpg" class="img-responsive"></a> </section> <!-- FlexSlider --> <script type="text/javascript"> $(function() { Nav('#nav')//导航 mobideMenu()// 移动端主导航 $(".banner .flexslider").flexslider({ animation:'fade', slideshowSpeed: 6000, //展示时间间隔ms animationSpeed: 1000, //滚动时间ms touch: true //是否支持触屏滑动 }); }); </script> <!--footer--> <footer class="bxyfoot"> <div class="container"> <div class="row"> <div class="col-md-12"> <p><?php echo $data['copyright']; ?></p> <p><?php echo $data['support']; ?> <?php echo $data['tel']; ?></p> </div> </div> </div> </footer> <!--footer--> </body> </html> <file_sep><?php if (!defined('THINK_PATH')) exit(); /*a:1:{s:53:"D:\lp\WWW\jiu/application/index\view\share\index.html";i:1548159919;}*/ ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>红酒分享页面</title> <link href="__STATIC__/css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="__STATIC__/css/style.css" /> <link rel="stylesheet" href="__STATIC__/fonts/css/font-awesome.min.css"> </head> <body> <div class="container" style="padding-top:0;"> <!--视频开始--> <!--分享开始--> <div class="area8 share"> <img src="__IMG__/<?php echo $data['qrcode']; ?>"/> <button class="btn">分享给好友</button> </div> <!--分享结束--> </div> </body> </html> <file_sep><?php namespace app\index\controller; use think\Db; use think\Exception; use think\Request; use think\Response; use think\Controller; /** * 前端首页控制器 * Class Index * @package app\index\controller */ class Index extends Controller { public function index(){ /* if(session('useropenid')){ $s="http://www.loungwangtouzi.com/index/index/index"; header("Location:".$s."");exit; } */ //获取参与人数信息 $joinNum=Db::name('join_num')->field('nickname,avatar')->select(); $joinCount=Db::name('join_num')->count('id'); $this->view->assign('joinNum',$joinNum); $this->view->assign('joinCount',$joinCount); // 判断用户是否存在 $userId = Db::name('join_num')->field('id')->where('open_id',session('useropenid'))->find(); $this->view->assign('userId',$userId['id']); //获取分享人的信息 $shareNum=Db::name('share_num') ->alias('a') ->field('a.share_money,a.create_time,b.nickname,b.avatar,b.phone') ->join('__JOIN_NUM__ b','a.user_id=b.id') ->select(); $shareCount=Db::name('share_num')->count('id'); $this->view->assign('shareNum',$shareNum); $this->view->assign('shareCount',$shareCount); return $this->view->fetch(); } } <file_sep><?php namespace app\admin\controller; \think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT); use app\admin\Controller; use think\Db; class JoinNum extends Controller { use \app\admin\traits\controller\Controller; /** * 列表 */ public function index(){ $listRows = 10; $list = Db::name('join_num')->order('id desc')->paginate($listRows, false, ['query' => $this->request->get()]); $listnum = Db::name('join_num')->field('id')->select(); $count = count($listnum); $this->view->assign('list', $list); $this->view->assign("count", $count); $this->view->assign("page", $list->render()); return $this->view->fetch(); } } <file_sep><?php namespace app\common\model; use think\Model; class Order extends Model { // 指定表名,不含前缀 protected $name = 'order'; // 开启自动写入时间戳字段 protected $autoWriteTimestamp = 'int'; //获取订单状态类型 public function getOrderStatus(){ return $statusType = [ [ 'id' => 0 , 'name' => '待付款' ] , [ 'id' => 1 , 'name' => '待配送' ] , [ 'id' => 2 , 'name' => '已完成' ] ]; } //获取订单状态类型 public function getPayMode(){ return $statusType = [ [ 'id' => 1 , 'name' => '微信支付' ] , [ 'id' => 2 , 'name' => '支付宝支付' ] , [ 'id' => 3 , 'name' => '银联支付' ], [ 'id' => 4 , 'name' => '其他' ] ]; } } <file_sep><?php namespace app\common\validate; use think\Validate; class AboutUs extends Validate { } <file_sep><?php namespace app\index\controller; use think\Db; use think\Exception; use think\Request; use think\Response; use think\Controller; /** * 前端首页控制器 * Class Index * @package app\index\controller */ class Join extends Base { /** * 加盟中心 */ public function index() { return $this->view->fetch(); } /** * 加入我们的逻辑 * @throws Exception */ public function join(){ $request=Request::instance(); if($request->isPost()){ $companyName=trim($request->param('company_name')); if(!$companyName){ return $this->no('-1','公司名称不能为空'); } $userName=trim($request->param('user_name')); if(!$userName){ return $this->no('-1','用户姓名不能为空'); } $phone=trim($request->param('phone')); if(!$phone){ return $this->no('-1','电话号码不能为空'); } if(false===$this->isValidaMobile($phone)){ return $this->no('-1','手机号码不正确'); } try{ $data=$request->post(); $data['create_time']=time(); $res=Db::name('join_us')->insert($data); if($res){ return $this->ok('1','加盟成功'); }else{ return $this->no('-1','系统繁忙'); } }catch (\Exception $e){ throw new Exception($e->getMessage()); } } } /** * 验证手机号码 * @param $phone * @return bool */ public function isValidaMobile($phone){ return preg_match('/^1[3456789]{1}\d{9}$/',$phone) ? true :false; } } <file_sep><?php /** * tpAdmin [a web admin based ThinkPHP5] * * @author yuan1994 <<EMAIL>> * @link http://tpadmin.yuan1994.com/ * @copyright 2016 yuan1994 all rights reserved. * @license http://www.apache.org/licenses/LICENSE-2.0 */ //------------------------ // 用户控制器 //------------------------- namespace app\admin\controller; \think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT); use app\admin\Controller; use think\Exception; use think\Loader; class AdminUser extends Controller { use \app\admin\traits\controller\Controller; // protected static $blacklist = ['delete', 'clear', 'deleteforever', 'recyclebin', 'recycle']; //查询过滤操作 protected function filter(&$map) { //不查询管理员 $map['id'] = ["gt", 1]; //根据条件查询 if ($this->request->param('realname')) { $map['realname'] = ["like", "%" . $this->request->param('realname') . "%"]; } if ($this->request->param('account')) { $map['account'] = ["like", "%" . $this->request->param('account') . "%"]; } if ($this->request->param('email')) { $map['email'] = ["like", "%" . $this->request->param('email') . "%"]; } if ($this->request->param('mobile')) { $map['mobile'] = ["like", "%" . $this->request->param('mobile') . "%"]; } } /** * 修改密码 */ public function password() { $id = $this->request->param('id/d'); if ($this->request->isPost()) { //禁止修改管理员的密码,管理员id为1 if ($id < 2) { return ajax_return_adv_error("缺少必要参数"); } $password = $this->request->post('password'); if (!$password) { return ajax_return_adv_error("密码不能为空"); } if (false === Loader::model('AdminUser')->updatePassword($id, $password)) { return ajax_return_adv_error("密码修改失败"); } return ajax_return_adv("密码已修改为{$password}", ''); } else { // 禁止修改管理员的密码,管理员 id 为 1 if ($id < 2) { throw new Exception("缺少必要参数"); } return $this->view->fetch(); } } /** * 禁用限制 */ protected function beforeForbid() { // 禁止禁用 Admin 模块,权限设置节点 $this->filterId(1, '该用户不能被禁用', '='); } }<file_sep><?php namespace app\index\controller; use think\Db; use think\Exception; use think\Request; use think\Response; use think\Controller; use think\Config; /** * 前端首页控制器 * Class Index * @package app\index\controller */ class Index extends Controller { public function login(){ $uid=$this->request->param('id'); session('userpid',$uid); $s="http://guoguo.meyatu.com/index.php/index/index/index"; header("Location:".$s."");exit; } //首页 public function index(){ //微信授权获取基本信息 if ($this->request->param('code')==''){//没有code,去微信接口获取code码 $this->getcodess(); file_put_contents("log322.log",2); } else {//获取code后跳转回来到这里了 $code=$this->request->param('code'); //获取openid $openid = $this->getopenid($code); $access_token=$this->getAccesstoken(); $wxUserInfo=$this->getWxUserInfo($openid,$access_token); $user_openid = $wxUserInfo['openid']; session('useropenid',$user_openid); // 判断用户是否存在 $data_user = Db::name('join_num')->where('open_id',$user_openid)->find(); if(empty($data_user)){ $data['openid'] = $user_openid; $data['nickname']=$wxUserInfo['nickname']; $data['avatar']=$wxUserInfo['headimgurl']; $data['create_time']=time(); Db::name('join_num')->insert($data); }else{ $data['nickname']=$wxUserInfo['nickname']; $data['avatar']=$wxUserInfo['headimgurl']; $data['update_time']=time(); Db::name('join_num')->where('open_id',$user_openid)->update($data); } } // 判断用户是否存在 $userId = Db::name('join_num')->field('id')->where('open_id',session('useropenid'))->find(); $this->view->assign('userId',$userId['id']); //获取分享人的信息 $shareNum=Db::name('share_num') ->alias('a') ->field('a.share_money,a.create_time,b.nickname,b.avatar,b.phone') ->join('__JOIN_NUM__ b','a.user_id=b.id') ->select(); $shareCount=Db::name('share_num')->count('id'); $this->view->assign('shareNum',$shareNum); $this->view->assign('shareCount',$shareCount); //相关信息 $about=Db::name('about')->find(); $this->view->assign('about',$about); return $this->view->fetch(); //赚钱排行版 } //获取微信用户的信息 public function getWxUserInfo($openid,$access_token){ $userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid"; $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_URL, $userinfo_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_POSTFIELDS,false); $result = curl_exec($ch); curl_close($ch); file_put_contents("log_wx.txt", $result); $info = json_decode(htmlspecialchars_decode($result), true); return $info; } // 用于请求微信接口获取数据 public function getOpenid($code){ //获取微信配置参数 $wxConfig = Config::get('wechat'); $appId=$wxConfig['AppId']; $appSecret=$wxConfig['AppSecret']; $url="https://api.weixin.qq.com/sns/oauth2/access_token? appid=$appId &secret=$appSecret &code=$code &grant_type=authorization_code"; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $tmpInfo=curl_exec($curl); curl_close($curl); file_put_contents("log_openid.log",$tmpInfo,FILE_APPEND); $openid = json_decode(htmlspecialchars_decode($tmpInfo), true); if(isset($openid['openid'])){ session('opennewid',$openid['openid']); session('newaccess_token',$openid['access_token']); return $openid; }else{ $newopenid['openid']=session('opennewid'); $newopenid['access_token']=session('newaccess_token'); return $newopenid; } } //获取access_token public function getAccesstoken() { //获取微信配置参数 $wxConfig = Config::get('wechat'); $appId=$wxConfig['AppId']; $appSecret=$wxConfig['AppSecret']; $url = "https://api.weixin.qq.com/cgi-bin/token? grant_type=client_credential &appid=$appId &secret=$appSecret"; $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_POSTFIELDS,false); $result = curl_exec($ch); curl_close($ch); file_put_contents("log_accesstoken.txt", $result); $access_token = json_decode(htmlspecialchars_decode($result), true); return $access_token['access_token']; } //授权反馈 public function getcodess() { //获取微信配置参数 $wxConfig = Config::get('wechat'); $appId=$wxConfig['AppId']; file_put_contents("log3233.log",1); $url = "http://admin.guoguo.net/index/login/index"; $url =rawurlencode($url); $s="https://open.weixin.qq.com/connect/oauth2/authorize? appid=$appId &redirect_uri=$url &response_type=code &scope=snsapi_userinfo&state=1#wechat_redirect"; header("Location:".$s."");exit; } /** * 验证手机号码 * @param $phone * @return bool */ public function isValidaMobile($phone){ return preg_match('/^1[3456789]{1}\d{9}$/',$phone) ? true :false; } } <file_sep><?php if (!defined('THINK_PATH')) exit(); /*a:3:{s:58:"D:\lp\WWW\jiu/application/admin\view\admin_node\index.html";i:1548057803;s:55:"D:\lp\WWW\jiu/application/admin\view\template\base.html";i:1548057803;s:66:"D:\lp\WWW\jiu/application/admin\view\template\javascript_vars.html";i:1548057803;}*/ ?> <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <meta name="renderer" content="webkit|ie-comp|ie-stand"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/> <meta http-equiv="Cache-Control" content="no-siteapp"/> <title><?php echo \think\Config::get('site.title'); ?></title> <link rel="Bookmark" href="__ROOT__/favicon.ico" > <link rel="Shortcut Icon" href="__ROOT__/favicon.ico" /> <!--[if lt IE 9]> <script type="text/javascript" src="__LIB__/html5.js"></script> <script type="text/javascript" src="__LIB__/respond.min.js"></script> <script type="text/javascript" src="__LIB__/PIE_IE678.js"></script> <![endif]--> <link rel="stylesheet" type="text/css" href="__STATIC__/h-ui/css/H-ui.min.css"/> <link rel="stylesheet" type="text/css" href="__STATIC__/h-ui.admin/css/H-ui.admin.css"/> <link rel="stylesheet" type="text/css" href="__LIB__/Hui-iconfont/1.0.7/iconfont.css"/> <link rel="stylesheet" type="text/css" href="__LIB__/icheck/icheck.css"/> <link rel="stylesheet" type="text/css" href="__STATIC__/h-ui.admin/skin/default/skin.css" id="skin"/> <link rel="stylesheet" type="text/css" href="__STATIC__/h-ui.admin/css/style.css"/> <link rel="stylesheet" type="text/css" href="__STATIC__/css/app.css"/> <link rel="stylesheet" type="text/css" href="__LIB__/icheck/icheck.css"/> <link rel="stylesheet" href="__LIB__/zTree/css/zTreeStyle/zTreeStyle.css" type="text/css"> <link rel="stylesheet" href="__LIB__/contextmenu/jquery.contextmenu.css" type="text/css"> <style type="text/css"> div#rMenu { position: absolute; visibility: hidden; top: 0; background-color: #555; text-align: left; padding: 2px; } div#rMenu ul li { margin: 1px 0; padding: 0 5px; cursor: pointer; list-style: none outside none; background-color: #DFDFDF; } </style> <!--[if IE 6]> <script type="text/javascript" src="__LIB__/DD_belatedPNG_0.0.8a-min.js"></script> <script>DD_belatedPNG.fix('*');</script> <![endif]--> <!--定义JavaScript常量--> <script> window.THINK_ROOT = '<?php echo \think\Request::instance()->root(); ?>'; window.THINK_MODULE = '<?php echo \think\Url::build("/" . \think\Request::instance()->module(), "", false); ?>'; window.THINK_CONTROLLER = '<?php echo \think\Url::build("___", "", false); ?>'.replace('/___', ''); </script> </head> <body> <nav class="breadcrumb"> <div id="nav-title"></div> <a class="btn btn-success radius r btn-refresh" style="line-height:1.6em;margin-top:3px" href="javascript:;" title="刷新"><i class="Hui-iconfont"></i></a> </nav> <div class="pos-f tp-page-aside"> <div class="panel panel-primary tp-panel tp-panel-module"> <div class="panel-header">模块</div> <div class="panel-body tp-box-list"> <ul id="module-list"> <?php if(is_array($modules) || $modules instanceof \think\Collection || $modules instanceof \think\Paginator): if( count($modules)==0 ) : echo "" ;else: foreach($modules as $key=>$module): ?> <li data-module-id="<?php echo $module['id']; ?>"><a href="javascript:;" class="list-select"><?php echo $module['title']; ?>(<?php echo $module['name']; ?>)</a></li> <?php endforeach; endif; else: echo "" ;endif; ?> </ul> </div> </div> <div class="panel panel-primary tp-panel tp-panel-group"> <div class="panel-header">分组</div> <div class="panel-body tp-box-list"> <ul id="group-list"> <li data-group-id="0"><a href="javascript:;" class="list-select"><i class="Hui-iconfont"></i> 未分组</a></li> </ul> </div> </div> </div> <div class="tp-page-main"> <div class="page-container"> <div class="cl pd-5 bg-1 bk-gray"> <span class="l"> <?php if (\Rbac::AccessCheck('add', 'AdminNode', 'admin')) : ?> <a class="btn btn-primary radius J_add" href="javascript:;"><i class="Hui-iconfont">&#xe600;</i> 添加</a> <?php endif; if (\Rbac::AccessCheck('forbid', 'AdminNode', 'admin')) : ?> <a href="javascript:;" onclick="treeOpAll('<?php echo \think\Url::build('forbid'); ?>', '禁用')" class="btn btn-warning radius ml-5"><i class="Hui-iconfont">&#xe631;</i> 禁用</a> <?php endif; if (\Rbac::AccessCheck('resume', 'AdminNode', 'admin')) : ?> <a href="javascript:;" onclick="treeOpAll('<?php echo \think\Url::build('resume'); ?>', '恢复')" class="btn btn-success radius ml-5"><i class="Hui-iconfont">&#xe615;</i> 恢复</a> <?php endif; if (\Rbac::AccessCheck('delete', 'AdminNode', 'admin')) : ?> <a href="javascript:;" onclick="treeOpAll('<?php echo \think\Url::build('delete'); ?>', '删除')" class="btn btn-danger radius ml-5"><i class="Hui-iconfont">&#xe6e2;</i> 删除</a> <?php endif; if (\Rbac::AccessCheck('recyclebin')) : ?><a href="javascript:;" onclick="open_window('回收站','<?php echo \think\Url::build('recyclebin', []); ?>')" class="btn btn-secondary radius mr-5"><i class="Hui-iconfont">&#xe6b9;</i> 回收站</a><?php endif; if (\Rbac::AccessCheck('load', 'AdminNode', 'admin')) : ?> <a href="javascript:;" class="btn btn-primary radius J_load"><i class="Hui-iconfont">&#xe645;</i> 批量导入</a> <?php endif; ?> </span> </div> <div class="zTreeDemoBackground left"> <ul id="tree" class="ztree"></ul> </div> </div> </div> <div id="rMenu"> <ul> <li class="J_add" onclick="hideRMenu();">添加节点</li> <li onclick="hideRMenu();onEditName('tree', zTree.getSelectedNodes()[0]);">编辑节点</li> <li onclick="hideRMenu();onRemove('tree', zTree.getSelectedNodes()[0]);">删除节点</li> <li onclick="checkTreeNode(true);">选中节点</li> <li onclick="checkTreeNode(false);">取消选择</li> </ul> </div> <script type="text/javascript" src="__LIB__/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript" src="__LIB__/layer/2.4/layer.js"></script> <script type="text/javascript" src="__STATIC__/h-ui/js/H-ui.js"></script> <script type="text/javascript" src="__STATIC__/h-ui.admin/js/H-ui.admin.js"></script> <script type="text/javascript" src="__STATIC__/js/app.js"></script> <script type="text/javascript" src="__LIB__/icheck/jquery.icheck.min.js"></script> <script type="text/javascript" src="__LIB__/zTree/js/jquery.ztree.all.js"></script> <script type="text/javascript" src="__LIB__/contextmenu/jquery.contextmenu.js"></script> <script type="text/javascript"> // 当前链接 var THINK_CURRENT = THINK_CONTROLLER + '/<?php echo \think\Request::instance()->action(); ?>'; </script> <script type="text/javascript" src="__STATIC__/js/admin_node.js"></script> </body> </html><file_sep><?php namespace app\common\model; use think\Model; class LogEnquiry extends Model { // 指定表名,不含前缀 protected $name = 'log_enquiry'; // 开启自动写入时间戳字段 protected $autoWriteTimestamp = 'int'; //获取车辆类型 public function getCarType(){ return $agentType = [ [ 'id' => 1 , 'name' => '公车' ] , [ 'id' => 2 , 'name' => '私车' ] , [ 'id' => 3 , 'name' => '公私车' ] ]; } //获取车辆类型 public function getInsureType(){ return $agentType = [ [ 'id' => 1 , 'name' => '公车' ] , [ 'id' => 2 , 'name' => '私车' ] , [ 'id' => 3 , 'name' => '公私车' ] , [ 'id' => 4 , 'name' => '保险公司' ] , [ 'id' => 5 , 'name' => '其他' ] ]; } } <file_sep><?php if (!defined('THINK_PATH')) exit(); /*a:2:{s:57:"D:\lp\WWW\jingguan/application/index\view\neiye\zyys.html";i:1547192992;s:60:"D:\lp\WWW\jingguan/application/index\view\public\footer.html";i:1547171540;}*/ ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <title>教学管理与优势特色</title> <link rel="stylesheet" href="__STATIC__/css/bootstrap.min.css"/> <link rel="stylesheet" href="__STATIC__/css/animate.css"/><!--页面块特效css--> <link rel="stylesheet" href="__STATIC__/css/swiper.min.css" /> <link rel="stylesheet" href="__STATIC__/css/bxyindex.css"/> <link rel="stylesheet" href="__STATIC__/css/head.css"/> <script src="__STATIC__/js/jquery.min.js"></script> <script src="__STATIC__/js/bootstrap.min.js"></script> <script type="text/javascript" src="__STATIC__/js/swiper.min.js"></script> <script src="__STATIC__/js/jquery.singlePageNav.min.js"></script><!--页面上拉下拉慢镜头--> <script src="__STATIC__/js/wow.min.js"></script><!--页面块特效js--> <script type="text/javascript" src="__STATIC__/js/script.js"></script> <script> /*运用页面块特效*/ if(!(/msie [6|7|8|9]/i.test(navigator.userAgent))) { new WOW().init(); }; </script> <!--[if lt IE 9]> <script src="__STATIC__/js/html5.js" type="text/javascript"></script> <![endif]--> </head> <body> <!--header开始--> <header class="header"> <div class="topWrap"> <div class="top"> <img src="__STATIC__/images/head1.png" class="img1 img-responsive"> <img src="__STATIC__/images/jingcha.png" class="img3 img-responsive"> <img src="__STATIC__/images/head2.png" class="img2 img-responsive"> </div> </div> <div class="nav-wrapper"> <div class="logo"><a href="<?php echo Url('index/index2'); ?>"><img src="__STATIC__/images/logo.png" alt="" style="width:100%;max-width:100%;width:auto\9;-ms-interpolation-mode: bicubic;"></a></div> <div class="nav" id="nav"> <ul class="nav_lf"> <li><a href="<?php echo url('neiye/sqs'); ?>">申报材料</a></li> <li><a href="<?php echo url('neiye/zysz'); ?>">专业建设与人才培养</a></li> <li><a href="<?php echo url('neiye/dwjg'); ?>">师资结构与素质</a></li> <li><a href="<?php echo url('neiye/jxzy'); ?>">教学条件与投入</a></li> </ul> <ul class="nav_rt"> <li><a href="<?php echo url('neiye/kcsj'); ?>">课程建设与改革</a></li> <li><a href="<?php echo url('neiye/zljk'); ?>">教育质量与服务能力</a></li> <li><a class="bxyact" href="<?php echo url('neiye/jxgl'); ?>">教学管理与优势特色</a></li> </ul> </div> </div> <span class="black_bg01"></span> <!-- 移动端主导航--> <section class="mobile"> <div class="mobile-inner-header"> <div class="mobile-inner-header-icon mobile-inner-header-icon-out"> <span class="mobile_home">导航</span></div> </div> <div class="mobile-inner-nav"> <ul> <li><a href="<?php echo url('neiye/sqs'); ?>">申报材料</a></li> <li><a href="<?php echo url('neiye/zysz'); ?>">专业建设与人才培养</a></li> <li><a href="<?php echo url('neiye/dwjg'); ?>">师资结构与素质</a></li> <li><a href="<?php echo url('neiye/jxzy'); ?>">教学条件与投入</a></li> <li><a href="<?php echo url('neiye/kcsj'); ?>">课程建设与改革</a></li> <li><a href="<?php echo url('neiye/zljk'); ?>">教育质量与服务能力</a></li> <li><a href="<?php echo url('neiye/jxgl'); ?>">教学管理与优势特色</a></li> </ul> </div> </section> </header> <!--header结束--> <section> <img src="__STATIC__/images/neiye.jpg" class="img-responsive"> </section> <div style="width:100%; overflow:hidden; background:#eaf3fd; padding-top:60px; padding-bottom:120px;"> <div class="container"> <div class="row"> <div class="col-md-3 wow fadeInLeft" data-wow-delay="0.2s"> <dl class="bxye"> <dt>教学管理与优势特色</dt> <dd><a href="<?php echo url('neiye/jxgl'); ?>">教学管理</a></dd> <dd class="curr"><a href="<?php echo url('neiye/zyys'); ?>">专业优势与特色</a></dd> </dl> </div> <div class="col-md-9 wow fadeInRight" data-wow-delay="0.2s" > <div class="bxyf"><i>专业设置</i><ul><li>您当前的位置:</li><li><a href="<?php echo url('neiye/index2'); ?>">首页</a></li><li>>></li><li><a href="">教学管理与优势特色</a></li><li>>></li><li><a href="">专业优势与特色</a></li></ul></div> <div class="bxyg"> <div class="zyjsbox" style="height:500px;"> <?php echo $about['editorValue']; ?> </div> </div> </div> </div> </div> </div> <!-- FlexSlider --> <script type="text/javascript"> $(function() { Nav('#nav')//导航 mobideMenu()// 移动端主导航 $(".banner .flexslider").flexslider({ animation:'fade', slideshowSpeed: 6000, //展示时间间隔ms animationSpeed: 1000, //滚动时间ms touch: true //是否支持触屏滑动 }); }); </script> <!--footer--> <footer class="bxyfoot"> <div class="container"> <div class="row"> <div class="col-md-12"> <p><?php echo $data['copyright']; ?></p> <p><?php echo $data['support']; ?> <?php echo $data['tel']; ?></p> </div> </div> </div> </footer> <!--footer--> </body> </html> <file_sep><?php if (!defined('THINK_PATH')) exit(); /*a:3:{s:79:"D:\lp\WWW\tpAdmin\public/../application/admin\view\one\two\three\four\edit.html";i:1488899632;s:69:"D:\lp\WWW\tpAdmin\public/../application/admin\view\template\base.html";i:1488899632;s:80:"D:\lp\WWW\tpAdmin\public/../application/admin\view\template\javascript_vars.html";i:1488899632;}*/ ?> <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <meta name="renderer" content="webkit|ie-comp|ie-stand"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/> <meta http-equiv="Cache-Control" content="no-siteapp"/> <title><?php echo \think\Config::get('site.title'); ?></title> <link rel="Bookmark" href="__ROOT__/favicon.ico" > <link rel="Shortcut Icon" href="__ROOT__/favicon.ico" /> <!--[if lt IE 9]> <script type="text/javascript" src="__LIB__/html5.js"></script> <script type="text/javascript" src="__LIB__/respond.min.js"></script> <script type="text/javascript" src="__LIB__/PIE_IE678.js"></script> <![endif]--> <link rel="stylesheet" type="text/css" href="__STATIC__/h-ui/css/H-ui.min.css"/> <link rel="stylesheet" type="text/css" href="__STATIC__/h-ui.admin/css/H-ui.admin.css"/> <link rel="stylesheet" type="text/css" href="__LIB__/Hui-iconfont/1.0.7/iconfont.css"/> <link rel="stylesheet" type="text/css" href="__LIB__/icheck/icheck.css"/> <link rel="stylesheet" type="text/css" href="__STATIC__/h-ui.admin/skin/default/skin.css" id="skin"/> <link rel="stylesheet" type="text/css" href="__STATIC__/h-ui.admin/css/style.css"/> <link rel="stylesheet" type="text/css" href="__STATIC__/css/app.css"/> <link rel="stylesheet" type="text/css" href="__LIB__/icheck/icheck.css"/> <!--[if IE 6]> <script type="text/javascript" src="__LIB__/DD_belatedPNG_0.0.8a-min.js"></script> <script>DD_belatedPNG.fix('*');</script> <![endif]--> <!--定义JavaScript常量--> <script> window.THINK_ROOT = '<?php echo \think\Request::instance()->root(); ?>'; window.THINK_MODULE = '<?php echo \think\Url::build("/" . \think\Request::instance()->module(), "", false); ?>'; window.THINK_CONTROLLER = '<?php echo \think\Url::build("___", "", false); ?>'.replace('/___', ''); </script> </head> <body> <nav class="breadcrumb"> <div id="nav-title"></div> <a class="btn btn-success radius r btn-refresh" style="line-height:1.6em;margin-top:3px" href="javascript:;" title="刷新"><i class="Hui-iconfont"></i></a> </nav> <div class="page-container"> <form class="form form-horizontal" id="form" method="post" action="<?php echo \think\Request::instance()->baseUrl(); ?>"> <input type="hidden" name="id" value="<?php echo isset($vo['id']) ? $vo['id'] : ''; ?>"> <div class="row cl"> <label class="form-label col-xs-3 col-sm-3"><span class="c-red">*</span>字段一:</label> <div class="formControls col-xs-6 col-sm-6"> <input type="text" class="input-text" placeholder="字段一" name="field1" value="<?php echo isset($vo['field1']) ? $vo['field1'] : ''; ?>" datatype="*" nullmsg="请填写字段一"> </div> <div class="col-xs-3 col-sm-3"></div> </div> <div class="row cl"> <label class="form-label col-xs-3 col-sm-3">选填:</label> <div class="formControls col-xs-6 col-sm-6"> <input type="text" class="input-text" placeholder="选填" name="option" value="<?php echo isset($vo['option']) ? $vo['option'] : ''; ?>" > </div> <div class="col-xs-3 col-sm-3"></div> </div> <div class="row cl"> <label class="form-label col-xs-3 col-sm-3">下拉框:</label> <div class="formControls col-xs-6 col-sm-6"> <div class="select-box"> <select name="select" class="select"> <option value="1">选项一</option> <option value="2">选项二</option> <option value="3">选项三</option> </select> </div> </div> <div class="col-xs-3 col-sm-3"></div> </div> <div class="row cl"> <label class="form-label col-xs-3 col-sm-3">单选:</label> <div class="formControls col-xs-6 col-sm-6 skin-minimal"> <?php if(is_array(\think\Config::get('conf.sex')) || \think\Config::get('conf.sex') instanceof \think\Collection || \think\Config::get('conf.sex') instanceof \think\Paginator): if( count(\think\Config::get('conf.sex'))==0 ) : echo "" ;else: foreach(\think\Config::get('conf.sex') as $k=>$v): ?> <div class="radio-box"> <input type="radio" name="radio" id="radio-<?php echo $k; ?>" value="<?php echo $k; ?>"> <label for="radio-<?php echo $k; ?>"><?php echo $v; ?></label> </div> <?php endforeach; endif; else: echo "" ;endif; ?> </div> <div class="col-xs-3 col-sm-3"></div> </div> <div class="row cl"> <label class="form-label col-xs-3 col-sm-3">复选框:</label> <div class="formControls col-xs-6 col-sm-6 skin-minimal"> <div class="radio-box"> <input type="checkbox" name="checkbox[]" id="checkbox-1" value="1"> <label for="checkbox-1">选项一</label> </div> <div class="radio-box"> <input type="checkbox" name="checkbox[]" id="checkbox-2" value="2"> <label for="checkbox-2">选项二</label> </div> <div class="radio-box"> <input type="checkbox" name="checkbox[]" id="checkbox-3" value="3"> <label for="checkbox-3">选项三</label> </div> </div> <div class="col-xs-3 col-sm-3"></div> </div> <div class="row cl"> <label class="form-label col-xs-3 col-sm-3">密码:</label> <div class="formControls col-xs-6 col-sm-6"> <input type="password" class="input-text" placeholder="密码" name="password" value="<?php echo isset($vo['password']) ? $vo['password'] : ''; ?>" > </div> <div class="col-xs-3 col-sm-3"></div> </div> <div class="row cl"> <label class="form-label col-xs-3 col-sm-3">文本域:</label> <div class="formControls col-xs-6 col-sm-6"> <textarea class="textarea" placeholder="" name="textarea" onKeyUp="textarealength(this, 100)"><?php echo isset($vo['textarea']) ? $vo['textarea'] : ''; ?></textarea> <p class="textarea-numberbar"><em class="textarea-length">0</em>/100</p> </div> <div class="col-xs-3 col-sm-3"></div> </div> <div class="row cl"> <label class="form-label col-xs-3 col-sm-3"><span class="c-red">*</span>日期:</label> <div class="formControls col-xs-6 col-sm-6"> <input type="text" class="input-text Wdate" placeholder="日期" name="date" value="<?php echo isset($vo['date']) ? $vo['date'] : ''; ?>" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd'})" datatype="*" nullmsg="请选择日期"> </div> <div class="col-xs-3 col-sm-3"></div> </div> <div class="row cl"> <label class="form-label col-xs-3 col-sm-3"><span class="c-red">*</span>手机号:</label> <div class="formControls col-xs-6 col-sm-6"> <input type="text" class="input-text" placeholder="手机号" name="mobile" value="<?php echo isset($vo['mobile']) ? $vo['mobile'] : ''; ?>" datatype="/^1[34578]\d{9}$/" nullmsg="请填写手机号" errormsg="手机号格式错误"> </div> <div class="col-xs-3 col-sm-3"></div> </div> <div class="row cl"> <label class="form-label col-xs-3 col-sm-3"><span class="c-red">*</span>邮箱:</label> <div class="formControls col-xs-6 col-sm-6"> <input type="text" class="input-text" placeholder="邮箱" name="email" value="<?php echo isset($vo['email']) ? $vo['email'] : ''; ?>" datatype="e" nullmsg="请填写邮箱" errormsg="邮箱格式错误"> </div> <div class="col-xs-3 col-sm-3"></div> </div> <div class="row cl"> <label class="form-label col-xs-3 col-sm-3"><span class="c-red">*</span>排序:</label> <div class="formControls col-xs-6 col-sm-6"> <input type="number" class="input-text" placeholder="排序" name="sort" value="<?php echo isset($vo['sort']) ? $vo['sort'] : '50'; ?>" datatype="*" nullmsg="请填写排序"> </div> <div class="col-xs-3 col-sm-3"></div> </div> <div class="row cl"> <label class="form-label col-xs-3 col-sm-3"><span class="c-red">*</span>状态:</label> <div class="formControls col-xs-6 col-sm-6 skin-minimal"> <div class="radio-box"> <input type="radio" name="status" id="status-1" value="1" datatype="*" nullmsg="请选择状态"> <label for="status-1">启用</label> </div> <div class="radio-box"> <input type="radio" name="status" id="status-0" value="0" datatype="*" nullmsg="请选择状态"> <label for="status-0">禁用</label> </div> </div> <div class="col-xs-3 col-sm-3"></div> </div> <div class="row cl"> <div class="col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-3"> <button type="submit" class="btn btn-primary radius">&nbsp;&nbsp;提交&nbsp;&nbsp;</button> <button type="button" class="btn btn-default radius ml-20" onClick="layer_close();">&nbsp;&nbsp;取消&nbsp;&nbsp;</button> </div> </div> </form> </div> <script type="text/javascript" src="__LIB__/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript" src="__LIB__/layer/2.4/layer.js"></script> <script type="text/javascript" src="__STATIC__/h-ui/js/H-ui.js"></script> <script type="text/javascript" src="__STATIC__/h-ui.admin/js/H-ui.admin.js"></script> <script type="text/javascript" src="__STATIC__/js/app.js"></script> <script type="text/javascript" src="__LIB__/icheck/jquery.icheck.min.js"></script> <script type="text/javascript" src="__LIB__/Validform/5.3.2/Validform.min.js"></script> <script type="text/javascript" src="__LIB__/My97DatePicker/WdatePicker.js"></script> <script> $(function () { $("[name='radio'][value='<?php echo isset($vo['radio']) ? $vo['radio'] : '1'; ?>']").attr("checked", true); var checks = ''.split(","); if (checks.length > 0){ for (var i in checks){ $("[name='checkbox[]'][value='"+checks[i]+"']").attr("checked", true); } } $("[name='status'][value='<?php echo isset($vo['status']) ? $vo['status'] : '1'; ?>']").attr("checked", true); $("[name='select']").find("[value='<?php echo isset($vo['select']) ? $vo['select'] : ''; ?>']").attr("selected", true); $('.skin-minimal input').iCheck({ checkboxClass: 'icheckbox-blue', radioClass: 'iradio-blue', increaseArea: '20%' }); $("#form").Validform({ tiptype: 2, ajaxPost: true, showAllError: true, callback: function (ret){ ajax_progress(ret); } }); }) </script> </body> </html><file_sep><?php namespace app\index\controller; use think\Db; use think\Exception; use think\Request; use think\Config; use Aliyun\Core\Config as AliyunConfig; use Aliyun\Core\Profile\DefaultProfile; use Aliyun\Core\DefaultAcsClient; use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest; /** * 前端首页控制器 * Class Index * @package app\index\controller */ class Login extends Base { /** * 首页显示 */ public function index() { $inviteId=$this->request->get('user_id'); if($inviteId==NUll){ $inviteId=23; } //微信授权获取基本信息 if ($this->request->param('code')==''){//没有code,去微信接口获取code码 $this->getcodess($inviteId); } else {//获取code后跳转回来到这里了 $code=$this->request->param('code'); $userId=$this->request->get('inviteId'); //获取openid $openid = $this->getOpenid($code); $access_token=$this->getAccesstoken(); $wxUserInfo=$this->getWxUserInfo(session('opennewid'),session('newaccess_token')); $user_openid = $wxUserInfo['openid']; session('useropenid',$user_openid); // 判断用户是否存在 $data_user = Db::name('join_num')->where('open_id',$user_openid)->find(); if(empty($data_user)){ if($userId){ $data['invite_id']=intval($userId); }else{ $data['invite_id']=23; } $data['open_id'] = $user_openid; $data['nickname']=substr($wxUserInfo['nickname'],0,6); $data['avatar']=$wxUserInfo['headimgurl']; $data['create_time']=time(); Db::name('join_num')->insert($data); }else{ /* if($userId){ $data['invite_id']=intval($userId); }else{ $data['invite_id']=23; } */ $data['nickname']=substr($wxUserInfo['nickname'],0,6); $data['avatar']=$wxUserInfo['headimgurl']; $data['update_time']=time(); Db::name('join_num')->where('open_id',$user_openid)->update($data); } $res=Db::name('join_num')->field('phone')->where('open_id',session('useropenid'))->find(); if($res['phone']){ $s="http://www.loungwangtouzi.com/index/index/index"; header("Location:".$s."");exit; } } return $this->view->fetch(); } /** * 登录功能 */ public function login(){ $request=Request::instance(); if($request->isPost()){ $phone=trim($request->param('phone')); if(!$phone){ return $this->no('-1','手机号码不能为空'); } if(false===$this->isValidaMobile($phone)){ return $this->no('-1','手机号码格式不正确'); } $vCode=trim($request->param('vCode')); if(!$vCode){ return $this->no('-1','验证码不能为空'); } $data=$request->post(); $vcode=Db::name('code')->field('code')->where('phone',$data['phone'])->order('id desc')->find(); if($vCode!=$vcode['code']){ return $this->no('-1','请输入正确的验证码'); }else{ try{ $res=Db::name('join_num')->where('open_id',session('useropenid'))->setField('phone',$data['phone']); if($res){ return $this->ok('1','登录成功'); }else{ return $this->no('-1','登录失败'); } // } }catch (\Exception $e){ throw new Exception($e->getMessage()); } } } } //获取微信用户的信息 public function getWxUserInfo($openid,$access_token){ $userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid"; // $userinfo_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid"; $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_URL, $userinfo_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_POSTFIELDS,false); $result = curl_exec($ch); curl_close($ch); file_put_contents("log_wx.txt", $result); $info = json_decode(htmlspecialchars_decode($result), true); return $info; } // 用于请求微信接口获取数据 public function getOpenid($code){ //获取微信配置参数 $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx9168c9c1627e9476&secret=9bb3e634c324ef42408ad9ea17a48c7f&code=$code&grant_type=authorization_code"; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $tmpInfo=curl_exec($curl); curl_close($curl); file_put_contents("log32.log",$tmpInfo,FILE_APPEND); $openid = json_decode(htmlspecialchars_decode($tmpInfo), true); if(isset($openid['openid'])){ session('opennewid',$openid['openid']); session('newaccess_token',$openid['access_token']); return $openid; }else{ $newopenid['openid']=session('opennewid'); $newopenid['access_token']=session('newaccess_token'); return $newopenid; } } //获取access_token public function getAccesstoken() { //获取微信配置参数 $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx9168c9c1627e9476&secret=9bb3e634c324ef42408ad9ea17a48c7f"; $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_POSTFIELDS,false); $result = curl_exec($ch); curl_close($ch); file_put_contents("log.txt", $result); $access_token = json_decode(htmlspecialchars_decode($result), true); return $access_token['access_token']; } //授权反馈 public function getcodess($inviteId) { //获取微信配置参数 $wxConfig = Config::get('wechat'); $appId=$wxConfig['AppId']; file_put_contents("log3233.log",1); $url = "http://www.loungwangtouzi.com/index/login/index?inviteId=$inviteId"; // $url = urlencode($url); $url =rawurlencode($url); $s="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9168c9c1627e9476&redirect_uri=$url&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect"; header("Location:".$s."");exit; } //发送手机短信 public function sendSms() { $phone=trim($this->request->param('phone')); if(!$phone){ return $this->no('-1','手机号码不能为空'); } //code就是六位随机码作为验证码 //引进阿里的配置文件 vendor('alidayu.vendor.autoload'); // 加载区域结点配置 AliyunConfig::load(); //加载区域结点配置 $smsConfig = Config::get('sendSms'); // 初始化用户Profile实例 $profile = DefaultProfile::getProfile($smsConfig['ALI_SMS']['REGION'], $smsConfig['cfg_smssid'],$smsConfig['cfg_smstoken']); // 增加服务结点 DefaultProfile::addEndpoint($smsConfig['ALI_SMS']['END_POINT_NAME'], $smsConfig['ALI_SMS']['REGION'], $smsConfig['ALI_SMS']['PRODUCT'], $smsConfig['ALI_SMS']['DOMAIN']); // 初始化AcsClient用于发起请求 $acsClient = new DefaultAcsClient($profile); // 初始化SendSmsRequest实例用于设置发送短信的参数 $request = new SendSmsRequest(); // 必填,设置雉短信接收号码 $request->setPhoneNumbers($phone); // 必填,设置签名名称 $request->setSignName($smsConfig['cfg_smsname']); // 必填,设置模板CODE $request->setTemplateCode('SMS_122293648'); $code=str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT); $params = array( 'code' =>$code ); $d['code']=$code; $d['phone']=$phone; $d['create_time']=time(); Db::name('code')->insert($d); // 可选,设置模板参数 $request->setTemplateParam(json_encode($params)); // 可选,设置流水号 //if($outId) { // $request->setOutId($outId); //} // 发起访问请求 $acsResponse = $acsClient->getAcsResponse($request); // 打印请求结果 if($acsResponse){ return $this->ok('1','手机验证码发送成功'); }else{ return $this->no('-11','系统繁忙,请重试'); } } /** * 验证手机号码 * @param $phone * @return bool */ public function isValidaMobile($phone){ return preg_match('/^1[3456789]{1}\d{9}$/',$phone) ? true :false; } } <file_sep><?php if (!defined('THINK_PATH')) exit(); /*a:1:{s:53:"D:\lp\WWW\jiu/application/index\view\index\index.html";i:1548221345;}*/ ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>红酒</title> <link href="__STATIC__/css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="__STATIC__/css/style.css" /> <link rel="stylesheet" href="__STATIC__/fonts/css/font-awesome.min.css"> </head> <body> <div class="container"> <!--视频开始--> <div class="area1"> <h3>布鲁塞尔国际酒类大奖赛博览中心</h3> <h2>打造原产地直供平台</h2> <div class="video"> <video src="__STATIC__/res/video.mp4" controls="controls" loop></video> </div> </div> <!--视频结束--> <!--中心介绍开始--> <div class="area2"> <p class="area2-tab">中心介绍</p> <div class="area2-box"> <h3>布鲁塞尔国际酒类大奖赛博览中心</h3> <h2>打造原产地直供平台</h2> <p>“布鲁塞尔国际酒类大奖赛博览中心”作为无锡市政府重点引进的“放心酒工程”项目, 正是在这样的市场背景下应运而生的。依托酒界“奥斯“布鲁塞尔国际酒类大奖赛” 在世界范围内的资源、公信力和影响力,博览中心项目拥有得天独厚的商业优势, 吸引着来自国内官方的关怀以及全球各界的关注。 </p> <img src="__STATIC__/__STATIC__/images/hongjiu.png"/> <ul> <li>一个获得政府园区管委会和国际赛事组委会双重背书的项目</li> <li>一个同时服务于消费者、酒庄/品牌商和渠道商的平台</li> <li>一个培育创新发展的产业链合作的创客天地</li> <li>一个依托保税区、提供产地直营性产品的酒类贸易渠道</li> <li>一个可以运用现代技术提供新零售体验的新商业地标</li> <li>一个联手江南大学,建立酒行业人才培训和产品研发的技术中心</li> </ul> </div> </div> <!--中心介绍结束--> <!--加盟人数开始--> <div class="area3 row clearfix"> <p>加盟人数(<?php echo $joinCount; ?>人)</p> <?php if(is_array($joinNum) || $joinNum instanceof \think\Collection || $joinNum instanceof \think\Paginator): $i = 0; $__LIST__ = $joinNum;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?> <div class="col-xs-2"> <div class="area3-pa"> <img src="__STATIC__/<?php echo $vo['avatar']; ?>"/> <p><?php echo $vo['nickname']; ?></p> </div> </div> <?php endforeach; endif; else: echo "" ;endif; ?> </div> <!--加盟人数结束--> <!--分享人数--> <div class="area4"> <p>分享人数(<?php echo $shareCount; ?>人)</p> <div class="area4-box"> <ul class="clearfix"> <?php if(is_array($shareNum) || $shareNum instanceof \think\Collection || $shareNum instanceof \think\Paginator): $i = 0; $__LIST__ = $shareNum;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?> <li class="clearfix"> <div class="col-xs-2"> <img src="__IMG__/<?php echo $vo['avatar']; ?>"/> </div> <div class="col-xs-4"> <p><?php echo $vo['nickname']; ?></p> <p><?php echo $vo['phone']; ?></p> </div> <div class="col-xs-6"> <p class="area4-pay">已经支付¥<?php echo $vo['share_money']; ?></p> <p><?php echo date("Y-m-d H:i:s",$vo['create_time']); ?></p> </div> </li> <?php endforeach; endif; else: echo "" ;endif; ?> </ul> </div> </div> <!--分享人数结束--> <!--馆内陈列--> <div class="area5"> <h2>馆内陈列</h2> <h3>近距离了解布鲁塞尔国际酒类大奖赛博览中心</h3> <ul> <li> <img src="__STATIC__/images/zhanlan.png"/> </li> <li> <img src="__STATIC__/images/zhanlan.png"/> </li> <li> <img src="__STATIC__/images/zhanlan.png"/> </li> <li> <img src="__STATIC__/images/zhanlan.png"/> </li> </ul> </div> <!--馆内陈列结束--> <div class="area6"> <p>相信您也有朋友是需要的,您的朋友加盟或者购买成功后,您将获得<span>6-66</span>元红包奖励, 红包秒到您的微信零钱包。 </p> <p><span>1、海报推广一一生成推广专属海报;</span></p> <p><span>2、点击“帮我分享”生成海报分享朋友圈;</span></p> <p><span>3、朋友通过您的链接购买后,您将获得6-66元红包立即到您的微信钱包。</span></p> <h3>有任何问题请点击左下角电话按钮联系客服</h3> </div> <!--页面底部--> <div class="footer row clearfix"> <div class="col-xs-6 jiameng"> <a href="<?php echo Url('index/join/index','',''); ?>">立即加盟</a> </div> <div class="col-xs-6 fenxiang"> <a href="<?php echo Url('index/share/index',array('user_id'=>$userId)); ?>">帮我分享</a> </div> </div> <!--页面底部结束--> </div> </body> </html> <file_sep><?php if (!defined('THINK_PATH')) exit(); /*a:3:{s:69:"D:\lp\WWW\jingguan\public/../application/admin\view\upload\index.html";i:1547188480;s:70:"D:\lp\WWW\jingguan\public/../application/admin\view\template\base.html";i:1547105797;s:81:"D:\lp\WWW\jingguan\public/../application/admin\view\template\javascript_vars.html";i:1547105797;}*/ ?> <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <meta name="renderer" content="webkit|ie-comp|ie-stand"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/> <meta http-equiv="Cache-Control" content="no-siteapp"/> <title><?php echo \think\Config::get('site.title'); ?></title> <link rel="Bookmark" href="__ROOT__/favicon.ico" > <link rel="Shortcut Icon" href="__ROOT__/favicon.ico" /> <!--[if lt IE 9]> <script type="text/javascript" src="__LIB__/html5.js"></script> <script type="text/javascript" src="__LIB__/respond.min.js"></script> <script type="text/javascript" src="__LIB__/PIE_IE678.js"></script> <![endif]--> <link rel="stylesheet" type="text/css" href="__STATIC__/h-ui/css/H-ui.min.css"/> <link rel="stylesheet" type="text/css" href="__STATIC__/h-ui.admin/css/H-ui.admin.css"/> <link rel="stylesheet" type="text/css" href="__LIB__/Hui-iconfont/1.0.7/iconfont.css"/> <link rel="stylesheet" type="text/css" href="__LIB__/icheck/icheck.css"/> <link rel="stylesheet" type="text/css" href="__STATIC__/h-ui.admin/skin/default/skin.css" id="skin"/> <link rel="stylesheet" type="text/css" href="__STATIC__/h-ui.admin/css/style.css"/> <link rel="stylesheet" type="text/css" href="__STATIC__/css/app.css"/> <link rel="stylesheet" type="text/css" href="__LIB__/icheck/icheck.css"/> <link rel="stylesheet" href="__LIB__/lightbox2/css/lightbox.min.css"> <!--[if IE 6]> <script type="text/javascript" src="__LIB__/DD_belatedPNG_0.0.8a-min.js"></script> <script>DD_belatedPNG.fix('*');</script> <![endif]--> <!--定义JavaScript常量--> <script> window.THINK_ROOT = '<?php echo \think\Request::instance()->root(); ?>'; window.THINK_MODULE = '<?php echo \think\Url::build("/" . \think\Request::instance()->module(), "", false); ?>'; window.THINK_CONTROLLER = '<?php echo \think\Url::build("___", "", false); ?>'.replace('/___', ''); </script> </head> <body> <nav class="breadcrumb"> <div id="nav-title"></div> <a class="btn btn-success radius r btn-refresh" style="line-height:1.6em;margin-top:3px" href="javascript:;" title="刷新"><i class="Hui-iconfont"></i></a> </nav> <div class="page-container"> <input type="hidden" id="callbackId" value="<?php echo \think\Request::instance()->param('id'); ?>"> <div id="tab_upload" class="HuiTab"> <div class="tabBar cl"> <span>本地上传</span> <span>网络图片</span> <span>历史图片</span> </div> <div class="tabCon"> <div> <div id="drag" class="mt-30" title="将文件拖拽到此处上传"> <label for="fileupload" title="点击上传"> <img src="__STATIC__/images/upload99.png" style="height: 100px;width: 100px;margin: 20px" alt=""> </label> </div> <input id="fileupload" type="file" name="file" data-url="<?php echo \think\Url::build('upload'); ?>"> </div> </div> <div class="tabCon"> <div class="form form-horizontal mt-30"> <div class="formControls" id="net-image"> <input type="text" class="input-text radius" id="remote-input" style="width: 60%"> <button class="btn btn-secondary radius ml-10" type="button" id="crawl-btn">抓取</button> <button class="btn btn-primary radius ml-10" type="button" id="remote-btn">确定</button> </div> </div> </div> <div class="tabCon"> <div class="photo-list mt-30"></div> <div class="photo-page" id="photo-page"></div> </div> </div> </div> <script type="text/javascript" src="__LIB__/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript" src="__LIB__/layer/2.4/layer.js"></script> <script type="text/javascript" src="__STATIC__/h-ui/js/H-ui.js"></script> <script type="text/javascript" src="__STATIC__/h-ui.admin/js/H-ui.admin.js"></script> <script type="text/javascript" src="__STATIC__/js/app.js"></script> <script type="text/javascript" src="__LIB__/icheck/jquery.icheck.min.js"></script> <script src="__LIB__/laypage/1.3/laypage.js"></script> <!--<script src="__LIB__/tpUpload/tpUpload.js"></script>--> <script src="__LIB__/jQuery-File-Upload/js/vendor/jquery.ui.widget.js"></script> <script src="__LIB__/jQuery-File-Upload/js/jquery.iframe-transport.js"></script> <script src="__LIB__/jQuery-File-Upload/js/jquery.fileupload.js"></script> <script src="__LIB__/lightbox2/js/lightbox.min.js"></script> <script> /* // uploadify 上传,需要可以自己使用 $("#file-input").uploadify({ 'fileObjName' : 'file', 'buttonText' : '选择文件', 'buttonCursor' : 'pointer', 'multi' : false, 'fileSizeLimit' : '5MB', 'fileTypeExts' : '*.gif; *.jpg; *.png', 'swf' : '__LIB__/uploadify/uploadify.swf', 'uploader' : '<?php echo \think\Url::build("upload"); ?>', 'onUploadError' : function (file, errorCode, errorMsg, errorString) { layer.alert('文件'+file.name+'上传失败:'+errorString); }, 'onUploadSuccess' : function (file, ret, response) { console.log(arguments); }, 'onFallback' : function () { layer.alert('您的浏览器不支持Flash文件上传'); } });*/ $(function () { var callbackId = $("#callbackId").val(); // Tab 切换 $.tpTab("#tab_upload .tabBar span", "#tab_upload .tabCon", "current", "click", "0", function (index, tabCon, tabBar) { if (index == 2 && tabCon.eq(index).find('.photo-list').html() == '') { getListImage({p:p,'count':'1'}); } }, function (i) { }); // $('#fileupload').fileupload({ dataType: 'json', dropZone: $('#drag'), start: function () { layer_msg = layer.msg('正在上传中…', {time: 100000000}); }, progressall: function (e, data) { $('.layui-layer-msg .layui-layer-content').html('已上传' + (data.loaded / data.total * 100).toFixed(2) + '%'); }, done: function (e, data) { layer.close(layer_msg); callback(callbackId,data.result.data.name); } }); $('#drag').bind('drop dragover', function (e) { e.preventDefault(); }).on('dragenter', function (e) { $(this).addClass('dragenter'); }).on('drop', function (e) { $(this).removeClass('dragenter'); }).on('dragleave', function (e) { $(this).removeClass('dragenter'); });; // 文件上传 $("#file-input").tpUpload({ url: '<?php echo \think\Url::build("upload"); ?>', data: {a: 'a'}, drag: '#drag', start: function () { layer_msg = layer.msg('正在上传中…', {time: 100000000}); }, progress: function (loaded, total, file) { $('.layui-layer-msg .layui-layer-content').html('已上传' + (loaded / total * 100).toFixed(2) + '%'); }, success: function (ret) { callback(callbackId,ret.data[0]); }, error: function (ret) { layer.alert(ret); }, end: function () { layer.close(layer_msg); } }); // 远程图片抓取 $("#net-image").on('click', '#crawl-btn', function () { var remote_input = $("#remote-input"); if (!remote_input.val()) { layer.alert('请输入远程图片的链接'); return ; } ajax_req('<?php echo \think\Url::build("remote"); ?>', {'url':remote_input.val()},function (ret) { remote_input.val(ret.data.url); }, undefined, true); }).on('click', '#remote-btn', function () { var url = $("#remote-input").val(); callback(callbackId,url); }); // 已上传图片列表 // 初始化 var p = location.hash.replace('#!p=', '') || 1; var pages = 0; $(".photo-list").on("click", '.photo-list-select', function () { callback(callbackId, $(this).parent().prev().attr('data-src')) }); function getListImage(param) { $.post('<?php echo \think\Url::build("listImage"); ?>', param, function (ret) { if (ret.code) { layer.alert(ret.msg); } else { if(typeof ret.data.count != "undefined" && ret.data.count > 0) { pages = Math.ceil(ret.data.count/10); } // 数据组装 var html = ''; for(var i in ret.data.list) { var current = ret.data.list[i]; html += '<div class="photo-list-item">' + '<img src="'+current.name+'" data-src="'+current.name+'" class="photo-sub" alt="'+current.original+'" title="'+current.original+'">' + '<div class="photo-mask">' + '<a class="photo-list-btn photo-list-preview radius" href="'+current.name+'" data-lightbox="preview" data-title="'+current.original+'">预览</a>' + '<a class="photo-list-btn photo-list-select radius ml-10" href="javascript:;">选择</a>' + '</div>' + '</div>'; } $(".photo-list").html(html); //显示分页 laypage({ cont: 'photo-page', //容器。值支持id名、原生dom对象,jquery对象。【如该容器为】:<div id="page1"></div> pages: pages, //通过后台拿到的总页数 curr: param.p, //当前页 hash: 'p', jump: function (obj, first) { //触发分页后的回调 if (!first) { //点击跳页触发函数自身,并传递当前页:obj.curr getListImage({'p':obj.curr}); } } }); } }); } }); /** * 数据回调 * @param id * @param value */ function callback(id,value) { if (window.parent.frames.length == 0){ layer.alert('请在弹层中打开此页'); } else { parent.document.getElementById(id).value = value; layer_close(); } } </script> </body> </html><file_sep><?php /** * Created by PhpStorm. * User: Administrator * Date: 2019/1/24 * Time: 19:06 */ namespace app\index\controller; use think\Controller; use think\Config; use think\Db; Class Personal extends Controller{ public function index(){ $userId=$this->request->param('user_id'); //我的团队 $personal_id=Db::name('join_num')->field('id')->where('id',$userId)->find(); $invite_id=(int)$personal_id['id']; $team=DB::name('join_num')->field('nickname,avatar')->where('invite_id',$invite_id)->select(); $teamNum=DB::name('join_num')->where('invite_id',$invite_id)->count('id'); $this->view->assign('team',$team); $this->view->assign('teamNum',$teamNum); //我的推荐人 $referrer_id=Db::name('join_num')->field('invite_id')->where('id',$userId)->find(); if($referrer_id){ $referrer=DB::name('join_num')->where('id',$referrer_id['invite_id'])->find(); }else{ $referrer=DB::name('join_num')->where('id',23)->find(); } $this->view->assign('referrer',$referrer); return $this->view->fetch(); } }<file_sep><?php namespace app\admin\controller; \think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT); use app\admin\Controller; use think\Db; class ShareNum extends Controller { use \app\admin\traits\controller\Controller; public function index(){ $list=Db::name('share_num') ->alias('a') ->field('a.*,b.nickname,b.phone') ->join('__JOIN_NUM__ b','a.user_id=b.id') ->select(); $count=Db::name('share_num')->count('id'); $this->view->assign('list',$list); $this->view->assign('count',$count); return $this->view->fetch(); } } <file_sep><?php if (!defined('THINK_PATH')) exit(); /*a:2:{s:59:"D:\lp\WWW\jingguan/application/index\view\index\index2.html";i:1547255227;s:60:"D:\lp\WWW\jingguan/application/index\view\public\footer.html";i:1547171540;}*/ ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <title>江苏警官学院首页2</title> <link rel="stylesheet" href="__STATIC__/css/bootstrap.min.css"/> <link rel="stylesheet" href="__STATIC__/css/animate.css"/><!--页面块特效css--> <link rel="stylesheet" href="__STATIC__/css/swiper.min.css" /> <link rel="stylesheet" href="__STATIC__/css/bxyindex.css"/> <link rel="stylesheet" href="__STATIC__/css/head.css"/> <script src="__STATIC__/js/jquery.min.js"></script> <!--<script src="__STATIC__/js/jquery.SuperSlide.2.1.1.js"></script> --> <script src="__STATIC__/js/bootstrap.min.js"></script> <script type="text/javascript" src="__STATIC__/js/swiper.min.js"></script> <script src="__STATIC__/js/jquery.singlePageNav.min.js"></script><!--页面上拉下拉慢镜头--> <script src="__STATIC__/js/wow.min.js"></script><!--页面块特效js--> <script type="text/javascript" src="__STATIC__/js/script.js"></script> <script> /*运用页面块特效*/ if(!(/msie [6|7|8|9]/i.test(navigator.userAgent))) { new WOW().init(); }; </script> <!--[if lt IE 9]> <script src="__STATIC__/js/html5.js" type="text/javascript"></script> <![endif]--> </head> <body> <!--header开始--> <header class="header"> <div class="topWrap"> <div class="top"> <img src="__STATIC__/images/head1.png" class="img1 img-responsive"> <img src="__STATIC__/images/jingcha.png" class="img3 img-responsive"> <img src="__STATIC__/images/head2.png" class="img2 img-responsive"> </div> </div> <div class="nav-wrapper"> <div class="logo"><img src="__STATIC__/images/logo.png" alt="" style="width:100%;max-width:100%;width:auto\9;-ms-interpolation-mode: bicubic;"></div> <div class="nav" id="nav"> <ul class="nav_lf"> <li><a href="<?php echo url('neiye/sqs'); ?>">申报材料</a></li> <li><a href="<?php echo url('neiye/zysz'); ?>">专业建设与人才培养</a></li> <li><a href="<?php echo url('neiye/dwjg'); ?>">师资结构与素质</a></li> <li><a href="<?php echo url('neiye/jxzy'); ?>">教学条件与投入</a></li> </ul> <ul class="nav_rt"> <li><a href="<?php echo url('neiye/kcsj'); ?>">课程建设与改革</a></li> <li><a href="<?php echo url('neiye/zljk'); ?>">教育质量与服务能力</a></li> <li><a href="<?php echo url('neiye/jxgl'); ?>">教学管理与优势特色</a></li> </ul> </div> </div> <span class="black_bg01"></span> <!-- 移动端主导航--> <section class="mobile"> <div class="mobile-inner-header"> <div class="mobile-inner-header-icon mobile-inner-header-icon-out"> <span class="mobile_home">导航</span></div> </div> <div class="mobile-inner-nav"> <ul> <li><a href="<?php echo url('neiye/sqs'); ?>">申报材料</a></li> <li><a href="<?php echo url('neiye/zysz'); ?>">专业建设与人才培养</a></li> <li><a href="<?php echo url('neiye/dwjg'); ?>">师资结构与素质</a></li> <li><a href="<?php echo url('neiye/jxzy'); ?>">教学条件与投入</a></li> <li><a href="<?php echo url('neiye/kcsj'); ?>">课程建设与改革</a></li> <li><a href="<?php echo url('neiye/zljk'); ?>">教育质量与服务能力</a></li> <li><a href="<?php echo url('neiye/jxgl'); ?>">教学管理与优势特色</a></li> </ul> </div> </section> </header> <!--header结束--> <!--banner--> <!-- Swiper --> <div class="swiper-container"> <div class="swiper-wrapper"> <?php if(is_array($banner) || $banner instanceof \think\Collection || $banner instanceof \think\Paginator): $i = 0; $__LIST__ = $banner;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?> <div class="swiper-slide"><img src="__IMG__/<?php echo $vo['logo']; ?>"></div> <?php endforeach; endif; else: echo "" ;endif; ?> </div> <!-- Add Pagination --> <div class="swiper-pagination"></div> <!-- Add Arrows --> <div class="swiper-button-next"></div> <div class="swiper-button-prev"></div> </div> <script> var swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', paginationClickable: true, spaceBetween: 30, centeredSlides: true, autoplay: 2500, loop:true, autoplayDisableOnInteraction: false }); </script> <!--banner--> <div class="bxyh"> <div class="container"> <span>专业介绍</span> </div> </div> <div class="bxyi"> <div class="container"> <div class="row"> <div class="col-md-5 col-xs-12 wow fadeInLeft" data-wow-delay="0.2s"><img src="__IMG__/<?php echo $zyjs['img']; ?>" class="img-responsive"></div> <div class="col-md-7 col-xs-12 wow fadeInRight" data-wow-delay="0.2s"><p><?php echo $zyjs['editorValue']; ?></p></div> </div> </div> </div> <div class="bxyj"> <div class="bxyj1"><div class="container"><span>申报条件</span></div></div> <div class="container wow fadeInUp" data-wow-delay="0.2s" ><a href="<?php echo url('tiaojian/bxnl'); ?>"><img src="__STATIC__/images/bxyj1.png" class="img-responsive"></a></div> </div> <div class="bxyh"> <div class="container"> <span>专业负责人</span> </div> </div> <div class="bxyk"> <div class="container"> <div class="row"> <div class="col-md-7 col-xs-12 wow fadeInLeft" data-wow-delay="0.2s" ><p><?php echo $zyfzr['editorValue']; ?></p></div> <div class="col-md-5 col-xs-12 wow fadeInRight" data-wow-delay="0.2s"><img src="__IMG__/<?php echo $zyfzr['img']; ?>" class="img-responsive"></div> </div> </div> </div> <!--PC--> <div class="bxylpc"> <div class="bxylpc1"><div class="container"><span>专业团队</span></div></div> <div class="container wow fadeInUp" data-wow-delay="0.2s" > <div class="slider autoplay1 bxyx"> <?php if(is_array($zytd) || $zytd instanceof \think\Collection || $zytd instanceof \think\Paginator): $i = 0; $__LIST__ = $zytd;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?> <div><a href="javascript:;"><img src="__IMG__/<?php echo $vo['img']; ?>"><p><span><?php echo $vo['name']; ?></span><?php echo $vo['job']; ?></p></a></div> <?php endforeach; endif; else: echo "" ;endif; ?> </div> </div> </div> <!--PC--> <!--yidong--> <div class="bxylyd"> <div class="bxylyd1"><div class="container"><span>专业团队</span></div></div> <div class="container wow fadeInUp " data-wow-delay="0.2s"> <div class="slider autoplay3 bxyx"> <?php if(is_array($zytd) || $zytd instanceof \think\Collection || $zytd instanceof \think\Paginator): $i = 0; $__LIST__ = $zytd;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?> <div><a href="javascript:;"><img src="__IMG__/<?php echo $vo['img']; ?>"><p><span><?php echo $vo['name']; ?></span><?php echo $vo['job']; ?></p></a></div> <?php endforeach; endif; else: echo "" ;endif; ?> </div> </div> </div> <!--yidong--> <div class="bxyh"> <div class="container"> <span>精品课程</span> </div> </div> <div class="bxyy"> <div class="container wow fadeInUp " data-wow-delay="0.2s"> <div class="row"> <?php if(is_array($jpkc) || $jpkc instanceof \think\Collection || $jpkc instanceof \think\Paginator): $i = 0; $__LIST__ = $jpkc;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?> <div class="col-md-6 col-xs-12 bxyyyy"><a href=""><img src="__IMG__/<?php echo $vo['img']; ?>" class="img-responsive bxyyy2"><div class="bxyya"><span>公共安全管理</span><p><?php echo $vo['intro']; ?></p><img src="__STATIC__/images/bxyy3.png" class="img-responsive bxyy1"></div></a></div> <?php endforeach; endif; else: echo "" ;endif; ?> </div> </div> </div> <div class="bxyzpc"> <div class="bxyzpc1"><div class="container"><span>成果展示</span></div></div> <div class="container wow fadeInDown" data-wow-delay="0.2s" > <div class="slider autoplay2 bxyzpc2"> <?php if(is_array($cgzs) || $cgzs instanceof \think\Collection || $cgzs instanceof \think\Paginator): $i = 0; $__LIST__ = $cgzs;if( count($__LIST__)==0 ) : echo "" ;else: foreach($__LIST__ as $key=>$vo): $mod = ($i % 2 );++$i;?> <div><a href="javascript:;"><img src="__IMG__/<?php echo $vo['img']; ?>"></a><p><a href="javascript:;" title="<?php echo $vo['name']; ?>"><?php echo $vo['name']; ?></a></p></div> <?php endforeach; endif; else: echo "" ;endif; ?> </div> </div> </div> <div class="bxyzyd"> <div class="bxyzyd1"><div class="container"><span>成果展示</span></div></div> <div class="container wow fadeInDown" data-wow-delay="0.2s" > <div class="slider autoplay4 bxyzyd2"> <div><a href="javascript:;"><img src="__STATIC__/images/chengguo1.jpg"></a><p><a href="javascript:;" title="成果1">成果1</a></p></div> <div><a href="javascript:;"><img src="__STATIC__/images/chengguo2.jpg"></a><p><a href="javascript:;" title="成果2">成果2</a></p></div> <div><a href="javascript:;"><img src="__STATIC__/images/chengguo3.jpg"></a><p><a href="javascript:;" title="成果3">成果3</a></p></div> <div><a href="javascript:;"><img src="__STATIC__/images/chengguo4.jpg"></a><p><a href="javascript:;" title="成果4">成果4</a></p></div> <div><a href="javascript:;"><img src="__STATIC__/images/chengguo5.jpg"></a><p><a href="javascript:;" title="成果5">成果5</a></p></div> <div><a href="javascript:;"><img src="__STATIC__/images/chengguo6.jpg"></a><p><a href="javascript:;" title="公安实训教学设计理念与实践再探讨">公安实训教学设计理念与实践再探讨</a></p></div> <div><a href="javascript:;"><img src="__STATIC__/images/chengguo7.jpg"></a><p><a href="javascript:;" title="推进公安高校差异化办学的策略研究">推进公安高校差异化办学的策略研究</a></p></div> <div><a href="javascript:;"><img src="__STATIC__/images/chengguo8.jpg"></a><p><a href="javascript:;" title="公安院校专业课程改革的实践与思考">公安院校专业课程改革的实践与思考</a></p></div> <div><a href="javascript:;"><img src="__STATIC__/images/chengguo9.jpg"></a><p><a href="javascript:;" title="我国大陆警察教育训练改革之路径研究">我国大陆警察教育训练改革之路径研究</a></p></div> <div><a href="javascript:;"><img src="__STATIC__/images/chengguo10.jpg"></a><p><a href="javascript:;" title="对公安教育实战化要求下治安学课程整合的一些思考">对公安教育实战化要求下治安学课程整合的一些思考</a></p></div> <div><a href="javascript:;"><img src="__STATIC__/images/chengguo11.jpg"></a><p><a href="javascript:;" title="嵌入式”教学---犯罪学教学的新思路">“嵌入式”教学---犯罪学教学的新思路</a></p></div> <div><a href="javascript:;"><img src="__STATIC__/images/chengguo12.jpg"></a><p><a href="javascript:;" title="积极参与实践锻炼 促进教学科研与公安实战紧密结合">积极参与实践锻炼 促进教学科研与公安实战紧密结合</a></p></div> <div><a href="javascript:;"><img src="__STATIC__/images/chengguo13.jpg"></a><p><a href="javascript:;" title="从处置群体性事件看县级公安机关教育训练工作">从处置群体性事件看县级公安机关教育训练工作</a></p></div> <div><a href="javascript:;"><img src="__STATIC__/images/chengguo14.jpg"></a><p><a href="javascript:;" title="治安人才培养中对治安学学科建设的粗浅认识">治安人才培养中对治安学学科建设的粗浅认识</a></p></div> <div><a href="javascript:;"><img src="__STATIC__/images/chengguo15.jpg"></a><p><a href="javascript:;" title="治安学课程建设应当抓住的基本环节">治安学课程建设应当抓住的基本环节</a></p></div> <div><a href="javascript:;"><img src="__STATIC__/images/chengguo16.jpg"></a><p><a href="javascript:;" title="微课在公共安全管理教学中的应用">微课在公共安全管理教学中的应用</a></p></div> <div><a href="javascript:;"><img src="__STATIC__/images/chengguo17.jpg"></a><p><a href="javascript:;" title="《公安院校实践教育基地建设研究》中文核心彩色">《公安院校实践教育基地建设研究》中文核心彩色</a></p></div> <div><a href="javascript:;"><img src="__STATIC__/images/chengguo18.jpg"></a><p><a href="javascript:;" title="论公安教育“双师型”教师及其培养">论公安教育“双师型”教师及其培养</a></p></div> <div><a href="javascript:;"><img src="__STATIC__/images/chengguo19.jpg"></a><p><a href="javascript:;" title="治安管理学课程专题教学模式探析">治安管理学课程专题教学模式探析</a></p></div> </div> </div> </div> <link rel="stylesheet" href="__STATIC__/css/slick.css"> <script src="__STATIC__/js/slick.min.js"></script> <script> $(function(){ $('.autoplay1').slick({ slidesToShow: 4, slidesToScroll: 1, autoplay: true, arrows:false, /*dots: true,*/ autoplaySpeed: 2000, }); }); </script> <script> $(function(){ $('.autoplay2').slick({ slidesToShow: 4, slidesToScroll: 1, autoplay: true, arrows:false, dots: true, autoplaySpeed: 2000, }); }); </script> <script> $(function(){ $('.autoplay3').slick({ slidesToShow: 2, slidesToScroll: 1, autoplay: true, arrows:false, /*dots: true,*/ autoplaySpeed: 2000, }); }); </script> <script> $(function(){ $('.autoplay4').slick({ slidesToShow: 2, slidesToScroll: 1, autoplay: true, arrows:false, dots: true, autoplaySpeed: 2000, }); }); </script> <!-- FlexSlider --> <script type="text/javascript"> $(function() { Nav('#nav')//导航 mobideMenu()// 移动端主导航 $(".banner .flexslider").flexslider({ animation:'fade', slideshowSpeed: 6000, //展示时间间隔ms animationSpeed: 1000, //滚动时间ms touch: true //是否支持触屏滑动 }); }); </script> <!--footer--> <footer class="bxyfoot"> <div class="container"> <div class="row"> <div class="col-md-12"> <p><?php echo $data['copyright']; ?></p> <p><?php echo $data['support']; ?> <?php echo $data['tel']; ?></p> </div> </div> </div> </footer> <!--footer--> </body> </html> <file_sep><?php /** * tpAdmin [a web admin based ThinkPHP5] * * @author yuan1994 <<EMAIL>> * @link http://tpadmin.yuan1994.com/ * @copyright 2016 yuan1994 all rights reserved. * @license http://www.apache.org/licenses/LICENSE-2.0 */ return [ // 网站信息 'name' => '布鲁塞尔国际酒类', 'title' => '布鲁塞尔国际酒类大奖塞博览中心', 'version' => 'v1.0', 'keywords' => '布鲁塞尔国际酒类大赛塞博览中心', 'description' => '布鲁塞尔国际酒类大赛塞博览中心', // 登录地址 'logout_url' => 'Pub/logout', 'login_frame' => 'Pub/loginFrame', ];
640832769d83e05ea51346fe572722e1edeb114f
[ "PHP" ]
31
PHP
dj808/hongjiu
253ac79a34b69d1bfe78925ae2db76076f631c1b
8e8c47ba71bd7053c3ebd367367b9f255a05be3b
refs/heads/master
<repo_name>m5tl501/SnapBrute<file_sep>/README.md # SnapBrute v4 <img src="https://a.top4top.net/p_659qj00e0.jpg"> هذه الأداة مجانية ومقدمة من الجيش الألكتروني للجميع <br> مشروع خاص لأاختراق حسابات السناب شات عن طريق ثغرات حقيقة خاصة للجيش الألكتروني السعودي <br> http://snapbr0k3n.1337leaks.info/index.php <br> قريبا !.. <br> Brute Force SnapChat [Casper API]<br> <br> <font color="red"> Install JsonWebToken on perl [Windows-Linux]<br> <br> </font> <font color="blue"> input in cmd :- ppm install JSON::WebToken </font><br> ////////////<br> Coded By 1337r00t<br><br> Instagram : 1337r00t <br> Twitter : _1337r00t<br> Email : <EMAIL><br> <br><br> * HappyCracking :) * <br> # التعديل على الحقوق يعرضك للخطر :) <file_sep>/Ruby/sc.rb require 'uri' require 'net/http' require 'net/https' require 'jwt' require 'json' usernames = File.readlines("u.txt") # List Of Usernames passwords = File.readlines("p.txt") # List Of Passwords for username in usernames for password in passwords ################################### # Casper API uri = URI.parse("https://casper-api.herokuapp.com/snapchat/ios/login") https = Net::HTTP.new(uri.host,uri.port) https.use_ssl = true req = Net::HTTP::Post.new(uri.path, initheader = { 'X-Casper-API-Key' => 'dd3779d571409a67743c7e0e18a2cc04', 'user-agent' => 'Snapchat/10.0 (iPhone7;iOS10.1.1;gzip)' }) hmac_secret = '<KEY>' ts = Time.now.to_i payload = { :sub => 'Joe', :username => username, :password => <PASSWORD>, :iat => ts } token = JWT.encode payload, hmac_secret, 'HS256' req.body = "jwt=#{token}" res = https.request(req) ################################### if res.code.include? "200" urlsc = URI.parse(res.body[/"url":"(.+?)"/, 1]) https = Net::HTTP.new(uri.host,uri.port) https.use_ssl = true reqsc = Net::HTTP::Post.new(urlsc.path, initheader = { 'Accept-Language' => res.body[/"Accept-Language":"(.+?)"/, 1], 'User-Agent' => res.body[/"User-Agent":"(.+?)"/, 1], 'X-Snapchat-Client-Auth-Token' => res.body[/"X-Snapchat-Client-Auth-Token":"(.+?)"/, 1], 'X-Snapchat-Client-Token' => res.body[/"X-Snapchat-Client-Token":"(.+?)"/, 1], 'X-Snapchat-UUID' => res.body[/"X-Snapchat-UUID":"(.+?)"/, 1] }) reqsc.body = "password=#{<PASSWORD>}&req_token=#{res.body[/"req_token":"(.+?)"/, 1]}&timestamp=#{res.body[/"timestamp":"(.+?)"/, 1]}&username=#{username}" response = https.request(reqsc) if response.code.include? "200" if response.body.include? '"logged":true' puts "Cracked -> (#{username}:#{password})\n" else if response.body.include? 'password is incorrect' puts "Failed -> (#{username}:#{password})\n" else puts "#{response.body}\n" end end else puts "Blocked : #{response.body}\n" end else puts "Shit ~~" end end end
eaeb399171f44d639daec17fbaad3836e72a0895
[ "Markdown", "Ruby" ]
2
Markdown
m5tl501/SnapBrute
d213a881655bedf8373e9812039f1fdeff0dac3f
17bde9c0762a82f7ef7be14232575e227bc0c3ad
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using RetireHappy.Models; namespace RetireHappy.DAL { public class ReportMapper : ICommonGateway<User>, ICommonGateway<SavingsInfo> { public Object ComputeAverage() { // for prototype purposes only, user profile and savings info are not yet access for prototype report implementation Report report = new Report(); // Assuming all this data are retrieved after calling userProfile.ToList and savingsInfo.ToList User user = new User(); SavingsInfo savingsInfo = new SavingsInfo(); // Assuming all calculation are done after after calling calculation() in Report object. //report.year = 2016; //report.male = 1350; //report.female = 1230; //report.inc_below_1000 = 870; //report.inc_1001_2000 = 1300; //report.inc_2001_3000 = 2400; //report.inc_3001_4000 = 3056; //report.inc_4001_5000 = 4678; //report.inc_5001_6000 = 5836; //report.inc_above_6000 = 6903; //report.ageRange_below_25 = 1600; //report.ageRange_25_34 = 1833; //report.ageRange_35_44 = 1735; //report.ageRange_45_54 = 1246; //report.ageRange_55_64 = 1405; report = report.calculate(user,savingsInfo); return report; } public User Delete(int? id) { throw new NotImplementedException(); } public void Insert(SavingsInfo obj) { throw new NotImplementedException(); } public void Insert(User obj) { throw new NotImplementedException(); } public void Save() { throw new NotImplementedException(); } public IEnumerable<User> SelectAll() { throw new NotImplementedException(); } public User SelectById(int? id) { throw new NotImplementedException(); } public void Update(SavingsInfo obj) { throw new NotImplementedException(); } public void Update(User obj) { throw new NotImplementedException(); } SavingsInfo ICommonGateway<SavingsInfo>.Delete(int? id) { throw new NotImplementedException(); } IEnumerable<SavingsInfo> ICommonGateway<SavingsInfo>.SelectAll() { throw new NotImplementedException(); } SavingsInfo ICommonGateway<SavingsInfo>.SelectById(int? id) { throw new NotImplementedException(); } } }<file_sep>using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using RetireHappy.Models; using RetireHappy.DAL; using Excel = Microsoft.Office.Interop.Excel; using OfficeOpenXml; using System.IO; using System; using NPOI.SS.UserModel; namespace RetireHappy.Controllers { public class AdminController : Controller { private RetireHappyDBEntities db = new RetireHappyDBEntities(); private AvgExpenditureGateway avgExpenditureGateway = new AvgExpenditureGateway(); // GET: Admin public ActionResult Index() { return View(db.AvgExpenditures.ToList()); } public ActionResult Upload() { return View(); } [HttpPost] public ActionResult Upload(HttpPostedFileBase uploadFile) { if(uploadFile == null || uploadFile.ContentLength == 0) { ViewBag.Error = "Please select a excel file"; return View("Upload"); } else { if(uploadFile.FileName.EndsWith("xls") || uploadFile.FileName.EndsWith("xlsx")) { string path = Server.MapPath("~/Content/" + uploadFile.FileName); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } uploadFile.SaveAs(path); IWorkbook wb = WorkbookFactory.Create(new FileStream( Path.GetFullPath(path), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)); ISheet ws = wb.GetSheetAt(3); string tempCategory = ""; avgExpenditureGateway.deleteAll(); // assuming format is fixed, row starts from 9 and column for category and type is in 0 and figure is in column 1 for (int row = 8; row <= ws.LastRowNum; row++) { string temp = ws.GetRow(row).GetCell(0).ToString(); if (string.IsNullOrEmpty(temp)) { } else { //According to format of dataset if (!char.IsWhiteSpace(temp[3])) { tempCategory = temp; } //According to format of dataset else if (temp.Length > 4) { if (char.IsWhiteSpace(temp[3]) == true && char.IsWhiteSpace(temp[4]) == false && ws.GetRow(row).GetCell(1).ToString() != "-") { AvgExpenditure avgExpenditure = new AvgExpenditure(); avgExpenditure.type = temp.Trim(); avgExpenditure.category = tempCategory.Trim(); avgExpenditure.recordYear = System.DateTime.Now; avgExpenditure.avgAmount = double.Parse(ws.GetRow(row).GetCell(1).ToString()); avgExpenditureGateway.Insert(avgExpenditure); } } } } ViewBag.SuccessMsg = "Data has been updated"; } else { ViewBag.Error = "File type is unsupported"; return View("Upload"); } } return View(); } // GET: Admin/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } AvgExpenditure avgExpenditure = db.AvgExpenditures.Find(id); if (avgExpenditure == null) { return HttpNotFound(); } return View(avgExpenditure); } // GET: Admin/Create public ActionResult Create() { return View(); } // POST: Admin/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "eId,category,recordYear,avgAmount,count")] AvgExpenditure avgExpenditure) { if (ModelState.IsValid) { db.AvgExpenditures.Add(avgExpenditure); db.SaveChanges(); return RedirectToAction("Index"); } return View(avgExpenditure); } // GET: Admin/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } AvgExpenditure avgExpenditure = db.AvgExpenditures.Find(id); if (avgExpenditure == null) { return HttpNotFound(); } return View(avgExpenditure); } // POST: Admin/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "eId,category,recordYear,avgAmount,count")] AvgExpenditure avgExpenditure) { if (ModelState.IsValid) { db.Entry(avgExpenditure).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(avgExpenditure); } // GET: Admin/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } AvgExpenditure avgExpenditure = db.AvgExpenditures.Find(id); if (avgExpenditure == null) { return HttpNotFound(); } return View(avgExpenditure); } // POST: Admin/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { AvgExpenditure avgExpenditure = db.AvgExpenditures.Find(id); db.AvgExpenditures.Remove(avgExpenditure); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using RetireHappy.DAL; using RetireHappy.Models; namespace RetireHappy.Controllers { public class ReportController : Controller { private RetireHappyContext db = new RetireHappyContext(); private ReportMapper reportMapper = new ReportMapper(); // GET: Report public ActionResult Index() { return View(reportMapper.ComputeAverage()); } // GET: Report public ActionResult Table() { return View(reportMapper.ComputeAverage()); } public ActionResult Test() { return View(reportMapper.ComputeAverage()); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace RetireHappy.Models { public class Report { public int cRID { get; set; } public int year { get; set; } public DateTime latestModDate { get; set; } public float male { get; set; } public float female { get; set; } public float inc_below_1000 { get; set; } public float inc_1001_2000 { get; set; } public float inc_2001_3000 { get; set; } public float inc_3001_4000 { get; set; } public float inc_4001_5000 { get; set; } public float inc_5001_6000 { get; set; } public float inc_above_6000 { get; set; } public float ageRange_below_25 { get; set; } public float ageRange_25_34 { get; set; } public float ageRange_35_44 { get; set; } public float ageRange_45_54 { get; set; } public float ageRange_55_64 { get; set; } public Report calculate(Object T, Object U) { Report report = new Report(); //Assuming calculation logic is implemented here report.year = 2016; report.male = 1350; report.female = 1230; report.inc_below_1000 = 870; report.inc_1001_2000 = 1300; report.inc_2001_3000 = 2400; report.inc_3001_4000 = 3056; report.inc_4001_5000 = 4678; report.inc_5001_6000 = 5836; report.inc_above_6000 = 6903; report.ageRange_below_25 = 1600; report.ageRange_25_34 = 1833; report.ageRange_35_44 = 1735; report.ageRange_45_54 = 1246; report.ageRange_55_64 = 1405; return report; } } }<file_sep>using RetireHappy.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace RetireHappy.DAL { public class AvgExpenditureGateway : CommonGateway<AvgExpenditure> { public void deleteAll() { string query = "DELETE FROM AvgExpenditure"; db.Database.ExecuteSqlCommand(query); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using RetireHappy.Models; namespace RetireHappy.DAL { public class UserGateway : CommonGateway<UserProfile> { } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using RetireHappy.DAL; using RetireHappy.Models; namespace RetireHappy.Controllers { public class SavingsInfosController : Controller { private RetireHappyDBEntities db = new RetireHappyDBEntities(); private SavingInfosGateway savingInfosGateway = new SavingInfosGateway(); // GET: SavingsInfos public ActionResult Index() { return View(db.SavingsInfoes.ToList()); } // method to receive and compute savingsinfo // GET: SavingsInfos/computeSavginsInfo public ActionResult ComputeSavingsInfo() { double avgMonExpenditure = (double)Session["avgMonExpenditure"]; double monIncome = (double)Session["monIncome"]; // assuming a fixed rate of 2.4% inflation rate double inflationRate = ((double)Session["inflationRate"] / 100) + 1; int currentAge = (int)Session["age"]; int expRetAge = (int)Session["expRetAge"]; int retDuration = (int)Session["retDuration"]; int limit = expRetAge + retDuration; double curSavingAmt = (double)Session["curSavingAmt"]; double desiredMonRetInc = (double)Session["desiredMonRetInc"]; SavingsInfo savingsInfo = new SavingsInfo(); //float pvAsOfRetAge = computeRiskLevel(expRetAge, currentAge, desiredMonRetInc, inflationRate, retDuration); // calculate PV as of current age //float pvAsOfCurAge = (float)(pvAsOfRetAge / Math.Pow((1 + 0.01), (expRetAge - currentAge))); double calcRetSavings = savingsInfo.calculate(expRetAge, currentAge, desiredMonRetInc, inflationRate, retDuration); // calculate monthly savings using PV as of current age //float calcRetSavings = pvAsOfCurAge / ((expRetAge - currentAge) * 12); // to calculate risk level using inflation adjusted current monthly savings double riskLevelDiff = savingsInfo.computeRiskLevel(calcRetSavings, curSavingAmt); //float riskLevelDiff = ((calcRetSavings - curSavingAmt) / curSavingAmt) * 100; if (riskLevelDiff <= 0) { savingsInfo.riskLevel = "Low Risk"; ViewBag.riskClass = "panel-green"; } else if (riskLevelDiff < 20) { savingsInfo.riskLevel = "Medium Risk"; ViewBag.riskClass = "panel-yellow"; } else { savingsInfo.riskLevel = "High Risk"; ViewBag.riskClass = "panel-red"; } savingsInfo.diffPercent = Math.Round(riskLevelDiff, 2); savingsInfo.calcRetSavings = Math.Round(calcRetSavings, 2); savingsInfo.Id = (int)Session["Id"]; savingsInfo.expPercent = Math.Round( (avgMonExpenditure / monIncome) * 100, 2); savingInfosGateway.Insert(savingsInfo); return View(savingsInfo); } // GET: SavingsInfos/calculatorStep4/5 public ActionResult calculatorStep4(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } SavingsInfo savingsInfo = savingInfosGateway.SelectById(id); if (savingsInfo == null) { return HttpNotFound(); } return View(savingsInfo); } // GET: SavingsInfos/Details/5 public ActionResult Details(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } SavingsInfo savingsInfo = db.SavingsInfoes.Find(id); if (savingsInfo == null) { return HttpNotFound(); } return View(savingsInfo); } // GET: SavingsInfos/Create public ActionResult Create() { return View(); } // POST: SavingsInfos/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "uId,calcRetSavings,savePercent,riskLevel,expPercent,diffPercent")] SavingsInfo savingsInfo) { if (ModelState.IsValid) { db.SavingsInfoes.Add(savingsInfo); db.SaveChanges(); return RedirectToAction("Index"); } return View(savingsInfo); } // GET: SavingsInfos/Edit/5 public ActionResult Edit(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } SavingsInfo savingsInfo = db.SavingsInfoes.Find( Convert.ToInt32(id) ); if (savingsInfo == null) { return HttpNotFound(); } return View(savingsInfo); } // POST: SavingsInfos/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "uId,calcRetSavings,savePercent,riskLevel,expPercent,diffPercent")] SavingsInfo savingsInfo) { if (ModelState.IsValid) { db.Entry(savingsInfo).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(savingsInfo); } // GET: SavingsInfos/Delete/5 public ActionResult Delete(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } SavingsInfo savingsInfo = db.SavingsInfoes.Find(id); if (savingsInfo == null) { return HttpNotFound(); } return View(savingsInfo); } // POST: SavingsInfos/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(string id) { SavingsInfo savingsInfo = db.SavingsInfoes.Find(id); db.SavingsInfoes.Remove(savingsInfo); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using RetireHappy.DAL; using RetireHappy.Models; namespace RetireHappy.Controllers { public class UsersController : Controller { private RetireHappyDBEntities db = new RetireHappyDBEntities(); private UserGateway userGateway = new UserGateway(); // GET: Users public ActionResult Index() { return View(userGateway.SelectAll()); } // GET: Users/selectGender public ActionResult selectGender() { return View(); } // GET: Users/calculatorStep1 public ActionResult CalculatorStep1() { return View(); } // POST: Users/calculatorStep1 [HttpPost] [ValidateAntiForgeryToken] public ActionResult CalculatorStep1([Bind(Include = "gender")] UserProfile userProfile) { //If no radio button is selected if (userProfile.gender == null) { //Return the same page with error massage return View(); } else { Session["gender"] = userProfile.gender; } return RedirectToAction("CalculatorStep2"); } // GET: Users/CalculatorStep2 public ActionResult CalculatorStep2() { return View(); } // POST: Users/CalculatorStep2 [HttpPost] [ValidateAntiForgeryToken] public ActionResult CalculatorStep2([Bind(Include = "age,monIncome,curSavingAmt,avgMonExpenditure,inflationRate")] UserProfile userProfile) { Session["age"] = userProfile.age; Session["monIncome"] = userProfile.monIncome; Session["curSavingAmt"] = userProfile.curSavingAmt; Session["avgMonExpenditure"] = userProfile.avgMonExpenditure; Session["inflationRate"] = userProfile.inflationRate; return RedirectToAction("CalculatorStep3"); } // GET: Users/CalculatorStep3 public ActionResult CalculatorStep3() { return View(); } // POST: Users/CalculatorStep3 [HttpPost] [ValidateAntiForgeryToken] public ActionResult CalculatorStep3([Bind(Include = "Id, desiredMonRetInc,expRetAge,retDuration")] UserProfile userProfile) { //last step of user inputs, insert into gateway Session["desiredMonRetInc"] = userProfile.desiredMonRetInc; Session["expRetAge"] = userProfile.expRetAge; Session["retDuration"] = userProfile.retDuration; // To fix entity framework bug of being unable to cater to multiple temp instance of userProfile model UserProfile newUserProfile = new UserProfile(); newUserProfile.desiredMonRetInc = userProfile.desiredMonRetInc; newUserProfile.expRetAge = userProfile.expRetAge; newUserProfile.retDuration = userProfile.retDuration; newUserProfile.age = (int)Session["age"]; newUserProfile.gender = (string)Session["gender"]; newUserProfile.monIncome = (double)Session["monIncome"]; newUserProfile.avgMonExpenditure = (double)Session["avgMonExpenditure"]; newUserProfile.curSavingAmt = (double)Session["curSavingAmt"]; newUserProfile.desiredMonRetInc = (double)Session["desiredMonRetInc"]; newUserProfile.inflationRate = (double)Session["inflationRate"]; newUserProfile.timestamp = DateTime.Now; userGateway.Insert(newUserProfile); Session["Id"] = newUserProfile.Id; //return RedirectToAction("Index"); return RedirectToAction("ComputeSavingsInfo", "SavingsInfos"); } // GET: Users/Details/5 public ActionResult Details(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } UserProfile userProfile = db.UserProfiles.Find(id); if (userProfile == null) { return HttpNotFound(); } return View(userProfile); } // GET: Users/Create public ActionResult Create() { return View(); } // POST: Users/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "uId,age,gender,expRetAge,retDuration,monIncome,avgMonExpenditure,calcRetSavings,curSavingAmt,timestamp,password,userName")] UserProfile userProfile) { if (ModelState.IsValid) { db.UserProfiles.Add(userProfile); db.SaveChanges(); return RedirectToAction("Index"); } return View(userProfile); } // GET: Users/Edit/5 public ActionResult Edit(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } UserProfile userProfiles = db.UserProfiles.Find(id); if (userProfiles == null) { return HttpNotFound(); } return View(userProfiles); } // POST: Users/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "uId,age,gender,expRetAge,retDuration,monIncome,avgMonExpenditure,calcRetSavings,curSavingAmt,timestamp,password,<PASSWORD>")] User user) { if (ModelState.IsValid) { db.Entry(user).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(user); } // GET: Users/Delete/5 public ActionResult Delete(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } UserProfile userProfile = db.UserProfiles.Find(id); if (userProfile == null) { return HttpNotFound(); } return View(userProfile); } // POST: Users/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(string id) { UserProfile userProfile = db.UserProfiles.Find(id); db.UserProfiles.Remove(userProfile); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace RetireHappy.Models { public class User { public int Id { get; set; } [Display(Name = "What is your age?")] [Range(12, 99)] public int age { get; set; } [Display(Name = "What is your gender?")] [Required(ErrorMessage = "Please select your gender")] public string gender { get; set; } [Display(Name = "Your Expected Retirement Age")] [Range(18, 99)] public int expRetAge { get; set; } [Display(Name = "Retirement Duration(years)")] [Range(1, 99)] public int retDuration { get; set; } [Display(Name = "Your Monthly Take Home Pay")] [Range(0d, (double)decimal.MaxValue, ErrorMessage = "Amount must be greater than zero.")] public float monIncome { get; set; } [Display(Name = "Monthly Expenditure")] [Range(0d, (double)decimal.MaxValue, ErrorMessage = "Amount must be greater than zero.")] public float avgMonExpenditure { get; set; } [Display(Name = "Current Monthly Savings Amount")] [Range(0d, (double)decimal.MaxValue, ErrorMessage = "Amount must be greater than zero.")] public float curSavingAmt { get; set; } [Display(Name = "Desired Monthly Retirement Income")] [Range(0d, (double)decimal.MaxValue, ErrorMessage = "Amount must be greater than zero.")] public float desiredMonRetInc { get; set; } [Display(Name = "Departure Date")] [DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yy}", ApplyFormatInEditMode = true)] public DateTime timestamp { get; set; } [Display(Name = "Inflation Rate")] public float inflationRate { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using RetireHappy.Models; using System.Data.Entity; namespace RetireHappy.DAL { public class RetireHappyContext : DbContext { public RetireHappyContext() : base("RetireHappyDB") { } //public DbSet<AvgExpenditure> AvgExpenditures{get;set;} //public DbSet<Expenditure> Expenditures { get; set; } //public DbSet<Report> Reports { get; set; } public DbSet<SavingsInfo> SavingsInfos { get; set; } public DbSet<User> User { get; set; } //public DbSet<Admin> Admins { get; set; } } }
f62991386256a8e1b1890270cdc764ab30433462
[ "C#" ]
10
C#
XingYi/RetireHappy
0a56cea7ddf123e11bdc6dd27e62be67e0429373
32fa0a7e43839b3cdd930c3ff04f61570708d87b
refs/heads/master
<file_sep>## Put comments here that give an overall description of what your ## functions do ## Function makeCacheMatrix creates a special list containing four functions ## These functions carry out the following: ## 1. set the matrix ## 2. get the matrix ## 3. set the matrix inverse ## 4. get the matrix inverse makeCacheMatrix <- function(x = matrix()) { inv <- NULL # The set function sets the matrix. ## Initially the inverse matrix is NULL as this has not been cached yet set <- function(y) { x <<- y inv <<- NULL } # The get function retrieves the matrix get <- function() x # This setinverse function calculates the matrix inverse and assigns it to 'inv' # This carries out the caching of the inverse setinverse <- function(solve) inv <<- solve # getinverse retrives the cached matrix inverse getinverse <- function() inv # The returned list of all 4 functions list(set = set, get = get, setinverse = setinverse, getinverse = getinverse) } ## cacheSolve takes as its argument a list of functions created by the makeCacheMatrix function above ## It returns the matrix that is the inverse of 'x' ## If the inverse is already cached, the function retrieves this cached inverse and returns it ## If not, then the inverse is calculated using solve(), cached and returned cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' inv <<- x$getinverse() # This if statement checks whether 'inv' contains non-NULL (i.e. what should be the cached inverse) if(!is.null(inv)) { message("getting cached data") # A non-NULL inv means the inverse is already cached, so no call to solve() is made # The cached 'inv' is returned return(inv) } # If 'inv' is NULL, then these lines retrive the matrix from the list, call solve() on this matrix, # caches the inverse in 'inv' then returns 'inv' data <- x$get() inv <- solve(data, ...) x$setinverse(inv) inv }
29d0f6ef6838c90e435b5d3c4b90644c7bc2e46b
[ "R" ]
1
R
dominictabeta/ProgrammingAssignment2
111686e0c51beba53727b12b3f89d48af3add651
90dcca5880ba605e8c3475c3422b3d4b9b4c00e9
refs/heads/master
<file_sep>from django.contrib import admin # Register your models here. from .models import Guest @admin.register(Guest) class GuestAdmin(admin.ModelAdmin): list_display = ('name', 'email', 'rsvp', 'additions', 'message')<file_sep>from django.db import models # Create your models here. class Guest(models.Model): name = models.CharField(max_length=255) email = models.CharField(max_length=255) rsvp = models.BooleanField(default=False) additions = models.IntegerField(null=True, blank=True) message = models.CharField(max_length=1020) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name <file_sep># Generated by Django 2.0.4 on 2018-05-27 15:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('rsvp', '0001_initial'), ] operations = [ migrations.AddField( model_name='guest', name='rsvp', field=models.BooleanField(default=False), ), ] <file_sep>from django.shortcuts import render from django.http import HttpResponse from rsvp.models import Guest from django.conf import settings import os # Create your views here. def index(request): guest = Guest.objects.all() if request.method == 'GET': return render(request, 'index.html', { 'guest': guest }) #Post Request Data guest = Guest( name=request.POST['name'], email=request.POST['email'], rsvp=request.POST['rsvp'], additions=request.POST['additions'], message=request.POST['message'], ) return render(request, 'rsvp.html') def process(request): required_fields = ['rsvp', 'name', 'email'] print(request.POST) for field in required_fields: if field not in request.POST: return HttpResponse('Error missing field.') #Post Request Data rsvp_val=True if request.POST['rsvp'] == 'True': rsvp_val=True elif request.POST['rsvp'] == 'False': rsvp_val=False guest = Guest( name=request.POST['name'], email=request.POST['email'], rsvp=rsvp_val, additions=request.POST['additions'], message=request.POST['message'], ) guest.save() print("ID %s:" % guest.id) return render(request, 'process.html') def jp(request): return render(request, 'index_jp.html') def nav(request): return render(request, 'nav.html') def nav_jp(request): return render(request, 'nav_jp.html') def guests(request): guests = Guest.objects.all() return render(request, 'guests.html', {'people' : guests}) def guests_jp(request): guests = Guest.objects.all() return render(request, 'guests_jp.html', {'people' : guests}) def album(request): photo_urls = [] photo_file_path = os.path.join(settings.PROJECT_DIR, 'photos.txt') with open(photo_file_path) as fp: for line in fp: line = line.strip() # Remove whitespace if line: photo_pair = (line + 'm.jpg', line + '.jpg') photo_urls.append(photo_pair) return render(request, 'album.html', { 'photo_urls': photo_urls }) def album_jp(request): return render(request, 'album_jp.html')
d66006442e8226fb130130103c4e0341a10b7d69
[ "Python" ]
4
Python
jwinf843/rsvp_website
0e5ca0cf647a3b5d8591268a4667e190d9723707
91bd3c2f63fea44af7224c8eb09be1abaefb53d6
refs/heads/main
<repo_name>Egor-04/Scientist-Engineer<file_sep>/Scientist Engineer/Assets/Scripts/Player/PlayerStates.cs using UnityEngine; public class PlayerStates : MonoBehaviour { public bool CanZoom = true; public bool CanMove = true; public bool CanJump = true; public bool CanHold = true; public bool CanLook = true; public static PlayerStates PlayerStatesScript; private void Start() { PlayerStatesScript = GetComponent<PlayerStates>(); } } <file_sep>/Scientist Engineer/Assets/Scripts/UI/PanelSwitcher.cs using UnityEngine; using System; public class PanelSwitcher : MonoBehaviour { [Header("Button ID")] [SerializeField] private int _buttonID; [Header("Panel for Activation")] [SerializeField] private GameObject _currentPanel; [Header("All Panels")] [SerializeField] private UIPanel[] _allUIPanels; [Serializable] public class UIPanel { public int PanelID; public GameObject Panel; } public void Switch() { if (!_currentPanel.activeSelf) { _currentPanel.SetActive(true); for (int i = 0; i < _allUIPanels.Length; i++) { if (_allUIPanels[i].PanelID != _buttonID) { _allUIPanels[i].Panel.SetActive(false); } } } } } <file_sep>/Scientist Engineer/Assets/Scripts/Inventory/SetCellID.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class SetCellID : MonoBehaviour { [Header("Content")] [SerializeField] private Transform _cellContent; [Header("Cells for Touch")] [SerializeField] private List<TouchCell> _touchCellList; private void Start() { _cellContent = GetComponent<Transform>(); for (int i = 0; i < _cellContent.childCount; i++) { _touchCellList.Add(new TouchCell()); TouchCell touchCell = _cellContent.GetChild(i).GetComponent<TouchCell>(); _touchCellList[i] = touchCell; touchCell.CellID = i; } } } <file_sep>/Scientist Engineer/Assets/Scripts/Camera Hold Point/Holder.cs using UnityEngine; public class Holder : MonoBehaviour { [Header("Scroll Holder Point Sensitivity")] [SerializeField] private float _sensitivity = 10f; [Header("Ray Length")] [SerializeField] private float _rayLength; [Header("Holder Point")] [SerializeField] private Transform _holderPoint; [Header("Holder Object Prefab")] [SerializeField] private GameObject _holderPrefab; [Header("Buttons")] [SerializeField] private KeyCode _holdButton = KeyCode.Mouse0; private GameObject _currentHolderPrefab; private CharacterJoint _characterJoint; private void Update() { Debug.DrawRay(transform.position, transform.forward * _rayLength, Color.red); if (PlayerStates.PlayerStatesScript.CanHold) { InstantiateHolder(); } } private void InstantiateHolder() { if (Input.GetKeyDown(_holdButton)) { Ray ray = new Ray(transform.position, transform.forward); RaycastHit hit; if (Physics.Raycast(ray, out hit, _rayLength)) { if (hit.collider) { if (hit.collider.GetComponent<Rigidbody>()) { Vector3 holderPoint = hit.point; GameObject draggedObject = hit.collider.gameObject; GameObject instantiatedHolderPrefab = Instantiate(_holderPrefab, holderPoint, Quaternion.identity); _currentHolderPrefab = instantiatedHolderPrefab; _characterJoint = instantiatedHolderPrefab.GetComponent<CharacterJoint>(); CharacterJoint characterJoint = instantiatedHolderPrefab.GetComponent<CharacterJoint>(); characterJoint.connectedBody = draggedObject.GetComponent<Rigidbody>(); } } } } else if (Input.GetKey(_holdButton)) { DragObject(); } else if (Input.GetKeyUp(_holdButton)) { if (_characterJoint) { _characterJoint.connectedBody.velocity = new Vector3(0f, 0f, 0f); } Destroy(_currentHolderPrefab); } } private void DragObject() { if (_currentHolderPrefab) { _currentHolderPrefab.transform.position = _holderPoint.position; HolderPointScrolling(); } } private void HolderPointScrolling() { float mouseWheelValue = Input.GetAxis("Mouse ScrollWheel"); _holderPoint.position += _sensitivity * mouseWheelValue * Time.deltaTime * _holderPoint.localPosition.z * transform.forward; } }<file_sep>/Scientist Engineer/Assets/Scripts/Player/MouseLook.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class MouseLook : MonoBehaviour { [Header("Sensitivity")] public float Sensitivity; public Camera PlayerCamera; [SerializeField] private Transform _body; [Header("Zoom")] [SerializeField] private float _zoomSpeed = 0.07f; [SerializeField] private float _zoomValue = 30; [SerializeField] private KeyCode _zoomButton = KeyCode.Mouse1; [Header("Clamp Rotation")] [SerializeField] private float _minRotation = -90; [SerializeField] private float _maxRotation = 90; private Vector3 _clampVerticalRotation; private float _cachedZoom; private void Start() { PlayerCamera = GetComponent<Camera>(); _cachedZoom = PlayerCamera.fieldOfView; } private void Update() { Zoom(); MouseRotation(); } private void MouseRotation() { if (PlayerStates.PlayerStatesScript.CanLook) { //Mouse Rotation float mouseHorizontal = Input.GetAxis("Mouse X") * Sensitivity; float mouseVertical = Input.GetAxis("Mouse Y") * -Sensitivity; _clampVerticalRotation.x += mouseVertical; _clampVerticalRotation.x = Mathf.Clamp(_clampVerticalRotation.x, _minRotation, _maxRotation); PlayerCamera.transform.Rotate(_clampVerticalRotation.x, 0f, 0f); PlayerCamera.transform.localEulerAngles = _clampVerticalRotation; //Body Rotation _body.Rotate(0f, mouseHorizontal, 0f); } } private void Zoom() { if (PlayerStates.PlayerStatesScript.CanZoom) { if (Input.GetKey(_zoomButton)) { PlayerCamera.fieldOfView = Mathf.Lerp(PlayerCamera.fieldOfView, _zoomValue, _zoomSpeed); } else { PlayerCamera.fieldOfView = Mathf.Lerp(PlayerCamera.fieldOfView, _cachedZoom, _zoomSpeed); } } } } <file_sep>/Scientist Engineer/Assets/Scripts/All Systems/CreatorMode.cs using UnityEngine; public class CreatorMode : MonoBehaviour { [Header("Items Panel")] [SerializeField] private GameObject _itemsPanel; [Header("Buttons")] [SerializeField] private KeyCode _buttonOpenPanelItems = KeyCode.I; private void Start() { } private void Update() { OpenItemsPanel(); } private void OpenItemsPanel() { if (Input.GetKeyDown(_buttonOpenPanelItems)) { if (_itemsPanel.activeSelf) { _itemsPanel.SetActive(false); Time.timeScale = 1f; Cursor.visible = false; Cursor.lockState = CursorLockMode.Locked; PlayerStates.PlayerStatesScript.CanLook = true; } else { _itemsPanel.SetActive(true); Time.timeScale = 0f; Cursor.visible = true; Cursor.lockState = CursorLockMode.None; PlayerStates.PlayerStatesScript.CanLook = false; } } } } <file_sep>/Scientist Engineer/Assets/Scripts/Inventory/Item.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Item : MonoBehaviour { [Header("Basic Information")] public int ID; public Sprite Icon; public string ItemName; [TextArea] public string Description; [Header("Additional Info")] public bool isAmmo; public bool isWeapon; } <file_sep>/Scientist Engineer/Assets/Scripts/Inventory/Inventory.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Inventory : MonoBehaviour { [Header("Camera")] [SerializeField] private Transform _cameraPosition; [Header("Ray Length")] [SerializeField] private float _rayLength; [Header("UI Inventory")] [SerializeField] private Transform _content; [Header("Inventory List")] public List<Item> InventoryList; [Header("All Items")] public Item[] AllItems; private void Start() { for (int i = 0; i < _content.childCount; i++) { InventoryList.Add(new Item()); } } private void Update() { TakeItem(); } private void TakeItem() { Ray ray = new Ray(_cameraPosition.position, transform.forward); RaycastHit hit; if (Physics.Raycast(ray, out hit, _rayLength)) { if (hit.collider.GetComponent<Item>()) { Item currentItem = hit.collider.GetComponent<Item>(); } } } private void DefineItem(Item currentItem) { for (int i = 0; i < AllItems.Length; i++) { if (currentItem.ID == AllItems[i].ID) { } } } } <file_sep>/Scientist Engineer/Assets/Scripts/Inventory/TouchCell.cs using System.Collections; using System.Collections.Generic; using UnityEngine.EventSystems; using UnityEngine; public class TouchCell : MonoBehaviour, IPointerDownHandler { [Header("Cell ID")] public int CellID; public void OnPointerDown(PointerEventData eventData) { } } <file_sep>/Scientist Engineer/Assets/Scripts/Player/Player.cs using UnityEngine; public class Player : MonoBehaviour { [Header("Camera")] [SerializeField] private Transform _cameraTransform; [Header("Values")] public float PlayerHP; [Header("Speed")] [SerializeField] private float _speed = 80f; [SerializeField] private float _runSpeed = 100f; [Header("Crouch && Crawl Speed")] [SerializeField] private float _crawlSpeed = 30f; [SerializeField] private float _crouchSpeed = 50f; [Header("Height,Crouch && Crawl Height")] [SerializeField] private float _height = 2f; [SerializeField] private float _crouchHeight = 1f; [SerializeField] private float _crawlHeight = 0.5f; [SerializeField] private float _cameraHeight = 80f; [SerializeField] private float _cameraCrouchHeight = 70f; [SerializeField] private float _cameraCrawlHeight = 60f; [Header("Jump Force")] [SerializeField] private float _jumpForce = 30f; [Header("Gravity Scale")] [SerializeField] private float _gravityScale = -200f; [Header("Controller")] [SerializeField] private CharacterController _characterController; [Header("Collider")] [SerializeField] private CapsuleCollider _playerCollider; [Header("Jump")] [SerializeField] float _radius; [SerializeField] Transform _sphereCheckTransform; [SerializeField] LayerMask _layerMask; [Header("Interpolation")] [SerializeField] private float _interpolationSpeed = 0.7f; [Header("Buttons")] public KeyCode ButtonRun = KeyCode.LeftShift; public KeyCode ButtonJump = KeyCode.Space; public KeyCode CrouchButton = KeyCode.C; public KeyCode CrawlButton = KeyCode.LeftControl; [Header("Gizmos Color")] [SerializeField] private float _red, _green, _blue; private Vector3 _moveDirection; private Vector3 _velocity; private float _chachedSpeed; private bool _isGrounded; private bool _isCrouchEnable; private bool _isCrawlEnable; private void Start() { _chachedSpeed = _speed; _playerCollider = GetComponent<CapsuleCollider>(); _characterController = GetComponent<CharacterController>(); Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; Time.timeScale = 1f; } private void Update() { CheckGround(); SoftFall(); Jump(); Movement(); CrawlPose(); CrouchPose(); Run(); //Gravity _velocity.y += _gravityScale * Time.deltaTime; _characterController.Move(_velocity * Time.deltaTime); } private void Run() { if (Input.GetKey(ButtonRun) && !_isCrouchEnable && !_isCrawlEnable) { _speed = Mathf.Lerp(_speed, _runSpeed, _interpolationSpeed); } else if (!Input.GetKeyDown(ButtonRun) && !_isCrouchEnable && !_isCrawlEnable) { _speed = _chachedSpeed; } } private void Movement() { //Movement float vertical = Input.GetAxis("Vertical"); float horizontal = Input.GetAxis("Horizontal"); _moveDirection = transform.forward * vertical + transform.right * horizontal; _characterController.Move(_moveDirection * _speed * Time.deltaTime); } private void CrouchPose() { if (Input.GetKeyDown(CrouchButton)) { if (!_isCrouchEnable) { _speed = _crouchSpeed; _playerCollider.height = _crouchHeight; _characterController.height = _crouchHeight; _cameraTransform.position = new Vector3(_cameraTransform.position.x, _cameraCrouchHeight, _cameraTransform.position.z); _isCrouchEnable = true; _isCrawlEnable = false; } else { _speed = _chachedSpeed; _playerCollider.height = _height; _characterController.height = _height; _cameraTransform.position = new Vector3(_cameraTransform.position.x, _cameraHeight, _cameraTransform.position.z); _isCrouchEnable = false; _isCrawlEnable = false; } } } private void CrawlPose() { if (Input.GetKeyDown(CrawlButton)) { if (!_isCrawlEnable) { _speed = _crawlSpeed; _playerCollider.height = _crawlHeight; _characterController.height = _crawlHeight; _cameraTransform.position = new Vector3(_cameraTransform.position.x, _cameraCrawlHeight, _cameraTransform.position.z); _isCrouchEnable = false; _isCrawlEnable = true; } else { _speed = _chachedSpeed; _playerCollider.height = _crouchHeight; _characterController.height = _crouchHeight; _cameraTransform.position = new Vector3(_cameraTransform.position.x, _cameraCrouchHeight, _cameraTransform.position.z); _isCrouchEnable = true; _isCrawlEnable = false; } } } private void Jump() { if (Input.GetKeyDown(ButtonJump) && !_isCrouchEnable && !_isCrawlEnable) { if (_isGrounded) { _velocity.y = Mathf.Sqrt(_jumpForce * -2 * _gravityScale); } } else if (Input.GetKeyDown(ButtonJump) && _isCrouchEnable) { _speed = _chachedSpeed; _playerCollider.height = _height; _characterController.height = _height; _cameraTransform.position = new Vector3(_cameraTransform.position.x, _cameraHeight, _cameraTransform.position.z); _isCrouchEnable = false; } else if (Input.GetKeyDown(ButtonJump) && _isCrawlEnable) { _speed = _chachedSpeed; _playerCollider.height = _crouchHeight; _characterController.height = _crouchHeight; _cameraTransform.position = new Vector3(_cameraTransform.position.x, _cameraCrouchHeight, _cameraTransform.position.z); _isCrawlEnable = false; _isCrouchEnable = true; } } private void SoftFall() { if (_isGrounded && _velocity.y < 0f) { _velocity.y = -20f; } } private void CheckGround() { _isGrounded = Physics.CheckSphere(_sphereCheckTransform.position, _radius, _layerMask); if (_isGrounded) { _isGrounded = true; } else { _isGrounded = false; } } private void OnDrawGizmos() { Gizmos.color = new Color(_red, _green, _blue); Gizmos.DrawWireSphere(_sphereCheckTransform.position, _radius); } }
b7088c2ee78132f224e6130945422cab589bcbbb
[ "C#" ]
10
C#
Egor-04/Scientist-Engineer
e7c7b7788e04fb61b112a1835a1132007da2a650
bb17845aee790012255aee8524ee0ad83cfe5c1c
refs/heads/master
<file_sep>package de.alex.jobsystem.jobplayer; import org.bukkit.entity.Player; import java.util.HashMap; public class JobPlayerManager { private final HashMap<Player, JobPlayer> playerJobPlayerHashMap = new HashMap<>(); public JobPlayer addGetOrGet(Player player) { if (!playerJobPlayerHashMap.containsKey(player)) { JobPlayer jobPlayer = new JobPlayer(JobEnum.NOJOB, player); playerJobPlayerHashMap.put(player, jobPlayer); return jobPlayer; } return playerJobPlayerHashMap.get(player); } public void removePlayer(Player player) { playerJobPlayerHashMap.remove(player); } } <file_sep>package de.alex.jobsystem.inventorys; import de.alex.jobsystem.jobplayer.JobEnum; import de.alex.jobsystem.jobplayer.JobPlayer; import de.alex.jobsystem.main.JobSystem; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.text.DateFormat; import java.util.Arrays; public class JobTreatInventory { public void openInventory(Player player) { Inventory inventory = Bukkit.createInventory(null, InventoryType.CHEST, "§bJob Coins Abholen!"); JobPlayer jobPlayer = JobSystem.getJobSystem().getJobPlayerManager().addGetOrGet(player); String lastRecieved = jobPlayer.getLastPickUp() == 0 ? "---" : "" + (DateFormat.getInstance().format(System.currentTimeMillis() - jobPlayer.getLastPickUp())); if (jobPlayer.getCurrentJobCoins() != 0) { ItemStack treatItemStack = new ItemStack(Material.GLOWSTONE_DUST, 1); ItemMeta treatItemMeta = treatItemStack.getItemMeta(); assert treatItemMeta != null; treatItemMeta.setDisplayName(String.format("%x §6Coins abholen!", jobPlayer.getCurrentJobCoins())); treatItemMeta.setLore(Arrays.asList("§7", String.format("§6Zu letzt abgeholt vor: %s", lastRecieved))); treatItemStack.setItemMeta(treatItemMeta); inventory.setItem(14, treatItemStack); } else if (jobPlayer.getJobEnum().equals(JobEnum.NOJOB)) { ItemStack noJobItem = new ItemStack(Material.GUNPOWDER, 1); ItemMeta noJobItemItemMeta = noJobItem.getItemMeta(); assert noJobItemItemMeta != null; noJobItemItemMeta.setDisplayName("§cDu hast keinen Job um Coins zu bekommen!"); noJobItemItemMeta.setLore(Arrays.asList("§7", String.format("§6Zu letzt abgeholt vor: %s", lastRecieved))); noJobItem.setItemMeta(noJobItemItemMeta); inventory.setItem(14, noJobItem); } else { ItemStack noCoinsItemStack = new ItemStack(Material.GUNPOWDER, 1); ItemMeta noCoinsItemStackItemMeta = noCoinsItemStack.getItemMeta(); assert noCoinsItemStackItemMeta != null; noCoinsItemStackItemMeta.setDisplayName("§cKeine Coins erarbeitet!!"); noCoinsItemStackItemMeta.setLore(Arrays.asList("§7", String.format("§6Zu letzt abgeholt vor: %s", lastRecieved))); noCoinsItemStack.setItemMeta(noCoinsItemStackItemMeta); inventory.setItem(14, noCoinsItemStack); } } } <file_sep># JobSystem <a href="https://www.codefactor.io/repository/github/goldengamerlp/jobsystem"><img src="https://www.codefactor.io/repository/github/goldengamerlp/jobsystem/badge" alt="CodeFactor" /></a> <file_sep>package de.alex.jobsystem.listener; import de.alex.jobsystem.main.JobSystem; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; public class PlayerQuitEvent implements Listener { @EventHandler public void onPlayerQuitEvent(org.bukkit.event.player.PlayerQuitEvent event) { JobSystem.getJobSystem().getJobPlayerManager().removePlayer(event.getPlayer()); } } <file_sep>package de.alex.jobsystem.jobplayer; public enum JobEnum { FISHERMAN("Fischer", 5), MINER("Minenarbeiter", 10), NOJOB("Kein Job", 0); private final String jobName; private final int coinsForATask; JobEnum(String jobName, int i) { this.coinsForATask = i; this.jobName = jobName; } public int getCoinsForATask() { return coinsForATask; } public String getJobName() { return jobName; } }
f52951605eac35e57003aa4c971c8a5cbd77ac89
[ "Markdown", "Java" ]
5
Java
GoldenGamerLP/JobSystem
a5990baf710cfed3aa5abb5f10f871dd65c6d264
c6ae46df09c3c05f7dcef16943b815542ef8f35c
refs/heads/master
<repo_name>luben-gonsalves/transporter-ui-demo<file_sep>/src/components/ProductFeatures/index.js import React from "react"; import { SpaceBetween } from "../CommonComponents"; import { FeatureCard } from "./style"; const ProductFeatures = () => { const features = [ "Air Express Shipping", "Sea and Air Cargo Shipping", "Full-truckload Freight", ]; return ( <div style={{ margin: "20px 0px" }}> <h3 style={{ marginBottom: "40px" }}>Product Features</h3> <SpaceBetween> {features.map((f, i) => ( <FeatureCard key={i}> <h4>{f}</h4> <p>On-demand Delivery</p> <p>Same-day/Next-day Delivery</p> <p>Time-defined/Slot-based Delivery</p> <p>Returns Management</p> </FeatureCard> ))} <iframe width="600" height="300" title="dummyVideo" src="https://www.youtube.com/embed/tEV5sXt6pV8" ></iframe> </SpaceBetween> </div> ); }; export default ProductFeatures; <file_sep>/src/components/ProductFeatures/style.js import styled from "styled-components"; import { Card } from "antd"; export const FeatureCard = styled(Card)` background-color: #edf0f9; border-radius: 12px; `; <file_sep>/src/components/ContactUs/index.js import React from "react"; import { Col, Image, Row } from "antd"; import { FacebookFilled, TwitterSquareFilled } from "@ant-design/icons"; const ContactUs = () => { return ( <div style={{ margin: "20px 0px 40px 0px" }}> <h3>Contact Us</h3> <Row gutter={[16, 16]} justify="center" style={{ marginTop: "20px" }}> <Col xs={24} md={12} xl={10} lg={10}> <div id="address"> <h4>Address</h4> <p>117 College View,Belleville IL Illinois</p> </div> <div id="email"> <h4>Email</h4> <p><EMAIL></p> </div> <div id="phone"> <h4>Phone</h4> <p>708-600-4460</p> </div> <div id="follow"> <h4>Follow us on</h4> <FacebookFilled style={{ fontSize: "30px", marginRight: "10px" }} /> <TwitterSquareFilled style={{ fontSize: "30px" }} /> </div> </Col> <Col xs={24} md={12} xl={10} lg={10}> <Image height={250} src="https://miro.medium.com/max/4064/1*qYUvh-EtES8dtgKiBRiLsA.png" /> </Col> </Row> </div> ); }; export default ContactUs; <file_sep>/src/components/Clients/index.js import { Col, Row } from "antd"; import React from "react"; import { ClientCard } from "./style"; const Clients = () => { const clients = [ "<NAME>", "Slark", "Nevermore", "<NAME>", "Fickrr", "<NAME>", ]; return ( <div style={{ margin: "20px 0px" }}> <h3>Clientele</h3> <Row gutter={[16, 16]} justify="center" style={{ marginTop: "20px" }}> {clients.map((c, i) => ( <Col xs={24} md={12} xl={4} lg={4} key={i}> <ClientCard>{c}</ClientCard> </Col> ))} </Row> </div> ); }; export default Clients;
ebab31e0e99c09c5b6f7f7a7443fda203f1f1ee4
[ "JavaScript" ]
4
JavaScript
luben-gonsalves/transporter-ui-demo
3f09baf848294076a11abc432382c953981163b0
5272a0bd8b4aa2a92bf74c7cebe0b979bf9917e1
refs/heads/master
<repo_name>iSklcndykid/PRJCT_ANGLR<file_sep>/src/models/customer.model.ts import { Request, Response, NextFunction } from 'express'; export class customer { _model: any; constructor(norm: any) { this.model = [{ CUST_ID: { type: Number, key: 'primary' }, First_Name: { type: String, maxlength: 24 }, Last_Name: { type: String, maxlength: 24 }, CUST_TYPE: { type: String, maxlength: 24 }, Last_Seen: { type: String, maxlength: 24 }, THEATER_ID: { type: Number, key: 'foreign', references: { table: 'theater', foreignKey: 'THEATER_ID' } }, user_id: { type: Number, key: 'foreign', references: { table: 'User', foreignKey: 'id' }, onDelete: 'cascade', onUpdate: 'cascade' }, }, 'A table to store Customer Info', [ { route: '/get-all-customer', method: 'POST', callback: this.getAllCustomers, requireToken: true, }, { route: '/get-customer-by-id/:CUST_ID', method: 'POST', callback: this.getCustomerById, requireToken: true, }, { route: '/create-customer', method: 'POST', callback: this.createCustomer, requireToken: true, }, { route: '/update-customer/id/:CUST_ID', method: 'PUT', callback: this.updateCustomer, requireToken: true, }, { route: '/delete/id/:CUST_ID', method: 'DELETE', callback: this.deleteCustomer, requireToken: true, } ] ]; } getAllCustomers(model: any) { return async (req: Request, res: Response, next: NextFunction) => { req.body = { get: ["*"] } let customerCtrl = model.controller; let resp = await customerCtrl.controller.get(req, null, null); res.json({ message: 'Customer information retrieved successfully!', resp }); } } getCustomerById(model: any) { return async (req: Request, res: Response, next: NextFunction) => { req.body= { get: ["*"], where: { id: req.params.id } } let customerCtrl = model.controller; let resp = await customerCtrl.controller.get(req,null, null); res.json({ message: 'Customer ID found succssfully!', resp }); } } createCustomer(model: any) { return async (req: Request, res: Response, next: NextFunction) => { let customerCtrl = model.controller; let resp = await customerCtrl.controller.insert(req,null, null); res.json({ message: 'Customer created successfully!', resp }); } } updateCustomer(model: any) { return async (req: Request, res: Response, next: NextFunction) => { let customerCtrl = model.controller; let resp = await customerCtrl.controller.update(req,null, null); res.json({ message: 'Customer Info updated successfully!', resp }); } } deleteCustomer(model: any) { return async (req: Request, res: Response, next: NextFunction) => { let customerCtrl = model.controller; let resp = await customerCtrl.controller.remove(req,null, null); res.json({ message: 'Customer deleted successfully!', resp }); } } set model(model: any) { this._model = model; } get model() { return this._model; } }<file_sep>/dist/definitions/models/employee.model.d.ts import { Request, Response, NextFunction } from 'express'; export declare class employee { _model: any; constructor(norm: any); getAllEmployees(model: any): (req: Request, res: Response, next: NextFunction) => Promise<void>; getEmployeeById(model: any): (req: Request, res: Response, next: NextFunction) => Promise<void>; createEmployee(model: any): (req: Request, res: Response, next: NextFunction) => Promise<void>; updateEmployee(model: any): (req: Request, res: Response, next: NextFunction) => Promise<void>; deleteEmployee(model: any): (req: Request, res: Response, next: NextFunction) => Promise<void>; model: any; } <file_sep>/dist/definitions/models/concession.model.d.ts import { Request, Response, NextFunction } from 'express'; export declare class Concession { _model: any; constructor(norm: any); getAllSnacks(model: any): (req: Request, res: Response, next: NextFunction) => Promise<void>; getSnackById(model: any): (req: Request, res: Response, next: NextFunction) => Promise<void>; createSnack(model: any): (req: Request, res: Response, next: NextFunction) => Promise<void>; updateSnack(model: any): (req: Request, res: Response, next: NextFunction) => Promise<void>; deleteSnack(model: any): (req: Request, res: Response, next: NextFunction) => Promise<void>; model: any; } <file_sep>/src/models/theater.model.ts import {Request, Response, NextFunction} from 'express'; export class theater { _model: any; constructor(norm: any) { this.model = [{ THEATER_ID: { type: Number, key: 'primary' }, Location: { type: String, maxlength: 24 }, THEATER_TYPE: { type: String, maxlength: 24 }, Number_of_Rooms: { type: String, maxlength: 24 }, Number_of_Employees: { type: String, maxlength: 24 }, user_id: { type: Number, key: 'foreign', references: { table: 'User', foreignKey: 'id' }, onDelete: 'cascade', onUpdate: 'cascade' }, }, 'A table to store Theater Info', [ { route: '/get-all-theaters', method: 'POST', callback: this.getAllTheaters, requireToken: true, }, { route: '/get-theater-by-id/:THEATER_ID', method: 'POST', callback: this.getTheaterById, requireToken: true, }, { route: '/create-theater', method: 'POST', callback: this.createTheater, requireToken: true, }, { route: '/update-theater/id/:THEATER_ID', method: 'PUT', callback: this.updateTheater, requireToken: true, }, { route: '/delete/id/:THEATER_ID', method: 'DELETE', callback: this.deleteTheater, requireToken: true, } ] ]; } getAllTheaters(model: any) { return async (req: Request, res: Response, next: NextFunction) => { req.body= { get: ["*"] } let theaterCtrl = model.controller; let resp = await theaterCtrl.controller.get(req,null, null); res.json({ message: 'Car information retrieved successfully!', resp }); } } getTheaterById(model: any) { return async (req: Request, res: Response, next: NextFunction) => { req.body= { get: ["*"], where: { id: req.params.id } } let theaterCtrl = model.controller; let resp = await theaterCtrl.controller.get(req,null, null); res.json({ message: 'Theater ID found succssfully!', resp }); } } createTheater(model: any) { return async (req: Request, res: Response, next: NextFunction) => { let theaterCtrl = model.controller; let resp = await theaterCtrl.controller.insert(req,null, null); res.json({ message: 'Theater created successfully!', resp }); } } updateTheater(model: any) { return async (req: Request, res: Response, next: NextFunction) => { let theaterCtrl = model.controller; let resp = await theaterCtrl.controller.update(req,null, null); res.json({ message: 'Theater Info updated successfully!', resp }); } } deleteTheater(model: any) { return async (req: Request, res: Response, next: NextFunction) => { let theaterCtrl = model.controller; let resp = await theaterCtrl.controller.remove(req,null, null); res.json({ message: 'Theater deleted successfully!', resp }); } } set model(model: any) { this._model = model; } get model() { return this._model; } }<file_sep>/src/models/employee.model.ts import { Request, Response, NextFunction } from 'express'; export class employee { _model: any; constructor(norm: any) { this.model = [{ EMP_ID: { type: Number, key: 'primary' }, First_Name: { type: String, maxlength: 24 }, Last_Name: { type: String, maxlength: 24 }, EMP_TYPE: { type: String, maxlength: 24 }, THEATER_ID: { type: Number, key: 'foreign', references: { table: 'theater', foreignKey: 'THEATER_ID' } }, user_id: { type: Number, key: 'foreign', references: { table: 'User', foreignKey: 'id' }, onDelete: 'cascade', onUpdate: 'cascade' }, }, 'A table to store Employee Info', [ { route: '/get-all-employee', method: 'POST', callback: this.getAllEmployees, requireToken: true, }, { route: '/get-employee-by-id/:EMP_ID', method: 'POST', callback: this.getEmployeeById, requireToken: true, }, { route: '/create-employee', method: 'POST', callback: this.createEmployee, requireToken: true, }, { route: '/update-Employee/id/:EMP_ID', method: 'PUT', callback: this.updateEmployee, requireToken: true, }, { route: '/delete/id/:EMP_ID', method: 'DELETE', callback: this.deleteEmployee, requireToken: true, } ] ]; } getAllEmployees(model: any) { return async (req: Request, res: Response, next: NextFunction) => { req.body = { get: ["*"] } let employeeCtrl = model.controller; let resp = await employeeCtrl.controller.get(req, null, null); res.json({ message: 'Employee information retrieved successfully!', resp }); } } getEmployeeById(model: any) { return async (req: Request, res: Response, next: NextFunction) => { req.body= { get: ["*"], where: { id: req.params.id } } let employeeCtrl = model.controller; let resp = await employeeCtrl.controller.get(req,null, null); res.json({ message: 'Employee ID found succssfully!', resp }); } } createEmployee(model: any) { return async (req: Request, res: Response, next: NextFunction) => { let employeeCtrl = model.controller; let resp = await employeeCtrl.controller.insert(req,null, null); res.json({ message: 'Customer created successfully!', resp }); } } updateEmployee(model: any) { return async (req: Request, res: Response, next: NextFunction) => { let employeeCtrl = model.controller; let resp = await employeeCtrl.controller.update(req,null, null); res.json({ message: 'Employee Info updated successfully!', resp }); } } deleteEmployee(model: any) { return async (req: Request, res: Response, next: NextFunction) => { let employeeCtrl = model.controller; let resp = await employeeCtrl.controller.remove(req,null, null); res.json({ message: 'Employee deleted successfully!', resp }); } } set model(model: any) { this._model = model; } get model() { return this._model; } }<file_sep>/dist/definitions/models/index.d.ts export * from './theater.model'; export * from './room.model'; export * from './film.model'; export * from './employee.model'; export * from './customer.model'; export * from './concession.model'; <file_sep>/dist/definitions/models/room.model.d.ts import { Request, Response, NextFunction } from 'express'; export declare class room { _model: any; constructor(norm: any); getAllRooms(model: any): (req: Request, res: Response, next: NextFunction) => Promise<void>; getRoomById(model: any): (req: Request, res: Response, next: NextFunction) => Promise<void>; createRoom(model: any): (req: Request, res: Response, next: NextFunction) => Promise<void>; updateRoom(model: any): (req: Request, res: Response, next: NextFunction) => Promise<void>; deleteRoom(model: any): (req: Request, res: Response, next: NextFunction) => Promise<void>; model: any; } <file_sep>/dist/definitions/models/customer.model.d.ts import { Request, Response, NextFunction } from 'express'; export declare class customer { _model: any; constructor(norm: any); getAllCustomers(model: any): (req: Request, res: Response, next: NextFunction) => Promise<void>; getCustomerById(model: any): (req: Request, res: Response, next: NextFunction) => Promise<void>; createCustomer(model: any): (req: Request, res: Response, next: NextFunction) => Promise<void>; updateCustomer(model: any): (req: Request, res: Response, next: NextFunction) => Promise<void>; deleteCustomer(model: any): (req: Request, res: Response, next: NextFunction) => Promise<void>; model: any; } <file_sep>/src/models/film.model.ts import { Request, Response, NextFunction } from 'express'; export class film { _model: any; constructor(norm: any) { this.model = [{ FILM_ID: { type: Number, key: 'primary' }, Genre: { type: String, maxlength: 24 }, Length: { type: String, maxlength: 24 }, Title: { type: String, maxlength: 24 }, Publishing_Company: { type: String, maxlength: 24 }, THEATER_ID: { type: Number, key: 'foreign', references: { table: 'theater', foreignKey: 'THEATER_ID' } }, ROOM_ID: { type: Number, key: 'foreign', references: { table: 'room', foreignKey: 'ROOM_ID' } }, user_id: { type: Number, key: 'foreign', references: { table: 'User', foreignKey: 'id' }, onDelete: 'cascade', onUpdate: 'cascade' }, }, 'A table to store Film Info', [ { route: '/get-all-film', method: 'POST', callback: this.getAllFilms, requireToken: true, }, { route: '/get-film-by-id/:FILM_ID', method: 'POST', callback: this.getFilmById, requireToken: true, }, { route: '/create-film', method: 'POST', callback: this.createFilm, requireToken: true, }, { route: '/update-film/id/:FILM_ID', method: 'PUT', callback: this.updateFilm, requireToken: true, }, { route: '/delete/id/:FILM_ID', method: 'DELETE', callback: this.deleteFilm, requireToken: true, } ] ]; } getAllFilms(model: any) { return async (req: Request, res: Response, next: NextFunction) => { req.body = { get: ["*"] } let filmCtrl = model.controller; let resp = await filmCtrl.controller.get(req, null, null); res.json({ message: 'Film information retrieved successfully!', resp }); } } getFilmById(model: any) { return async (req: Request, res: Response, next: NextFunction) => { req.body= { get: ["*"], where: { id: req.params.id } } let filmCtrl = model.controller; let resp = await filmCtrl.controller.get(req,null, null); res.json({ message: 'Film ID found succssfully!', resp }); } } createFilm(model: any) { return async (req: Request, res: Response, next: NextFunction) => { let filmCtrl = model.controller; let resp = await filmCtrl.controller.insert(req,null, null); res.json({ message: 'Film created successfully!', resp }); } } updateFilm(model: any) { return async (req: Request, res: Response, next: NextFunction) => { let filmCtrl = model.controller; let resp = await filmCtrl.controller.update(req,null, null); res.json({ message: 'Film Info updated successfully!', resp }); } } deleteFilm(model: any) { return async (req: Request, res: Response, next: NextFunction) => { let filmCtrl = model.controller; let resp = await filmCtrl.controller.remove(req,null, null); res.json({ message: 'Film deleted successfully!', resp }); } } set model(model: any) { this._model = model; } get model() { return this._model; } }<file_sep>/src/models/concession.model.ts import { Request, Response, NextFunction } from 'express'; export class Concession { _model: any; constructor(norm: any) { this.model = [{ SNACK_ID: { type: Number, key: 'primary' }, SNACK_TYPE: { type: String, maxlength: 24 }, Price: { type: Number, maxlength: 24 }, THEATER_ID: { type: Number, key: 'foreign', references: { table: 'theater', foreignKey: 'THEATER_ID' } }, user_id: { type: Number, key: 'foreign', references: { table: 'User', foreignKey: 'id' }, onDelete: 'cascade', onUpdate: 'cascade' }, }, 'A table to store Customer Info', [ { route: '/get-all-snack', method: 'POST', callback: this.getAllSnacks, requireToken: true, }, { route: '/get-snack-by-id/:SNACK_ID', method: 'POST', callback: this.getSnackById, requireToken: true, }, { route: '/create-snack', method: 'POST', callback: this.createSnack, requireToken: true, }, { route: '/update-snack/id/:SNACK_ID', method: 'PUT', callback: this.updateSnack, requireToken: true, }, { route: '/delete/id/:SNACK_ID', method: 'DELETE', callback: this.deleteSnack, requireToken: true, } ] ]; } getAllSnacks(model: any) { return async (req: Request, res: Response, next: NextFunction) => { req.body = { get: ["*"] } let concessionCtrl = model.controller; let resp = await concessionCtrl.controller.get(req, null, null); res.json({ message: 'Customer information retrieved successfully!', resp }); } } getSnackById(model: any) { return async (req: Request, res: Response, next: NextFunction) => { req.body= { get: ["*"], where: { id: req.params.id } } let concessionCtrl = model.controller; let resp = await concessionCtrl.controller.get(req,null, null); res.json({ message: 'Customer ID found succssfully!', resp }); } } createSnack(model: any) { return async (req: Request, res: Response, next: NextFunction) => { let concessionCtrlCtrl = model.controller; let resp = await concessionCtrlCtrl.controller.insert(req,null, null); res.json({ message: 'Customer created successfully!', resp }); } } updateSnack(model: any) { return async (req: Request, res: Response, next: NextFunction) => { let concessionCtrl = model.controller; let resp = await concessionCtrl.controller.update(req,null, null); res.json({ message: 'Customer Info updated successfully!', resp }); } } deleteSnack(model: any) { return async (req: Request, res: Response, next: NextFunction) => { let concessionCtrl = model.controller; let resp = await concessionCtrl.controller.remove(req,null, null); res.json({ message: 'Customer deleted successfully!', resp }); } } set model(model: any) { this._model = model; } get model() { return this._model; } }<file_sep>/src/models/room.model.ts import { Request, Response, NextFunction } from 'express'; export class room { _model: any; constructor(norm: any) { this.model = [{ ROOM_ID: { type: Number, key: 'primary' }, Room_Number: { type: String, maxlength: 24 }, Room_Type: { type: String, maxlength: 24 }, THEATER_ID: { type: Number, key: 'foreign', references: { table: 'theater', foreignKey: 'THEATER_ID' } }, FILM_ID: { type: Number, key: 'foreign', references: { table: 'film', foreignKey: 'FILM_ID' } }, user_id: { type: Number, key: 'foreign', references: { table: 'User', foreignKey: 'id' }, onDelete: 'cascade', onUpdate: 'cascade' }, }, 'A table to store Room Info', [ { route: '/get-all-room', method: 'POST', callback: this.getAllRooms, requireToken: true, }, { route: '/get-room-by-id/:ROOM_ID', method: 'POST', callback: this.getRoomById, requireToken: true, }, { route: '/create-room', method: 'POST', callback: this.createRoom, requireToken: true, }, { route: '/update-Room/id/:ROOM_ID', method: 'PUT', callback: this.updateRoom, requireToken: true, }, { route: '/delete/id/:ROOM_ID', method: 'DELETE', callback: this.deleteRoom, requireToken: true, } ] ]; } getAllRooms(model: any) { return async (req: Request, res: Response, next: NextFunction) => { req.body = { get: ["*"] } let roomCtrl = model.controller; let resp = await roomCtrl.controller.get(req, null, null); res.json({ message: 'Room information retrieved successfully!', resp }); } } getRoomById(model: any) { return async (req: Request, res: Response, next: NextFunction) => { req.body= { get: ["*"], where: { id: req.params.id } } let roomCtrl = model.controller; let resp = await roomCtrl.controller.get(req,null, null); res.json({ message: 'Room ID found succssfully!', resp }); } } createRoom(model: any) { return async (req: Request, res: Response, next: NextFunction) => { let roomCtrl = model.controller; let resp = await roomCtrl.controller.insert(req,null, null); res.json({ message: 'Room created successfully!', resp }); } } updateRoom(model: any) { return async (req: Request, res: Response, next: NextFunction) => { let roomCtrl = model.controller; let resp = await roomCtrl.controller.update(req,null, null); res.json({ message: 'Room Info updated successfully!', resp }); } } deleteRoom(model: any) { return async (req: Request, res: Response, next: NextFunction) => { let roomCtrl = model.controller; let resp = await roomCtrl.controller.remove(req,null, null); res.json({ message: 'Room deleted successfully!', resp }); } } set model(model: any) { this._model = model; } get model() { return this._model; } }
f65913f1261b05c61f647470fff4f9e7c853b1b9
[ "TypeScript" ]
11
TypeScript
iSklcndykid/PRJCT_ANGLR
be040dd89e20f8ab4f42bfd3c1a10a7ee33d0feb
c9309ff2f6e595349fe2fcbfef72b4c3e10fb5d4
refs/heads/FinalRobot
<repo_name>BotDogs4645/InfiniteRecharge2020<file_sep>/src/main/java/frc/robot/commands/RunShooter.java /*----------------------------------------------------------------------------*/ /* Copyright (c) 2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.commands; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.subsystems.Shooter; public class RunShooter extends CommandBase { //Subsystem the command runs on private final Shooter motorSub; private final double target; public RunShooter(Shooter pMotorSub, double targetRPM) { motorSub = pMotorSub; target = targetRPM; // Use addRequirements() here to declare subsystem dependencies. addRequirements(motorSub); } // Called when the command is initially scheduled. @Override public void initialize() { /* This method only runs once: when this command is first scheduled Motor move method only needs to be called once, because when the motor speed is set, it will not change unless it is set again */ motorSub.startShooting(); } // Called every time the scheduler runs while the command is scheduled. @Override public void execute() { motorSub.move(target); } // Called once the command ends or is interrupted. @Override public void end(boolean interrupted) { motorSub.stopShooting(); } // Returns true when the command should end. @Override public boolean isFinished() { return false; } } <file_sep>/src/main/java/frc/robot/subsystems/PneumaticsSubsystem.java package frc.robot.subsystems; import edu.wpi.first.wpilibj.DoubleSolenoid; import edu.wpi.first.wpilibj.DoubleSolenoid.Value; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.RobotContainer; import frc.robot.commands.pneumatics.PneumaticsJoysticks; public class PneumaticsSubsystem extends SubsystemBase { //Creates solenoid object //hi its me, natarichard :) ٩(♡ε♡ )۶ Boolean onoroff = false; //if onoroff true that means controls are enabled //if onoroff false that means controls are disabled public PneumaticsSubsystem() { setDefaultCommand(new PneumaticsJoysticks(this)); } public void joystickpistons(){ double leftstickY = -1 * RobotContainer.Xbox.getRawAxis(1); double rightstickY = -1 * RobotContainer.Xbox.getRawAxis(3); DoubleSolenoid.Value leftstate; if (leftstickY > .9){ leftstate = Value.kForward; } else if (leftstickY < -.9){ leftstate = Value.kReverse; } else{ leftstate = Value.kOff; } DoubleSolenoid.Value rightstate; if (rightstickY > .9){ rightstate = Value.kForward; } else if (rightstickY < -.9){ rightstate = Value.kReverse; } else{ rightstate = Value.kOff; } SmartDashboard.putBoolean("Pneumatics Controls onoroff", onoroff); if (onoroff){ SmartDashboard.putString("Left Piston", leftstate + ""); SmartDashboard.putString("Right Piston", rightstate + ""); RobotContainer.LeftPiston.set(leftstate); RobotContainer.RightPiston.set(rightstate); } else{ leftpiston(Value.kOff); rightpiston(Value.kOff); } } public void toggle (){ if (!onoroff){ onoroff = true; } else { onoroff = false; } SmartDashboard.putBoolean("onorofoff", onoroff); } public void rightpiston (DoubleSolenoid.Value state){ SmartDashboard.putString("Right Piston", state + ""); RobotContainer.RightPiston.set(state); } public void leftpiston (DoubleSolenoid.Value state){ SmartDashboard.putString("Left Piston", state + ""); RobotContainer.LeftPiston.set(state); } @Override public void periodic() { // This method will be called once per scheduler run SmartDashboard.putNumber("Climb angle", TankDrive.ahrs.getPitch()); } } <file_sep>/src/main/java/frc/robot/subsystems/PressureSensor.java package frc.robot.subsystems; import edu.wpi.first.wpilibj.AnalogInput; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.commands.GetPressure; public class PressureSensor extends SubsystemBase { //Creates solenoid object //hi its me, natarichard :) ٩(♡ε♡ )۶ public PressureSensor() { setDefaultCommand(new GetPressure(this)); } AnalogInput pressureanalog = new AnalogInput(3); public void getpressure(){ double voltage = pressureanalog.getVoltage(); double pressure = (250 * (voltage/5)) - 25; SmartDashboard.putNumber("Analog Pressure", pressure); } } <file_sep>/src/main/java/frc/robot/commands/Align.java /*----------------------------------------------------------------------------*/ /* Copyright (c) 2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.commands; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.subsystems.Limelight; import frc.robot.subsystems.TankDrive; public class Align extends CommandBase { public static Limelight limelightsubsytem; public static TankDrive tankdrivesubsystem; public Align(Limelight sub,TankDrive subtwo) { // Use requires() here to declare subsystem dependencies // eg. requires(chassis); limelightsubsytem = sub; tankdrivesubsystem = subtwo; addRequirements(limelightsubsytem); addRequirements(tankdrivesubsystem); } // Called just before this Command runs the first time @Override public void initialize() { } // Called repeatedly when this Command is scheduled to run @Override public void execute() { tankdrivesubsystem.limelightAlign(); /* double offset = limelightsubsytem.getXOffset(); if (offset < -1.5){ tankdrivesubsystem.limelightAlign(); //tankdrivesubsytem.turn(false); } else if(offset > 1.5){ tankdrivesubsystem.limelightAlign(); //tankdrivesubsytem.turn(true); } else { tankdrivesubsystem.stop(); //return true; } */ } // Make this return true when this Command no longer needs to run execute() @Override public boolean isFinished() { return false; } // Called once after isFinished returns true @Override public void end(boolean interrupted) { tankdrivesubsystem.stop(); } // Called when another command which requires one or more of the same // subsystems is scheduled to run } <file_sep>/src/main/java/frc/robot/subsystems/Limelight.java /*----------------------------------------------------------------------------*/ /* Copyright (c) 2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.subsystems; import edu.wpi.first.networktables.NetworkTable; import edu.wpi.first.networktables.NetworkTableEntry; import edu.wpi.first.networktables.NetworkTableInstance; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.SubsystemBase; public class Limelight extends SubsystemBase { /** * Creates a new Limlight. */ NetworkTable table = NetworkTableInstance.getDefault().getTable("limelight"); boolean lightToggle; public Limelight() { lightToggle = true; } public void switchPipelines(int pipline){ table.getEntry("pipeline").setNumber(pipline); } public void turnOn(){ table.getEntry("ledMode").setNumber(3); } public void toggle (){ if (lightToggle) { table.getEntry("pipeline").setNumber(1); table.getEntry("ledMode").setNumber(3); } else { table.getEntry("pipeline").setNumber(0); table.getEntry("ledMode").setNumber(1); } lightToggle = !lightToggle; } public double getXOffset(){ NetworkTable table = NetworkTableInstance.getDefault().getTable("limelight"); NetworkTableEntry tx = table.getEntry("tx"); return tx.getDouble(0); } public double getYOffset(){ NetworkTable table = NetworkTableInstance.getDefault().getTable("limelight"); NetworkTableEntry ty = table.getEntry("ty"); return ty.getDouble(0); } public void display(){ NetworkTableEntry tx = table.getEntry("tx"); NetworkTableEntry ty = table.getEntry("ty"); NetworkTableEntry ta = table.getEntry("ta"); NetworkTableEntry ts = table.getEntry("ts"); //read values periodically double x = tx.getDouble(0.0); double y = ty.getDouble(0.0); double targetArea = ta.getDouble(0.0); double skew = ts.getDouble(0.0); //post to smart dashboard periodically //SmartDashboard.putNumber("LimelightX", x); //SmartDashboard.putNumber("LimelightY", y); //SmartDashboard.putNumber("Target Area", targetArea); //SmartDashboard.putNumber("Skew", skew); double distance = (8-(34/12))/ Math.tan(y); //SmartDashboard.putNumber("Distance to target", distance); } @Override public void periodic() { // This method will be called once per scheduler run display(); } }
a64416c433d6c922423ebba302566d5c83643285
[ "Java" ]
5
Java
BotDogs4645/InfiniteRecharge2020
3dd673c13f1c308de4ec855bff8e486121b2ad21
17e965065070dd1c64c1f7c58c4aa357376a3d46